From 074785cea106179cb3305637055ab0a009ca74f2 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:42:52 -0500 Subject: initial commit --- .../accessibility/aria/aria_techniques/index.html | 215 ++ .../usando_o_role_status/index.html | 82 + files/pt-pt/web/acessibilidade/aria/index.html | 122 + files/pt-pt/web/acessibilidade/index.html | 71 + files/pt-pt/web/api/animation/index.html | 142 + 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/audionode/index.html | 207 + files/pt-pt/web/api/blob/blob/index.html | 77 + files/pt-pt/web/api/blob/index.html | 157 + files/pt-pt/web/api/blob/size/index.html | 73 + files/pt-pt/web/api/blob/type/index.html | 83 + files/pt-pt/web/api/client/index.html | 67 + .../pt-pt/web/api/closeevent/closeevent/index.html | 71 + files/pt-pt/web/api/closeevent/index.html | 195 + files/pt-pt/web/api/document.dir/index.html | 71 + files/pt-pt/web/api/document/index.html | 458 +++ .../web/api/document/queryselector/index.html | 134 + .../api/document/visibilitychange_event/index.html | 148 + files/pt-pt/web/api/domstring/index.html | 43 + .../web/api/eventos_de_luz_ambiente/index.html | 70 + files/pt-pt/web/api/file/file/index.html | 71 + files/pt-pt/web/api/file/filename/index.html | 37 + files/pt-pt/web/api/file/filesize/index.html | 37 + files/pt-pt/web/api/file/getasbinary/index.html | 77 + files/pt-pt/web/api/file/getasdataurl/index.html | 67 + files/pt-pt/web/api/file/getastext/index.html | 83 + files/pt-pt/web/api/file/index.html | 101 + files/pt-pt/web/api/file/lastmodified/index.html | 113 + .../pt-pt/web/api/file/lastmodifieddate/index.html | 80 + files/pt-pt/web/api/file/mozfullpath/index.html | 17 + files/pt-pt/web/api/file/name/index.html | 74 + files/pt-pt/web/api/file/type/index.html | 75 + .../web/api/file/webkitrelativepath/index.html | 80 + files/pt-pt/web/api/filereader/abort/index.html | 58 + files/pt-pt/web/api/filereader/error/index.html | 54 + files/pt-pt/web/api/filereader/index.html | 172 + .../api/filereader/readasarraybuffer/index.html | 64 + .../api/filereader/readasbinarystring/index.html | 85 + .../web/api/filereader/readasdataurl/index.html | 133 + .../pt-pt/web/api/filereader/readastext/index.html | 63 + .../pt-pt/web/api/filereader/readystate/index.html | 96 + files/pt-pt/web/api/filereader/result/index.html | 105 + files/pt-pt/web/api/geolocation/index.html | 223 ++ .../utilizacao_da_geolocalizacao/index.html | 242 ++ files/pt-pt/web/api/index.html | 14 + files/pt-pt/web/api/mathmlelement/index.html | 72 + files/pt-pt/web/api/mediadevices/index.html | 263 ++ files/pt-pt/web/api/messageevent/index.html | 139 + files/pt-pt/web/api/metadados/index.html | 116 + .../eventos_online_e_offline/index.html | 97 + files/pt-pt/web/api/navigatoronline/index.html | 134 + files/pt-pt/web/api/node/index.html | 407 ++ files/pt-pt/web/api/notification/index.html | 316 ++ files/pt-pt/web/api/notifications_api/index.html | 194 + .../index.html" | 289 ++ files/pt-pt/web/api/page_visibility_api/index.html | 271 ++ files/pt-pt/web/api/push_api/index.html | 175 + files/pt-pt/web/api/service_worker_api/index.html | 335 ++ .../using_service_workers/index.html | 459 +++ files/pt-pt/web/api/sharedworker/index.html | 200 + .../pt-pt/web/api/sistema_de_ficheiros/index.html | 54 + files/pt-pt/web/api/urlsearchparams/index.html | 207 + files/pt-pt/web/api/web_audio_api/index.html | 512 +++ .../utilizar_api_audio_web/index.html | 259 ++ .../index.html | 443 +++ files/pt-pt/web/api/web_workers_api/index.html | 234 ++ .../utilizacao_de_web_workers/index.html | 1091 ++++++ .../pt-pt/web/api/webgl_api/constantes/index.html | 4023 ++++++++++++++++++++ files/pt-pt/web/api/webgl_api/dados/index.html | 133 + files/pt-pt/web/api/webgl_api/index.html | 255 ++ files/pt-pt/web/api/webgl_api/tipos/index.html | 242 ++ .../utilizar_extens\303\265es/index.html" | 718 ++++ .../pt-pt/web/api/webglrenderingcontext/index.html | 444 +++ files/pt-pt/web/api/websocket/index.html | 148 + files/pt-pt/web/api/websocket/websocket/index.html | 59 + .../index.html" | 180 + .../escrever_servidores_de_websocket/index.html | 257 ++ .../escrever_um_servidor_websocket_em_c/index.html | 441 +++ .../index.html | 220 ++ files/pt-pt/web/api/websockets_api/index.html | 113 + .../pt-pt/web/api/window/barra_lateral/index.html | 60 + files/pt-pt/web/api/window/console/index.html | 56 + files/pt-pt/web/api/window/index.html | 479 +++ files/pt-pt/web/api/window/open/index.html | 748 ++++ files/pt-pt/web/api/window/postmessage/index.html | 337 ++ files/pt-pt/web/api/worker/index.html | 270 ++ files/pt-pt/web/api/xmlhttprequest/index.html | 174 + files/pt-pt/web/componentes_web/index.html | 226 ++ files/pt-pt/web/css/@font-face/index.html | 143 + files/pt-pt/web/css/@import/index.html | 53 + files/pt-pt/web/css/@media/index.html | 276 ++ 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/at-rule/index.html | 83 + files/pt-pt/web/css/azimuth/index.html | 72 + .../pt-pt/web/css/background-attachment/index.html | 140 + files/pt-pt/web/css/background-color/index.html | 108 + files/pt-pt/web/css/background-image/index.html | 131 + files/pt-pt/web/css/background-position/index.html | 85 + files/pt-pt/web/css/background-repeat/index.html | 138 + files/pt-pt/web/css/background/index.html | 117 + files/pt-pt/web/css/border-bottom-color/index.html | 110 + files/pt-pt/web/css/border-bottom-style/index.html | 94 + files/pt-pt/web/css/border-bottom-width/index.html | 112 + files/pt-pt/web/css/border-bottom/index.html | 109 + files/pt-pt/web/css/border-collapse/index.html | 87 + files/pt-pt/web/css/border-color/index.html | 116 + files/pt-pt/web/css/border-left-color/index.html | 16 + files/pt-pt/web/css/border-left-style/index.html | 16 + files/pt-pt/web/css/border-left-width/index.html | 16 + files/pt-pt/web/css/border-left/index.html | 50 + files/pt-pt/web/css/border-right-color/index.html | 16 + files/pt-pt/web/css/border-right-style/index.html | 16 + files/pt-pt/web/css/border-right-width/index.html | 16 + files/pt-pt/web/css/border-right/index.html | 49 + files/pt-pt/web/css/border-spacing/index.html | 100 + files/pt-pt/web/css/border-top-color/index.html | 16 + files/pt-pt/web/css/border-top-style/index.html | 16 + files/pt-pt/web/css/border-top-width/index.html | 16 + files/pt-pt/web/css/border-top/index.html | 49 + files/pt-pt/web/css/border-width/index.html | 112 + files/pt-pt/web/css/border/index.html | 51 + files/pt-pt/web/css/bottom/index.html | 81 + files/pt-pt/web/css/clear/index.html | 93 + files/pt-pt/web/css/color/index.html | 47 + .../web/css/como_come\303\247ar/caixas/index.html" | 358 ++ .../cascata_e_heran\303\247a/index.html" | 134 + .../como_o_css_trabalha/index.html" | 129 + .../conte\303\272do/index.html" | 188 + .../web/css/como_come\303\247ar/cor/index.html" | 340 ++ .../css_leg\303\255vel/index.html" | 187 + .../css/como_come\303\247ar/dados_xml/index.html" | 239 ++ .../disposi\303\247\303\243o/index.html" | 452 +++ .../estilos_de_texto/index.html" | 157 + .../gr\303\241ficos_svg/index.html" | 215 ++ .../pt-pt/web/css/como_come\303\247ar/index.html" | 91 + .../interfaces_de_usu\303\241rio_xul/index.html" | 336 ++ .../css/como_come\303\247ar/javascript/index.html" | 159 + .../web/css/como_come\303\247ar/listas/index.html" | 361 ++ .../como_come\303\247ar/m\303\255dia/index.html" | 433 +++ .../o_que_\303\251_css/index.html" | 134 + .../o_que_\303\251_css_question_/index.html" | 94 + .../porque_usar_css/index.html" | 110 + .../css/como_come\303\247ar/seletores/index.html" | 207 + .../css/como_come\303\247ar/tabelas/index.html" | 654 ++++ .../web/css/consulta_de_m\303\255dia/index.html" | 436 +++ files/pt-pt/web/css/consultas_de_media/index.html | 110 + files/pt-pt/web/css/content/index.html | 18 + files/pt-pt/web/css/counter-increment/index.html | 66 + files/pt-pt/web/css/counter-reset/index.html | 69 + .../web/css/css_background_and_borders/index.html | 154 + .../m\303\272ltiplos_planos_de_fundo/index.html" | 57 + files/pt-pt/web/css/css_box_model/index.html | 167 + .../introducao_modelo_caixa_css/index.html | 69 + .../css_colors/ferramenta_selecao_cor/index.html | 3243 ++++++++++++++++ files/pt-pt/web/css/css_columns/index.html | 240 ++ .../index.html | 215 ++ .../index.html | 143 + .../web/css/css_flexible_box_layout/index.html | 155 + .../ordenacao_dos_itens_flex/index.html | 140 + .../index.html" | 125 + files/pt-pt/web/css/css_tipos/index.html | 65 + files/pt-pt/web/css/cursor/index.html | 159 + files/pt-pt/web/css/direction/index.html | 46 + files/pt-pt/web/css/display/index.html | 707 ++++ files/pt-pt/web/css/float/index.html | 111 + .../css/folhas_de_estilo_alternativas/index.html | 23 + files/pt-pt/web/css/font-size-adjust/index.html | 75 + files/pt-pt/web/css/font-size/index.html | 83 + files/pt-pt/web/css/font-smooth/index.html | 85 + files/pt-pt/web/css/font-style/index.html | 40 + files/pt-pt/web/css/font-weight/index.html | 119 + files/pt-pt/web/css/font/index.html | 140 + files/pt-pt/web/css/grid-gap/index.html | 177 + files/pt-pt/web/css/height/index.html | 86 + files/pt-pt/web/css/index.html | 105 + files/pt-pt/web/css/inherit/index.html | 7 + .../pt-pt/web/css/layout_de_grelha_css/index.html | 250 ++ files/pt-pt/web/css/list-style/index.html | 79 + .../web/css/m\303\251dia_paginada/index.html" | 19 + files/pt-pt/web/css/pseudoclasses/index.html | 165 + files/pt-pt/web/css/pseudoelementos/index.html | 104 + .../web/css/refer\303\252ncia_css/index.html" | 171 + files/pt-pt/web/css/replaced_element/index.html | 23 + .../pt-pt/web/css/shorthand_properties/index.html | 143 + files/pt-pt/web/css/top/index.html | 54 + files/pt-pt/web/css/transform/index.html | 238 ++ .../index.html" | 34 + files/pt-pt/web/css/width/index.html | 86 + files/pt-pt/web/css/z-index/index.html | 41 + files/pt-pt/web/eventos/index.html | 3080 +++++++++++++++ .../web/guide/ajax/como_come\303\247ar/index.html" | 305 ++ files/pt-pt/web/guide/ajax/comunidade/index.html | 22 + files/pt-pt/web/guide/ajax/index.html | 131 + files/pt-pt/web/guide/eventos/index.html | 133 + "files/pt-pt/web/guide/gr\303\241ficos/index.html" | 50 + .../guide/html/categorias_de_conteudo/index.html | 175 + .../index.html | 343 ++ files/pt-pt/web/guide/index.html | 63 + .../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/cors_settings_attributes/index.html | 87 + 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 + .../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/index.html | 105 + files/pt-pt/web/html/referencia/index.html | 27 + .../web/html/tipos_de_hiperligacao/index.html | 608 +++ .../html/utilizar_a_cache_de_aplicacao/index.html | 342 ++ .../http/cors/errors/corsdidnotsucceed/index.html | 22 + files/pt-pt/web/http/cors/errors/index.html | 76 + files/pt-pt/web/http/cors/index.html | 570 +++ files/pt-pt/web/http/headers/allow/index.html | 67 + files/pt-pt/web/http/headers/index.html | 360 ++ .../http/headers/x-content-type-options/index.html | 83 + files/pt-pt/web/http/index.html | 84 + .../http/proxy_servers_and_tunneling/index.html | 98 + files/pt-pt/web/http/status/205/index.html | 45 + files/pt-pt/web/http/status/405/index.html | 46 + files/pt-pt/web/http/status/502/index.html | 51 + files/pt-pt/web/http/status/504/index.html | 50 + files/pt-pt/web/http/status/index.html | 185 + files/pt-pt/web/index.html | 88 + .../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 +++ files/pt-pt/web/javascript/index.html | 140 + .../javascript/novidades_no_javascript/index.html | 80 + .../novidades_no_javascript_1.8/index.html | 136 + .../o_que_\303\251_o_javascript/index.html" | 13 + .../web/javascript/reference/classes/index.html | 437 +++ .../javascript/reference/classes/static/index.html | 131 + .../index.html" | 113 + .../web/javascript/reference/errors/index.html | 31 + .../reference/errors/not_a_function/index.html | 172 + .../reference/errors/stmt_after_return/index.html | 77 + .../reference/errors/unexpected_token/index.html | 50 + .../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 ++ .../global_objects/array/concat/index.html | 205 + .../reference/global_objects/array/find/index.html | 210 + .../global_objects/array/foreach/index.html | 328 ++ .../global_objects/array/includes/index.html | 175 + .../reference/global_objects/array/index.html | 440 +++ .../reference/global_objects/array/join/index.html | 90 + .../reference/global_objects/array/map/index.html | 366 ++ .../reference/global_objects/array/pop/index.html | 96 + .../global_objects/array/reverse/index.html | 133 + .../global_objects/array/slice/index.html | 154 + .../global_objects/arraybuffer/index.html | 219 ++ .../global_objects/asyncfunction/index.html | 124 + .../asyncfunction/prototype/index.html | 55 + .../reference/global_objects/boolean/index.html | 156 + .../reference/global_objects/encodeuri/index.html | 152 + .../global_objects/function/arguments/index.html | 88 + .../global_objects/function/call/index.html | 164 + .../reference/global_objects/function/index.html | 192 + .../javascript/reference/global_objects/index.html | 173 + .../reference/global_objects/infinity/index.html | 69 + .../reference/global_objects/math/ceil/index.html | 161 + .../reference/global_objects/math/index.html | 214 ++ .../reference/global_objects/number/index.html | 213 ++ .../global_objects/number/isfinite/index.html | 126 + .../global_objects/number/isinteger/index.html | 125 + .../global_objects/number/isnan/index.html | 136 + .../global_objects/number/max_value/index.html | 119 + .../global_objects/number/min_value/index.html | 121 + .../reference/global_objects/number/nan/index.html | 103 + .../number/negative_infinity/index.html | 91 + .../global_objects/number/prototype/index.html | 130 + .../global_objects/number/tostring/index.html | 146 + .../object/hasownproperty/index.html | 187 + .../reference/global_objects/object/index.html | 184 + .../global_objects/object/prototype/index.html | 198 + .../reference/global_objects/string/index.html | 326 ++ .../global_objects/string/indexof/index.html | 191 + .../global_objects/string/length/index.html | 125 + .../global_objects/string/trim/index.html | 139 + .../global_objects/symbol/hasinstance/index.html | 114 + .../reference/global_objects/symbol/index.html | 458 +++ files/pt-pt/web/javascript/reference/index.html | 307 ++ .../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 +++ .../web/javascript/reference/sobre/index.html | 52 + files/pt-pt/web/manifest/index.html | 121 + files/pt-pt/web/mathml/attribute/index.html | 481 +++ .../pt-pt/web/mathml/attribute/valores/index.html | 153 + files/pt-pt/web/mathml/authoring/index.html | 350 ++ files/pt-pt/web/mathml/element/index.html | 234 ++ files/pt-pt/web/mathml/element/maction/index.html | 124 + files/pt-pt/web/mathml/element/math/index.html | 161 + files/pt-pt/web/mathml/element/menclose/index.html | 196 + files/pt-pt/web/mathml/element/merror/index.html | 73 + files/pt-pt/web/mathml/element/mfenced/index.html | 81 + files/pt-pt/web/mathml/element/mfrac/index.html | 92 + files/pt-pt/web/mathml/element/mglyph/index.html | 72 + files/pt-pt/web/mathml/element/mi/index.html | 114 + .../pt-pt/web/mathml/element/mlabeledtr/index.html | 99 + .../web/mathml/element/mmultiscripts/index.html | 131 + files/pt-pt/web/mathml/element/mn/index.html | 116 + files/pt-pt/web/mathml/element/mo/index.html | 171 + files/pt-pt/web/mathml/element/mover/index.html | 91 + files/pt-pt/web/mathml/element/mpadded/index.html | 96 + files/pt-pt/web/mathml/element/mphantom/index.html | 80 + files/pt-pt/web/mathml/element/mroot/index.html | 78 + files/pt-pt/web/mathml/element/mrow/index.html | 95 + files/pt-pt/web/mathml/element/ms/index.html | 112 + files/pt-pt/web/mathml/element/mspace/index.html | 88 + files/pt-pt/web/mathml/element/msqrt/index.html | 77 + files/pt-pt/web/mathml/element/mstyle/index.html | 126 + files/pt-pt/web/mathml/element/msub/index.html | 85 + files/pt-pt/web/mathml/element/msubsup/index.html | 89 + files/pt-pt/web/mathml/element/msup/index.html | 85 + files/pt-pt/web/mathml/element/mtable/index.html | 140 + files/pt-pt/web/mathml/element/mtd/index.html | 75 + files/pt-pt/web/mathml/element/mtext/index.html | 113 + files/pt-pt/web/mathml/element/mtr/index.html | 71 + files/pt-pt/web/mathml/element/munder/index.html | 91 + .../pt-pt/web/mathml/element/munderover/index.html | 91 + .../pt-pt/web/mathml/element/semantics/index.html | 127 + .../derivar_a_formula_resolvente/index.html | 17 + files/pt-pt/web/mathml/examples/index.html | 22 + .../mathml_teorema_de_pitagoras/index.html | 19 + files/pt-pt/web/mathml/index.html | 72 + files/pt-pt/web/mathml/index/index.html | 11 + .../guia_de_programacao/index.html | 77 + .../progressive_web_apps/identificavel/index.html | 61 + files/pt-pt/web/progressive_web_apps/index.html | 107 + .../elementos_base_desenho_adaptavel/index.html | 428 +++ .../web/progressive_web_apps/responsivo/index.html | 155 + .../web/progressive_web_apps/seguro/index.html | 34 + files/pt-pt/web/reference/api/index.html | 57 + files/pt-pt/web/reference/index.html | 28 + files/pt-pt/web/security/conteudo_misto/index.html | 80 + .../index.html | 30 + .../pt-pt/web/security/secure_contexts/index.html | 202 + 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 ++ files/pt-pt/web/svg/element/index.html | 298 ++ files/pt-pt/web/svg/index.html | 95 + .../svg/namespaces_crash_course/exemplo/index.html | 394 ++ .../web/svg/namespaces_crash_course/index.html | 266 ++ .../pt-pt/web/svg/svg_animacao_com_smil/index.html | 125 + files/pt-pt/web/svg/tutorial/index.html | 32 + files/pt-pt/web/svg/tutorial/introducao/index.html | 52 + .../svg/tutorial/svg_na_introducao_html/index.html | 179 + files/pt-pt/web/tutoriais/index.html | 252 ++ files/pt-pt/web/webapi/index.html | 213 ++ files/pt-pt/web/xml/index.html | 15 + files/pt-pt/web/xml/introducao_a_xml/index.html | 204 + files/pt-pt/web/xslt/comunidade/index.html | 8 + files/pt-pt/web/xslt/elementos/index.html | 59 + files/pt-pt/web/xslt/index.html | 56 + 392 files changed, 74821 insertions(+) create mode 100644 files/pt-pt/web/accessibility/aria/aria_techniques/index.html create mode 100644 files/pt-pt/web/accessibility/aria/aria_techniques/usando_o_role_status/index.html create mode 100644 files/pt-pt/web/acessibilidade/aria/index.html create mode 100644 files/pt-pt/web/acessibilidade/index.html create mode 100644 files/pt-pt/web/api/animation/index.html create mode 100644 files/pt-pt/web/api/api_armazenamento/index.html create mode 100644 files/pt-pt/web/api/api_autenticacao_web/index.html create mode 100644 files/pt-pt/web/api/api_de_armazenamento_da_web/index.html create mode 100644 files/pt-pt/web/api/api_de_canvas/index.html create mode 100644 files/pt-pt/web/api/api_de_canvas/tutorial/index.html create mode 100644 files/pt-pt/web/api/api_do_estado_da_bateria/index.html create mode 100644 files/pt-pt/web/api/api_entradas_de_diretoria_e_ficheiro/index.html create mode 100644 files/pt-pt/web/api/api_transmissoes_multimedia/index.html create mode 100644 files/pt-pt/web/api/api_webrtc/index.html create mode 100644 files/pt-pt/web/api/api_webrtc/tirar_fotografias/index.html create mode 100644 files/pt-pt/web/api/audionode/index.html create mode 100644 files/pt-pt/web/api/blob/blob/index.html create mode 100644 files/pt-pt/web/api/blob/index.html create mode 100644 files/pt-pt/web/api/blob/size/index.html create mode 100644 files/pt-pt/web/api/blob/type/index.html create mode 100644 files/pt-pt/web/api/client/index.html create mode 100644 files/pt-pt/web/api/closeevent/closeevent/index.html create mode 100644 files/pt-pt/web/api/closeevent/index.html create mode 100644 files/pt-pt/web/api/document.dir/index.html create mode 100644 files/pt-pt/web/api/document/index.html create mode 100644 files/pt-pt/web/api/document/queryselector/index.html create mode 100644 files/pt-pt/web/api/document/visibilitychange_event/index.html create mode 100644 files/pt-pt/web/api/domstring/index.html create mode 100644 files/pt-pt/web/api/eventos_de_luz_ambiente/index.html create mode 100644 files/pt-pt/web/api/file/file/index.html create mode 100644 files/pt-pt/web/api/file/filename/index.html create mode 100644 files/pt-pt/web/api/file/filesize/index.html create mode 100644 files/pt-pt/web/api/file/getasbinary/index.html create mode 100644 files/pt-pt/web/api/file/getasdataurl/index.html create mode 100644 files/pt-pt/web/api/file/getastext/index.html create mode 100644 files/pt-pt/web/api/file/index.html create mode 100644 files/pt-pt/web/api/file/lastmodified/index.html create mode 100644 files/pt-pt/web/api/file/lastmodifieddate/index.html create mode 100644 files/pt-pt/web/api/file/mozfullpath/index.html create mode 100644 files/pt-pt/web/api/file/name/index.html create mode 100644 files/pt-pt/web/api/file/type/index.html create mode 100644 files/pt-pt/web/api/file/webkitrelativepath/index.html create mode 100644 files/pt-pt/web/api/filereader/abort/index.html create mode 100644 files/pt-pt/web/api/filereader/error/index.html create mode 100644 files/pt-pt/web/api/filereader/index.html create mode 100644 files/pt-pt/web/api/filereader/readasarraybuffer/index.html create mode 100644 files/pt-pt/web/api/filereader/readasbinarystring/index.html create mode 100644 files/pt-pt/web/api/filereader/readasdataurl/index.html create mode 100644 files/pt-pt/web/api/filereader/readastext/index.html create mode 100644 files/pt-pt/web/api/filereader/readystate/index.html create mode 100644 files/pt-pt/web/api/filereader/result/index.html create mode 100644 files/pt-pt/web/api/geolocation/index.html create mode 100644 files/pt-pt/web/api/geolocation/utilizacao_da_geolocalizacao/index.html create mode 100644 files/pt-pt/web/api/index.html create mode 100644 files/pt-pt/web/api/mathmlelement/index.html create mode 100644 files/pt-pt/web/api/mediadevices/index.html create mode 100644 files/pt-pt/web/api/messageevent/index.html create mode 100644 files/pt-pt/web/api/metadados/index.html create mode 100644 files/pt-pt/web/api/navigatoronline/eventos_online_e_offline/index.html create mode 100644 files/pt-pt/web/api/navigatoronline/index.html create mode 100644 files/pt-pt/web/api/node/index.html create mode 100644 files/pt-pt/web/api/notification/index.html create mode 100644 files/pt-pt/web/api/notifications_api/index.html create 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/page_visibility_api/index.html create mode 100644 files/pt-pt/web/api/push_api/index.html create mode 100644 files/pt-pt/web/api/service_worker_api/index.html create mode 100644 files/pt-pt/web/api/service_worker_api/using_service_workers/index.html create mode 100644 files/pt-pt/web/api/sharedworker/index.html create mode 100644 files/pt-pt/web/api/sistema_de_ficheiros/index.html create mode 100644 files/pt-pt/web/api/urlsearchparams/index.html create mode 100644 files/pt-pt/web/api/web_audio_api/index.html create 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_workers_api/functions_and_classes_available_to_workers/index.html create mode 100644 files/pt-pt/web/api/web_workers_api/index.html create mode 100644 files/pt-pt/web/api/web_workers_api/utilizacao_de_web_workers/index.html create mode 100644 files/pt-pt/web/api/webgl_api/constantes/index.html create mode 100644 files/pt-pt/web/api/webgl_api/dados/index.html create mode 100644 files/pt-pt/web/api/webgl_api/index.html create mode 100644 files/pt-pt/web/api/webgl_api/tipos/index.html create mode 100644 "files/pt-pt/web/api/webgl_api/utilizar_extens\303\265es/index.html" create mode 100644 files/pt-pt/web/api/webglrenderingcontext/index.html create mode 100644 files/pt-pt/web/api/websocket/index.html create mode 100644 files/pt-pt/web/api/websocket/websocket/index.html create mode 100644 "files/pt-pt/web/api/websockets_api/escrever_aplica\303\247\303\243o_cliente_de_websocket/index.html" create mode 100644 files/pt-pt/web/api/websockets_api/escrever_servidores_de_websocket/index.html create mode 100644 files/pt-pt/web/api/websockets_api/escrever_um_servidor_websocket_em_c/index.html create 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/index.html create mode 100644 files/pt-pt/web/api/window/barra_lateral/index.html create mode 100644 files/pt-pt/web/api/window/console/index.html create mode 100644 files/pt-pt/web/api/window/index.html create mode 100644 files/pt-pt/web/api/window/open/index.html create mode 100644 files/pt-pt/web/api/window/postmessage/index.html create mode 100644 files/pt-pt/web/api/worker/index.html create mode 100644 files/pt-pt/web/api/xmlhttprequest/index.html create mode 100644 files/pt-pt/web/componentes_web/index.html create mode 100644 files/pt-pt/web/css/@font-face/index.html create mode 100644 files/pt-pt/web/css/@import/index.html create mode 100644 files/pt-pt/web/css/@media/index.html create mode 100644 files/pt-pt/web/css/_colon_after/index.html create mode 100644 files/pt-pt/web/css/_colon_before/index.html create mode 100644 files/pt-pt/web/css/at-rule/index.html create mode 100644 files/pt-pt/web/css/azimuth/index.html create mode 100644 files/pt-pt/web/css/background-attachment/index.html create mode 100644 files/pt-pt/web/css/background-color/index.html create mode 100644 files/pt-pt/web/css/background-image/index.html create mode 100644 files/pt-pt/web/css/background-position/index.html create mode 100644 files/pt-pt/web/css/background-repeat/index.html create mode 100644 files/pt-pt/web/css/background/index.html create mode 100644 files/pt-pt/web/css/border-bottom-color/index.html create mode 100644 files/pt-pt/web/css/border-bottom-style/index.html create mode 100644 files/pt-pt/web/css/border-bottom-width/index.html create mode 100644 files/pt-pt/web/css/border-bottom/index.html create mode 100644 files/pt-pt/web/css/border-collapse/index.html create mode 100644 files/pt-pt/web/css/border-color/index.html create mode 100644 files/pt-pt/web/css/border-left-color/index.html create mode 100644 files/pt-pt/web/css/border-left-style/index.html create mode 100644 files/pt-pt/web/css/border-left-width/index.html create mode 100644 files/pt-pt/web/css/border-left/index.html create mode 100644 files/pt-pt/web/css/border-right-color/index.html create mode 100644 files/pt-pt/web/css/border-right-style/index.html create mode 100644 files/pt-pt/web/css/border-right-width/index.html create mode 100644 files/pt-pt/web/css/border-right/index.html create mode 100644 files/pt-pt/web/css/border-spacing/index.html create mode 100644 files/pt-pt/web/css/border-top-color/index.html create mode 100644 files/pt-pt/web/css/border-top-style/index.html create mode 100644 files/pt-pt/web/css/border-top-width/index.html create mode 100644 files/pt-pt/web/css/border-top/index.html create mode 100644 files/pt-pt/web/css/border-width/index.html create mode 100644 files/pt-pt/web/css/border/index.html create mode 100644 files/pt-pt/web/css/bottom/index.html create mode 100644 files/pt-pt/web/css/clear/index.html create mode 100644 files/pt-pt/web/css/color/index.html create mode 100644 "files/pt-pt/web/css/como_come\303\247ar/caixas/index.html" create mode 100644 "files/pt-pt/web/css/como_come\303\247ar/cascata_e_heran\303\247a/index.html" create mode 100644 "files/pt-pt/web/css/como_come\303\247ar/como_o_css_trabalha/index.html" create mode 100644 "files/pt-pt/web/css/como_come\303\247ar/conte\303\272do/index.html" create mode 100644 "files/pt-pt/web/css/como_come\303\247ar/cor/index.html" create mode 100644 "files/pt-pt/web/css/como_come\303\247ar/css_leg\303\255vel/index.html" create mode 100644 "files/pt-pt/web/css/como_come\303\247ar/dados_xml/index.html" create mode 100644 "files/pt-pt/web/css/como_come\303\247ar/disposi\303\247\303\243o/index.html" create mode 100644 "files/pt-pt/web/css/como_come\303\247ar/estilos_de_texto/index.html" create mode 100644 "files/pt-pt/web/css/como_come\303\247ar/gr\303\241ficos_svg/index.html" create mode 100644 "files/pt-pt/web/css/como_come\303\247ar/index.html" create mode 100644 "files/pt-pt/web/css/como_come\303\247ar/interfaces_de_usu\303\241rio_xul/index.html" create mode 100644 "files/pt-pt/web/css/como_come\303\247ar/javascript/index.html" create mode 100644 "files/pt-pt/web/css/como_come\303\247ar/listas/index.html" create mode 100644 "files/pt-pt/web/css/como_come\303\247ar/m\303\255dia/index.html" create mode 100644 "files/pt-pt/web/css/como_come\303\247ar/o_que_\303\251_css/index.html" create mode 100644 "files/pt-pt/web/css/como_come\303\247ar/o_que_\303\251_css_question_/index.html" create mode 100644 "files/pt-pt/web/css/como_come\303\247ar/porque_usar_css/index.html" create mode 100644 "files/pt-pt/web/css/como_come\303\247ar/seletores/index.html" create mode 100644 "files/pt-pt/web/css/como_come\303\247ar/tabelas/index.html" create mode 100644 "files/pt-pt/web/css/consulta_de_m\303\255dia/index.html" create mode 100644 files/pt-pt/web/css/consultas_de_media/index.html create mode 100644 files/pt-pt/web/css/content/index.html create mode 100644 files/pt-pt/web/css/counter-increment/index.html create mode 100644 files/pt-pt/web/css/counter-reset/index.html create mode 100644 files/pt-pt/web/css/css_background_and_borders/index.html create 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_box_model/index.html create 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_colors/ferramenta_selecao_cor/index.html create mode 100644 files/pt-pt/web/css/css_columns/index.html create mode 100644 files/pt-pt/web/css/css_flexible_box_layout/alinhamento_de_itens_num_recipiente_flex/index.html create mode 100644 files/pt-pt/web/css/css_flexible_box_layout/casos_de_utilizacao_tipicos_do_flexbox/index.html create mode 100644 files/pt-pt/web/css/css_flexible_box_layout/index.html create 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/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_tipos/index.html create mode 100644 files/pt-pt/web/css/cursor/index.html create mode 100644 files/pt-pt/web/css/direction/index.html create mode 100644 files/pt-pt/web/css/display/index.html create mode 100644 files/pt-pt/web/css/float/index.html create mode 100644 files/pt-pt/web/css/folhas_de_estilo_alternativas/index.html create mode 100644 files/pt-pt/web/css/font-size-adjust/index.html create mode 100644 files/pt-pt/web/css/font-size/index.html create mode 100644 files/pt-pt/web/css/font-smooth/index.html create mode 100644 files/pt-pt/web/css/font-style/index.html create mode 100644 files/pt-pt/web/css/font-weight/index.html create mode 100644 files/pt-pt/web/css/font/index.html create mode 100644 files/pt-pt/web/css/grid-gap/index.html create mode 100644 files/pt-pt/web/css/height/index.html create mode 100644 files/pt-pt/web/css/index.html create mode 100644 files/pt-pt/web/css/inherit/index.html create mode 100644 files/pt-pt/web/css/layout_de_grelha_css/index.html create mode 100644 files/pt-pt/web/css/list-style/index.html create mode 100644 "files/pt-pt/web/css/m\303\251dia_paginada/index.html" create mode 100644 files/pt-pt/web/css/pseudoclasses/index.html create mode 100644 files/pt-pt/web/css/pseudoelementos/index.html create mode 100644 "files/pt-pt/web/css/refer\303\252ncia_css/index.html" create mode 100644 files/pt-pt/web/css/replaced_element/index.html create mode 100644 files/pt-pt/web/css/shorthand_properties/index.html create mode 100644 files/pt-pt/web/css/top/index.html create mode 100644 files/pt-pt/web/css/transform/index.html create mode 100644 "files/pt-pt/web/css/usando_transforma\303\247\303\265es_css/index.html" create mode 100644 files/pt-pt/web/css/width/index.html create mode 100644 files/pt-pt/web/css/z-index/index.html create mode 100644 files/pt-pt/web/eventos/index.html create mode 100644 "files/pt-pt/web/guide/ajax/como_come\303\247ar/index.html" create mode 100644 files/pt-pt/web/guide/ajax/comunidade/index.html create mode 100644 files/pt-pt/web/guide/ajax/index.html create mode 100644 files/pt-pt/web/guide/eventos/index.html create mode 100644 "files/pt-pt/web/guide/gr\303\241ficos/index.html" create mode 100644 files/pt-pt/web/guide/html/categorias_de_conteudo/index.html create mode 100644 files/pt-pt/web/guide/html/utilizar_estruturas_e_seccoes_de_html/index.html create mode 100644 files/pt-pt/web/guide/index.html create mode 100644 files/pt-pt/web/html/aplicar_cor_elementos_html_utilizando_css/index.html create mode 100644 files/pt-pt/web/html/atributos/index.html create mode 100644 files/pt-pt/web/html/atributos/rel/index.html create mode 100644 files/pt-pt/web/html/atributos_globais/index.html create mode 100644 files/pt-pt/web/html/cors_settings_attributes/index.html create mode 100644 files/pt-pt/web/html/elemento/audio/index.html create mode 100644 files/pt-pt/web/html/elemento/fieldset/index.html create mode 100644 files/pt-pt/web/html/elemento/figcaption/index.html create mode 100644 files/pt-pt/web/html/elemento/head/index.html create mode 100644 files/pt-pt/web/html/elemento/index.html create mode 100644 files/pt-pt/web/html/elemento/nav/index.html create mode 100644 files/pt-pt/web/html/elemento/progress/index.html create mode 100644 files/pt-pt/web/html/elemento/video/index.html create mode 100644 files/pt-pt/web/html/html5/forms_no_html5/index.html create mode 100644 files/pt-pt/web/html/html5/index.html create mode 100644 "files/pt-pt/web/html/html5/introdu\303\247\303\243o_ao_html5/index.html" create mode 100644 files/pt-pt/web/html/html5/parser_html5/index.html create mode 100644 files/pt-pt/web/html/index.html create mode 100644 files/pt-pt/web/html/referencia/index.html create mode 100644 files/pt-pt/web/html/tipos_de_hiperligacao/index.html create mode 100644 files/pt-pt/web/html/utilizar_a_cache_de_aplicacao/index.html create mode 100644 files/pt-pt/web/http/cors/errors/corsdidnotsucceed/index.html create mode 100644 files/pt-pt/web/http/cors/errors/index.html create mode 100644 files/pt-pt/web/http/cors/index.html create mode 100644 files/pt-pt/web/http/headers/allow/index.html create mode 100644 files/pt-pt/web/http/headers/index.html create mode 100644 files/pt-pt/web/http/headers/x-content-type-options/index.html create mode 100644 files/pt-pt/web/http/index.html create mode 100644 files/pt-pt/web/http/proxy_servers_and_tunneling/index.html create mode 100644 files/pt-pt/web/http/status/205/index.html create mode 100644 files/pt-pt/web/http/status/405/index.html create mode 100644 files/pt-pt/web/http/status/502/index.html create mode 100644 files/pt-pt/web/http/status/504/index.html create mode 100644 files/pt-pt/web/http/status/index.html create mode 100644 files/pt-pt/web/index.html create mode 100644 files/pt-pt/web/javascript/estruturas_de_dados/index.html create mode 100644 files/pt-pt/web/javascript/gestao_memoria/index.html create mode 100644 files/pt-pt/web/javascript/guia/detalhes_do_modelo_de_objeto/index.html create mode 100644 files/pt-pt/web/javascript/guia/expressoes_e_operadores/index.html create mode 100644 "files/pt-pt/web/javascript/guia/gram\303\241tica_e_tipos/index.html" create mode 100644 files/pt-pt/web/javascript/guia/index.html create mode 100644 "files/pt-pt/web/javascript/guia/introdu\303\247\303\243o/index.html" create mode 100644 "files/pt-pt/web/javascript/guia/introdu\303\247\303\243o_ao_javascript/index.html" create mode 100644 files/pt-pt/web/javascript/guia/sobre/index.html create mode 100644 "files/pt-pt/web/javascript/guia/valores,_vari\303\241veis_e_literais/index.html" create mode 100644 files/pt-pt/web/javascript/index.html create mode 100644 files/pt-pt/web/javascript/novidades_no_javascript/index.html create mode 100644 files/pt-pt/web/javascript/novidades_no_javascript/novidades_no_javascript_1.8/index.html create mode 100644 "files/pt-pt/web/javascript/o_que_\303\251_o_javascript/index.html" create mode 100644 files/pt-pt/web/javascript/reference/classes/index.html create mode 100644 files/pt-pt/web/javascript/reference/classes/static/index.html create 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/index.html create mode 100644 files/pt-pt/web/javascript/reference/errors/not_a_function/index.html create mode 100644 files/pt-pt/web/javascript/reference/errors/stmt_after_return/index.html create mode 100644 files/pt-pt/web/javascript/reference/errors/unexpected_token/index.html create mode 100644 "files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/bloco/index.html" create mode 100644 "files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/for/index.html" create mode 100644 "files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/index.html" create mode 100644 "files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/return/index.html" create mode 100644 "files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/throw/index.html" create mode 100644 files/pt-pt/web/javascript/reference/funcionalidades_obsoletas/index.html create mode 100644 files/pt-pt/web/javascript/reference/funcoes/arguments/index.html create mode 100644 files/pt-pt/web/javascript/reference/funcoes/funcoes_seta/index.html create mode 100644 files/pt-pt/web/javascript/reference/funcoes/index.html create mode 100644 files/pt-pt/web/javascript/reference/funcoes/parametros_rest/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/array/concat/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/array/find/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/array/foreach/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/array/includes/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/array/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/array/join/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/array/map/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/array/pop/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/array/reverse/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/array/slice/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/arraybuffer/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/asyncfunction/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/asyncfunction/prototype/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/boolean/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/encodeuri/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/function/arguments/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/function/call/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/function/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/infinity/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/math/ceil/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/math/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/number/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/number/isfinite/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/number/isinteger/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/number/isnan/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/number/max_value/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/number/min_value/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/number/nan/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/number/negative_infinity/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/number/prototype/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/number/tostring/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/object/hasownproperty/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/object/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/object/prototype/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/string/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/string/indexof/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/string/length/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/string/trim/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/symbol/hasinstance/index.html create mode 100644 files/pt-pt/web/javascript/reference/global_objects/symbol/index.html create mode 100644 files/pt-pt/web/javascript/reference/index.html create mode 100644 "files/pt-pt/web/javascript/reference/operadores/fun\303\247\303\243o/index.html" create mode 100644 files/pt-pt/web/javascript/reference/operadores/index.html create mode 100644 files/pt-pt/web/javascript/reference/operadores/operador_virgula/index.html create mode 100644 files/pt-pt/web/javascript/reference/operadores/precedencia_operador/index.html create mode 100644 files/pt-pt/web/javascript/reference/sobre/index.html create mode 100644 files/pt-pt/web/manifest/index.html create mode 100644 files/pt-pt/web/mathml/attribute/index.html create mode 100644 files/pt-pt/web/mathml/attribute/valores/index.html create mode 100644 files/pt-pt/web/mathml/authoring/index.html create mode 100644 files/pt-pt/web/mathml/element/index.html create mode 100644 files/pt-pt/web/mathml/element/maction/index.html create mode 100644 files/pt-pt/web/mathml/element/math/index.html create mode 100644 files/pt-pt/web/mathml/element/menclose/index.html create mode 100644 files/pt-pt/web/mathml/element/merror/index.html create mode 100644 files/pt-pt/web/mathml/element/mfenced/index.html create mode 100644 files/pt-pt/web/mathml/element/mfrac/index.html create mode 100644 files/pt-pt/web/mathml/element/mglyph/index.html create mode 100644 files/pt-pt/web/mathml/element/mi/index.html create mode 100644 files/pt-pt/web/mathml/element/mlabeledtr/index.html create mode 100644 files/pt-pt/web/mathml/element/mmultiscripts/index.html create mode 100644 files/pt-pt/web/mathml/element/mn/index.html create mode 100644 files/pt-pt/web/mathml/element/mo/index.html create mode 100644 files/pt-pt/web/mathml/element/mover/index.html create mode 100644 files/pt-pt/web/mathml/element/mpadded/index.html create mode 100644 files/pt-pt/web/mathml/element/mphantom/index.html create mode 100644 files/pt-pt/web/mathml/element/mroot/index.html create mode 100644 files/pt-pt/web/mathml/element/mrow/index.html create mode 100644 files/pt-pt/web/mathml/element/ms/index.html create mode 100644 files/pt-pt/web/mathml/element/mspace/index.html create mode 100644 files/pt-pt/web/mathml/element/msqrt/index.html create mode 100644 files/pt-pt/web/mathml/element/mstyle/index.html create mode 100644 files/pt-pt/web/mathml/element/msub/index.html create mode 100644 files/pt-pt/web/mathml/element/msubsup/index.html create mode 100644 files/pt-pt/web/mathml/element/msup/index.html create mode 100644 files/pt-pt/web/mathml/element/mtable/index.html create mode 100644 files/pt-pt/web/mathml/element/mtd/index.html create mode 100644 files/pt-pt/web/mathml/element/mtext/index.html create mode 100644 files/pt-pt/web/mathml/element/mtr/index.html create mode 100644 files/pt-pt/web/mathml/element/munder/index.html create mode 100644 files/pt-pt/web/mathml/element/munderover/index.html create mode 100644 files/pt-pt/web/mathml/element/semantics/index.html create mode 100644 files/pt-pt/web/mathml/examples/derivar_a_formula_resolvente/index.html create mode 100644 files/pt-pt/web/mathml/examples/index.html create mode 100644 files/pt-pt/web/mathml/examples/mathml_teorema_de_pitagoras/index.html create mode 100644 files/pt-pt/web/mathml/index.html create mode 100644 files/pt-pt/web/mathml/index/index.html create mode 100644 files/pt-pt/web/progressive_web_apps/guia_de_programacao/index.html create mode 100644 files/pt-pt/web/progressive_web_apps/identificavel/index.html create mode 100644 files/pt-pt/web/progressive_web_apps/index.html create mode 100644 files/pt-pt/web/progressive_web_apps/responsivo/elementos_base_desenho_adaptavel/index.html create mode 100644 files/pt-pt/web/progressive_web_apps/responsivo/index.html create mode 100644 files/pt-pt/web/progressive_web_apps/seguro/index.html create mode 100644 files/pt-pt/web/reference/api/index.html create mode 100644 files/pt-pt/web/reference/index.html create mode 100644 files/pt-pt/web/security/conteudo_misto/index.html create 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/secure_contexts/index.html create mode 100644 files/pt-pt/web/seguranca/index.html create mode 100644 files/pt-pt/web/seguranca/palavras-passe_inseguras/index.html create mode 100644 files/pt-pt/web/seguranca/same-origin_policy/index.html create mode 100644 files/pt-pt/web/svg/aplicar_efeitos_svg_conteudo_html/index.html create mode 100644 files/pt-pt/web/svg/element/index.html create mode 100644 files/pt-pt/web/svg/index.html create mode 100644 files/pt-pt/web/svg/namespaces_crash_course/exemplo/index.html create mode 100644 files/pt-pt/web/svg/namespaces_crash_course/index.html create mode 100644 files/pt-pt/web/svg/svg_animacao_com_smil/index.html create mode 100644 files/pt-pt/web/svg/tutorial/index.html create mode 100644 files/pt-pt/web/svg/tutorial/introducao/index.html create mode 100644 files/pt-pt/web/svg/tutorial/svg_na_introducao_html/index.html create mode 100644 files/pt-pt/web/tutoriais/index.html create mode 100644 files/pt-pt/web/webapi/index.html create mode 100644 files/pt-pt/web/xml/index.html create mode 100644 files/pt-pt/web/xml/introducao_a_xml/index.html create mode 100644 files/pt-pt/web/xslt/comunidade/index.html create mode 100644 files/pt-pt/web/xslt/elementos/index.html create mode 100644 files/pt-pt/web/xslt/index.html (limited to 'files/pt-pt/web') diff --git a/files/pt-pt/web/accessibility/aria/aria_techniques/index.html b/files/pt-pt/web/accessibility/aria/aria_techniques/index.html new file mode 100644 index 0000000000..34fa824f8c --- /dev/null +++ b/files/pt-pt/web/accessibility/aria/aria_techniques/index.html @@ -0,0 +1,215 @@ +--- +title: 'Using ARIA: Roles, states, and properties' +slug: Web/Accessibility/ARIA/ARIA_Techniques +tags: + - ARIA + - Accessibility + - NeedsTranslation + - Overview + - Reference + - TopicStub +translation_of: Web/Accessibility/ARIA/ARIA_Techniques +--- +

ARIA defines semantics that can be applied to elements, with these divided into roles (defining a type of user interface element) and states and properties that are supported by a role. Authors must assign an ARIA role and the appropriate states and properties to an element during its life-cycle, unless the element already has appropriate ARIA semantics (via use of an appropriate HTML element). Addition of ARIA semantics only exposes extra information to a browser's accessibility API, and does not affect a page's DOM.

+ +

Roles

+ +

Widget roles

+ +
+ +
+ +

Composite roles

+ +

The techniques below describe each composite role as well as their required and optional child roles.

+ +
+ +
+ +

Document structure roles

+ +
+ +
+ +

Landmark roles

+ +
+ +
+ +

Live Region Roles

+ +
+ +
+ +

Window Roles

+ +
+ +
+ +

States and properties

+ +

Widget attributes

+ +
+ +
+ +

Live region attributes

+ +
+ +
+ +

Drag & drop attributes

+ +
+ +
+ +

Relationship attributes

+ +
+ +
+ +

MicrosoftEdge-specific properties

+ +
+ +
diff --git a/files/pt-pt/web/accessibility/aria/aria_techniques/usando_o_role_status/index.html b/files/pt-pt/web/accessibility/aria/aria_techniques/usando_o_role_status/index.html new file mode 100644 index 0000000000..23374a0329 --- /dev/null +++ b/files/pt-pt/web/accessibility/aria/aria_techniques/usando_o_role_status/index.html @@ -0,0 +1,82 @@ +--- +title: Utilizar o role status +slug: Web/Accessibility/ARIA/ARIA_Techniques/Usando_o_role_status +tags: + - ARIA + - Acessibilidade + - RequerConteúdo +translation_of: Web/Accessibility/ARIA/ARIA_Techniques/Using_the_status_role +--- +

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/acessibilidade/aria/index.html b/files/pt-pt/web/acessibilidade/aria/index.html new file mode 100644 index 0000000000..d49bc53276 --- /dev/null +++ b/files/pt-pt/web/acessibilidade/aria/index.html @@ -0,0 +1,122 @@ +--- +title: ARIA +slug: Web/Acessibilidade/ARIA +tags: + - ARIA + - Acessibilidade + - Web +translation_of: Web/Accessibility/ARIA +--- +

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 new file mode 100644 index 0000000000..0bf23a4fc9 --- /dev/null +++ b/files/pt-pt/web/acessibilidade/index.html @@ -0,0 +1,71 @@ +--- +title: Acessibilidade +slug: Web/Acessibilidade +tags: + - Acessibilidade +translation_of: Web/Accessibility +--- +

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/animation/index.html b/files/pt-pt/web/api/animation/index.html new file mode 100644 index 0000000000..3921533613 --- /dev/null +++ b/files/pt-pt/web/api/animation/index.html @@ -0,0 +1,142 @@ +--- +title: Animation +slug: Web/API/Animation +tags: + - API + - Animations + - Animações da Web + - Experimental + - Interface + - Referencia + - api de animações da web + - waapi +translation_of: Web/API/Animation +--- +
{{ APIRef("Web Animations") }}{{SeeCompatTable}}
+ +

The Animation interface of the Web Animations API represents a single animation player and provides playback controls and a timeline for an animation node or source.

+ +

Construtor

+ +
+
{{domxref("Animation.Animation()", "Animation()")}}
+
Creates a new Animation object instance.
+
+ +

Propriedades

+ +
+
{{domxref("Animation.currentTime")}}
+
The current time value of the animation in milliseconds, whether running or paused. If the animation lacks a {{domxref("AnimationTimeline", "timeline")}}, is inactive or hasn't been played yet, its value is null.
+
+ +
+
{{domxref("Animation.effect")}}
+
Gets and sets the {{domxref("AnimationEffectReadOnly")}} associated with this animation. This will usually be a {{domxref("KeyframeEffect")}} object.
+
{{domxref("Animation.finished")}} {{readOnlyInline}}
+
Returns the current finished Promise for this animation.
+
+ +
+
{{domxref("Animation.id")}}
+
Gets and sets the String used to identify the animation.
+
{{domxref("Animation.pending")}} {{readonlyinline}}
+
Indicates whether the animation is currently waiting for an asynchronous operation such as initiating playback or pausing a running animation.
+
{{domxref("Animation.playState")}} {{readOnlyInline}}
+
Returns an enumerated value describing the playback state of an animation.
+
+ +
+
{{domxref("Animation.playbackRate")}}
+
Gets or sets the playback rate of the animation.
+
+ +
+
{{domxref("Animation.ready")}} {{readOnlyInline}}
+
Returns the current ready Promise for this animation.
+
+ +
+
{{domxref("Animation.startTime")}}
+
Gets or sets the scheduled time when an animation's playback should begin.
+
+ +
+
{{domxref("Animation.timeline")}}
+
Gets or sets the {{domxref("AnimationTimeline", "timeline")}} associated with this animation.
+
+ +

Manipuladores de evento

+ +
+
{{domxref("Animation.oncancel")}}
+
Gets and sets the event handler for the cancel event.
+
{{domxref("Animation.onfinish")}}
+
Gets and sets the event handler for the finish event.
+
+ +

Métodos

+ +
+
{{domxref("Animation.cancel()")}}
+
Clears all {{domxref("KeyframeEffect", "keyframeEffects")}} caused by this animation and aborts its playback.
+
+ +
+
{{domxref("Animation.finish()")}}
+
Seeks either end of an animation, depending on whether the animation is playing or reversing.
+
+ +
+
{{domxref("Animation.pause()")}}
+
Suspends playing of an animation.
+
+ +
+
{{domxref("Animation.play()")}}
+
Starts or resumes playing of an animation, or begins the animation again if it previously finished.
+
+ +
+
{{domxref("Animation.reverse()")}}
+
Reverses playback direction, stopping at the start of the animation. If the animation is finished or unplayed, it will play from end to beginning.
+
{{domxref("Animation.updatePlaybackRate()")}}
+
Sets the speed of an animation after first synchronizing its playback position.
+
+ +

Preocupações de acessibilidade

+ +

Blinking and flashing animation can be problematic for people with cognitive concerns such as Attention Deficit Hyperactivity Disorder (ADHD). Additionally, certain kinds of motion can be a trigger for Vestibular disorders, epilepsy, and migraine and Scotopic sensitivity.

+ +

Consider providing a mechanism for pausing or disabling animation, as well as using the Reduced Motion Media Query to create a complimentary experience for users who have expressed a preference for no animated experiences.

+ + + +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName("Web Animations", "#the-animation-interface", "Animation")}}{{Spec2("Web Animations")}}Initial definition
+ +

Compatibilidade de navegador

+ + + +

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

diff --git a/files/pt-pt/web/api/api_armazenamento/index.html b/files/pt-pt/web/api/api_armazenamento/index.html new file mode 100644 index 0000000000..434cee963d --- /dev/null +++ b/files/pt-pt/web/api/api_armazenamento/index.html @@ -0,0 +1,128 @@ +--- +title: API de armazenamento +slug: Web/API/API_armazenamento +tags: + - API + - API de armazenamento + - Armazenamento + - Contextod e segurança + - Quotas + - Referencia + - Resumo + - Sinopse + - Utilização +translation_of: Web/API/Storage_API +--- +

{{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 new file mode 100644 index 0000000000..ecc97dd5c0 --- /dev/null +++ b/files/pt-pt/web/api/api_autenticacao_web/index.html @@ -0,0 +1,149 @@ +--- +title: APi de Autenticação da Web +slug: Web/API/API_Autenticacao_Web +tags: + - API + - API de Autenticação da Web + - Landing + - Referencia +translation_of: Web/API/Web_Authentication_API +--- +
{{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 new file mode 100644 index 0000000000..192a51ee66 --- /dev/null +++ b/files/pt-pt/web/api/api_de_armazenamento_da_web/index.html @@ -0,0 +1,156 @@ +--- +title: API de Armazenamento da Web +slug: Web/API/API_de_Armazenamento_da_Web +tags: + - API + - Armazenamento + - Armazenamento Local + - Armazenamento da Sessão + - Armazenamento da Web + - Referencia +translation_of: Web/API/Web_Storage_API +--- +

{{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 new file mode 100644 index 0000000000..17971de4ee --- /dev/null +++ b/files/pt-pt/web/api/api_de_canvas/index.html @@ -0,0 +1,247 @@ +--- +title: API de Canvas +slug: Web/API/API_de_canvas +translation_of: Web/API/Canvas_API +--- +
{{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 new file mode 100644 index 0000000000..b93457336d --- /dev/null +++ b/files/pt-pt/web/api/api_de_canvas/tutorial/index.html @@ -0,0 +1,60 @@ +--- +title: Tutorial de Canvas +slug: Web/API/API_de_canvas/Tutorial +tags: + - Canvas + - Guía + - HTML + - HTML5 + - Intermediário + - Web + - graficos +translation_of: Web/API/Canvas_API/Tutorial +--- +
{{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 new file mode 100644 index 0000000000..4805a71bc6 --- /dev/null +++ b/files/pt-pt/web/api/api_do_estado_da_bateria/index.html @@ -0,0 +1,169 @@ +--- +title: API do Estado da Bateria +slug: Web/API/API_do_Estado_da_Bateria +tags: + - API + - API de Bateria + - API do Estado da Bateria + - Aplicações + - Apps + - Firefox OS + - Guía + - Movel + - Resumo + - Sinopse +translation_of: Web/API/Battery_Status_API +--- +
{{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 new file mode 100644 index 0000000000..26e56945ee --- /dev/null +++ b/files/pt-pt/web/api/api_entradas_de_diretoria_e_ficheiro/index.html @@ -0,0 +1,191 @@ +--- +title: API Entradas de Diretoria e Ficheiro +slug: Web/API/API_Entradas_de_Diretoria_e_Ficheiro +tags: + - API + - API Entradas de Diretoria e Ficheiro + - API Sistema de Ficheiros + - Ficheiros + - Não Padrão + - Referencia + - Resuno + - Sinopse +translation_of: Web/API/File_and_Directory_Entries_API +--- +

{{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 new file mode 100644 index 0000000000..399945ab71 --- /dev/null +++ b/files/pt-pt/web/api/api_transmissoes_multimedia/index.html @@ -0,0 +1,211 @@ +--- +title: API de Captura de Transmissões de Multimédia (Media Streams) +slug: Web/API/API_transmissoes_multimedia +tags: + - API + - API de Transmissão de Multimédia + - Audio + - Avançado + - Guía + - Introdução + - Media + - Multimedia + - Video +translation_of: Web/API/Media_Streams_API +--- +
{{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 new file mode 100644 index 0000000000..8e1b31898b --- /dev/null +++ b/files/pt-pt/web/api/api_webrtc/index.html @@ -0,0 +1,287 @@ +--- +title: API de WebRTC +slug: Web/API/API_WebRTC +tags: + - API + - API de WebRTC + - API de WebRTCÁudio + - Multimedia + - Rede + - Video + - WebRTC + - emissão + - transmissão +translation_of: Web/API/WebRTC_API +--- +
{{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 new file mode 100644 index 0000000000..203ebfab5b --- /dev/null +++ b/files/pt-pt/web/api/api_webrtc/tirar_fotografias/index.html @@ -0,0 +1,222 @@ +--- +title: Tirar fotografias com a câmara da Web +slug: Web/API/API_WebRTC/Tirar_fotografias +tags: + - API + - Avançado + - Código amostra + - Exemplo + - Vídeo(2) + - WebRTC + - cãmara da Web +translation_of: Web/API/WebRTC_API/Taking_still_photos +--- +

{{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/audionode/index.html b/files/pt-pt/web/api/audionode/index.html new file mode 100644 index 0000000000..df63de86c6 --- /dev/null +++ b/files/pt-pt/web/api/audionode/index.html @@ -0,0 +1,207 @@ +--- +title: AudioNode +slug: Web/API/AudioNode +tags: + - API + - AudioNode + - Interface + - NeedsTranslation + - Reference + - TopicStub + - Web Audio API +translation_of: Web/API/AudioNode +--- +

{{ APIRef("Web Audio API") }}

+ +

The AudioNode interface is a generic interface for representing an audio processing module like an audio source (e.g. an HTML {{HTMLElement("audio")}} or {{HTMLElement("video")}} element, an {{domxref("OscillatorNode")}}, etc.), the audio destination, intermediate processing module (e.g. a filter like {{domxref("BiquadFilterNode")}} or {{domxref("ConvolverNode")}}), or volume control (like {{domxref("GainNode")}}).

+ +

{{InheritanceDiagram}}

+ +

AudioNodes participating in an AudioContext create a audio routing graph.

+ +

An AudioNode has inputs and outputs, each with a given amount of channels. An AudioNode with zero inputs and one or multiple outputs is called a source node. The exact processing done varies from one AudioNode to another but, in general, a node reads its inputs, does some audio-related processing, and generates new values for its outputs, or simply lets the audio pass through (for example in the {{domxref("AnalyserNode")}}, where the result of the processing is accessed separately).

+ +

Different nodes can be linked together to build a processing graph. Such a graph is contained in an {{domxref("AudioContext")}}. Each AudioNode participates in exactly one such context. In general, processing nodes inherit the properties and methods of AudioNode, but also define their own functionality on top. See the individual node pages for more details, as listed on the Web Audio API homepage.

+ +
+

Note: An AudioNode can be target of events, therefore it implements the {{domxref("EventTarget")}} interface.

+
+ +

Properties

+ +
+
{{domxref("AudioNode.context")}} {{readonlyInline}}
+
Returns the associated {{domxref("AudioContext")}}, that is the object representing the processing graph the node is participating in.
+
+ +
+
{{domxref("AudioNode.numberOfInputs")}} {{readonlyInline}}
+
Returns the number of inputs feeding the node. Source nodes are defined as nodes having a numberOfInputs property with a value of 0.
+
+ +
+
{{domxref("AudioNode.numberOfOutputs")}} {{readonlyInline}}
+
Returns the number of outputs coming out of the node. Destination nodes — like {{ domxref("AudioDestinationNode") }} — have a value of 0 for this attribute.
+
+ +
+
{{domxref("AudioNode.channelCount")}}
+
Represents an integer used to determine how many channels are used when up-mixing and down-mixing connections to any inputs to the node. Its usage and precise definition depend on the value of {{domxref("AudioNode.channelCountMode")}}.
+
+ +
+
{{domxref("AudioNode.channelCountMode")}}
+
Represents an enumerated value describing the way channels must be matched between the node's inputs and outputs.
+
{{domxref("AudioNode.channelInterpretation")}}
+
Represents an enumerated value describing the meaning of the channels. This interpretation will define how audio up-mixing and down-mixing will happen.
+ The possible values are "speakers" or "discrete".
+
+ +

Methods

+ +

Also implements methods from the interface {{domxref("EventTarget")}}.

+ +
+
{{domxref("AudioNode.connect()")}}
+
Allows us to connect the output of this node to be input into another node, either as audio data or as the value of an {{domxref("AudioParam")}}.
+
{{domxref("AudioNode.disconnect()")}}
+
Allows us to disconnect the current node from another one it is already connected to.
+
+ +

Example

+ +

This simple snippet of code shows the creation of some audio nodes, and how the AudioNode properties and methods can be used. You can find examples of such usage on any of the examples linked to on the Web Audio API landing page (for example Violent Theremin.)

+ +
var AudioContext = window.AudioContext || window.webkitAudioContext;
+
+var audioCtx = new AudioContext();
+
+var oscillator = audioCtx.createOscillator();
+var gainNode = audioCtx.createGain();
+
+oscillator.connect(gainNode);
+gainNode.connect(audioCtx.destination);
+
+oscillator.context;
+oscillator.numberOfInputs;
+oscillator.numberOfOutputs;
+oscillator.channelCount;
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#the-audionode-interface', 'AudioNode')}}{{Spec2('Web Audio API')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(10.0)}}{{property_prefix("webkit")}}{{CompatVersionUnknown}}{{CompatGeckoDesktop(25.0)}}{{CompatNo}}15.0{{property_prefix("webkit")}}
+ 22 (unprefixed)
{{CompatVersionUnknown}}
channelCount channelCountMode{{CompatVersionUnknown}} {{property_prefix("webkit")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}
connect(AudioParam){{CompatVersionUnknown}} {{property_prefix("webkit")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}25.01.2{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
channelCount
+ channelCountMode
{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
connect(AudioParam){{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

See also

+ + diff --git a/files/pt-pt/web/api/blob/blob/index.html b/files/pt-pt/web/api/blob/blob/index.html new file mode 100644 index 0000000000..a00a527076 --- /dev/null +++ b/files/pt-pt/web/api/blob/blob/index.html @@ -0,0 +1,77 @@ +--- +title: Blob() +slug: Web/API/Blob/Blob +tags: + - API + - Blob + - Construtor + - File API + - Referencia +translation_of: Web/API/Blob/Blob +--- +
{{APIRef("File API")}}
+ +

O construtor Blob() devolve um novo objeto {{domxref("Blob")}}. O conteúdo do objeto Blob consiste na concatenação dos valores na matriz do primeiro parâmetro.

+ +

Sintaxe

+ +
var novoBlob = new Blob(array, options);
+
+ +

Parâmetros

+ +
+
array
+
Uma {{jsxref("Array")}} de {{jsxref("ArrayBuffer")}}, {{domxref("ArrayBufferView")}}, {{domxref("Blob")}}, {{domxref("USVString")}}, {{domxref("USVString")}}, ou uma mistura de quaisquer desses objetos, que serão colocados dentro do objeto {{domxref("Blob")}}. Os objetos USVString são codificados como UTF-8.
+
options {{optional_inline}}
+
+

Um objeto opcional do tipo {{domxref("BlobPropertyBag")}} que pode especificar qualquer uma das seguintes propriedades:

+ +
+
type {{optional_inline}}
+
O {{Glossary("MIME type", "tipo MIME")}} dos dados que serão armazenados no blob. O valor predefinido é uma string vazia, ("").
+
endings {{optional_inline}} {{non-standard_inline}}
+
Como interpretar os caracteres de nova linha (\n), se os dados são textos. O valor predefinido, transparent, copia os caracteres da nova linha para o blob sem os alterar. Para converter as novas linhas para a convenção nativa do sistema anfitrião, use o valor native.
+
+
+
+ +

Valor devolvido

+ +

Um novo objeto {{domxref("Blob")}} que contém os dados especificados.

+ +

Exemplo

+ +
var dadosParaFicheiro = ['<a id="a"><b id="b">hey!</b></a>']; // uma matriz constituída por uma única DOMString
+var oMeuBlob = new Blob(dadosParaFicheiro, {type : 'text/html'}); // o blob
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('File API', '#constructorBlob', 'Blob()')}}{{Spec2('File API')}}Definição inicial.
+ +

Compatibilidade

+ + + +

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

+ +

Ver também

+ + diff --git a/files/pt-pt/web/api/blob/index.html b/files/pt-pt/web/api/blob/index.html new file mode 100644 index 0000000000..878bc85e5e --- /dev/null +++ b/files/pt-pt/web/api/blob/index.html @@ -0,0 +1,157 @@ +--- +title: Blob +slug: Web/API/Blob +tags: + - API + - Blob + - File API + - Interface + - NeedsTranslation + - Raw + - Reference + - TopicStub + - data +translation_of: Web/API/Blob +--- +
{{APIRef("File API")}}
+ +

The Blob object represents a blob, which is a file-like object of immutable, raw data; they can be read as text or binary data, or converted into a {{DOMxRef("ReadableStream")}} so its methods can be used for processing the data.

+ +

Blobs can represent data that isn't necessarily in a JavaScript-native format. The {{DOMxRef("File")}} interface is based on Blob, inheriting blob functionality and expanding it to support files on the user's system.

+ +

Using blobs

+ +

To construct a Blob from other non-blob objects and data, use the {{DOMxRef("Blob.Blob", "Blob()")}} constructor. To create a blob that contains a subset of another blob's data, use the {{DOMxRef("Blob.slice()", "slice()")}} method. To obtain a Blob object for a file on the user's file system, see the {{DOMxRef("File")}} documentation.

+ +

The APIs accepting Blob objects are also listed in the {{DOMxRef("File")}} documentation.

+ +

Constructor

+ +
+
{{DOMxRef("Blob.Blob", "Blob()")}}
+
Returns a newly created Blob object which contains a concatenation of all of the data in the array passed into the constructor.
+
+ +

Instance properties

+ +
+
{{DOMxRef("Blob.prototype.size")}} {{readonlyinline}}
+
The size, in bytes, of the data contained in the Blob object.
+
{{DOMxRef("Blob.prototype.type")}} {{readonlyinline}}
+
A string indicating the MIME type of the data contained in the Blob. If the type is unknown, this string is empty.
+
+ +

Instance methods

+ +
+
{{DOMxRef("Blob.prototype.arrayBuffer()")}}
+
Returns a promise that resolves with an {{DOMxRef("ArrayBuffer")}} containing the entire contents of the Blob as binary data.
+
{{DOMxRef("Blob.prototype.slice()")}}
+
Returns a new Blob object containing the data in the specified range of bytes of the blob on which it's called.
+
{{DOMxRef("Blob.prototype.stream()")}}
+
Returns a {{DOMxRef("ReadableStream")}} that can be used to read the contents of the Blob.
+
{{DOMxRef("Blob.prototype.text()")}}
+
Returns a promise that resolves with a {{DOMxRef("USVString")}} containing the entire contents of the Blob interpreted as UTF-8 text.
+
+ +

Examples

+ +

Creating a blob

+ +

The {{DOMxRef("Blob.Blob", "Blob()")}} constructor can create blobs from other objects. For example, to construct a blob from a JSON string:

+ +
const obj = {hello: 'world'};
+const blob = new Blob([JSON.stringify(obj, null, 2)], {type : 'application/json'});
+ +

Creating a URL representing the contents of a typed array

+ +

The following code creates a JavaScript typed array and creates a new Blob containing the typed array's data. It then calls {{DOMxRef("URL.createObjectURL()")}} to convert the blob into a {{glossary("URL")}}.

+ +

HTML

+ +
<p>This example creates a typed array containing the ASCII codes
+   for the space character through the letter Z, then converts it
+   to an object URL. A link to open that object URL is created.
+   Click the link to see the decoded object URL.</p>
+ +

JavaScript

+ +

The main piece of this code for example purposes is the typedArrayToURL() function, which creates a Blob from the given typed array and returns an object URL for it. Having converted the data into an object URL, it can be used in a number of ways, including as the value of the {{HTMLElement("img")}} element's {{htmlattrxref("src", "img")}} attribute (assuming the data contains an image, of course).

+ +
function typedArrayToURL(typedArray, mimeType) {
+  return URL.createObjectURL(new Blob([typedArray.buffer], {type: mimeType}))
+}
+
+const bytes = new Uint8Array(59);
+
+for(let i = 0; i < 59; i++) {
+  bytes[i] = 32 + i;
+}
+
+const url = typedArrayToURL(bytes, 'text/plain');
+
+const link = document.createElement('a');
+link.href = url;
+link.innerText = 'Open the array URL';
+
+document.body.appendChild(link);
+ +

Result

+ +

Click the link in the example to see the browser decode the object URL.

+ +

{{EmbedLiveSample("Creating_a_URL_representing_the_contents_of_a_typed_array", 600, 200)}}

+ +

Extracting data from a blob

+ +

One way to read content from a Blob is to use a {{DOMxRef("FileReader")}}. The following code reads the content of a Blob as a typed array:

+ +
const reader = new FileReader();
+reader.addEventListener('loadend', () => {
+   // reader.result contains the contents of blob as a typed array
+});
+reader.readAsArrayBuffer(blob);
+ +

Another way to read content from a Blob is to use a {{domxref("Response")}}. The following code reads the content of a Blob as text:

+ +
const text = await (new Response(blob)).text();
+
+ +

Or by using {{DOMxRef("Blob.prototype.text()")}}:

+ +
const text = await blob.text();
+ +

By using other methods of FileReader, it is possible to read the contents of a Blob as a string or a data URL.

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('File API', '#blob-section', 'The Blob interface')}}{{Spec2('File API')}}Initial definition.
+ +

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/pt-pt/web/api/blob/size/index.html b/files/pt-pt/web/api/blob/size/index.html new file mode 100644 index 0000000000..fc6423a199 --- /dev/null +++ b/files/pt-pt/web/api/blob/size/index.html @@ -0,0 +1,73 @@ +--- +title: Blob.size +slug: Web/API/Blob/size +tags: + - API + - Blob + - Bytes + - Ficheiros + - File API + - Propriedade + - Referencia + - length + - size +translation_of: Web/API/Blob/size +--- +
{{APIRef("File API")}}
+ +

A propriedade size da interface do {{domxref("Blob")}} retorna o tamanho do {{domxref("Blob")}} ou {{domxref("File")}} em bytes.

+ +

Sintaxe

+ +
var sizeInBytes = blob.size
+
+ +

Valor

+ +

O número de bytes de dados contidos dentro do Blob (ou do objeto baseado em Blob, como um {{domxref("File")}}).

+ +

Exemplo

+ +

Este exemplo usa um {{HTMLElement("input")}} com os atributos type="file" e multiple para receber do utilizador um grupo de ficheiros, e depois um iterar sobre os ficheiros que emitem os seus nomes e comprimentos em bytes.

+ +
// fileInput is a HTMLInputElement: <input type="file" multiple id="myfileinput">
+var fileInput = document.getElementById("myfileinput");
+
+// files is a FileList object (simliar to NodeList)
+var files = fileInput.files;
+
+for (var i = 0; i < files.length; i++) {
+  console.log(files[i].name + " has a size of " + files[i].size + " Bytes");
+}
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('File API', '#dfn-size', 'Blob.size')}}{{Spec2('File API')}}Definição inicial
+ +

Compatibilidade

+ +
+ + +

{{Compat("api.Blob.size")}}

+
+ +

Ver também

+ + diff --git a/files/pt-pt/web/api/blob/type/index.html b/files/pt-pt/web/api/blob/type/index.html new file mode 100644 index 0000000000..5744a80a5b --- /dev/null +++ b/files/pt-pt/web/api/blob/type/index.html @@ -0,0 +1,83 @@ +--- +title: Blob.type +slug: Web/API/Blob/type +tags: + - API + - Blob + - DOM + - File + - File API + - Formato + - MIME + - MIME Type + - Propriedade + - Referencia + - tipo +translation_of: Web/API/Blob/type +--- +
{{APIRef("File API")}}
+ +

A propriade type do objeto {{domxref("Blob")}} devolve o {{Glossary("MIME type")}} do ficheiro.

+ +

Sintaxe

+ +
var mimetype = blob.type
+ +

Valor

+ +

Uma {{domxref("DOMString")}} que contem o MIME do ficheiro, ou uma string vazia se o tipo não consegue ser determinado.

+ +

Exemplo

+ +

Este exemplo pede ao utilizador que selecione uma série de ficheiros, depois verifica cada ficheiro para se certificar de que é um de um determinado conjunto de tipos de ficheiros de imagem.

+ +
var i, fileInput, files, allowedFileTypes;
+
+// fileInput é um HTMLInputElement: <input type="file" multiple id="myfileinput">
+fileInput = document.getElementById("myfileinput");
+
+// files é um objeto FileList (parecido ao NodeList)
+files = fileInput.files;
+
+// a nossa aplicação só aceita imagens GIF, PNG, e JPEG
+allowedFileTypes = ["image/png", "image/jpeg", "image/gif"];
+
+for (i = 0; i < files.length; i++) {
+  // Testar se file.type é um dos MIME types permitidos.
+  if (allowedFileTypes.indexOf(files[i].type) > -1) {
+    // file.type é válido
+  }
+});
+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('File API', '#dfn-type', 'Blob.type')}}{{Spec2('File API')}}Definição inicial.
+ +

Compatibilidade

+ +
+ + +

{{Compat("api.Blob.type")}}

+
+ +

Ver também

+ + diff --git a/files/pt-pt/web/api/client/index.html b/files/pt-pt/web/api/client/index.html new file mode 100644 index 0000000000..267c1fafc4 --- /dev/null +++ b/files/pt-pt/web/api/client/index.html @@ -0,0 +1,67 @@ +--- +title: Client +slug: Web/API/Client +tags: + - API + - Client + - Experimental + - Interface + - Referencia + - Service Workers + - Service worker API + - ServiceWorkerClient + - ServiceWorkers +translation_of: Web/API/Client +--- +

{{SeeCompatTable}}{{APIRef("Service Workers API")}}

+ +

A interface de Client representa um contexto executável, tal como um {{domxref("Worker")}}, ou um {{domxref("SharedWorker")}}. Os {{domxref("Window")}} clients são representados pelo mais específico {{domxref("WindowClient")}}. Pode obter os objetos Client/WindowClient a partir dos métodos, tais como {{domxref("Clients.matchAll","Clients.matchAll()")}} e {{domxref("Clients.get","Clients.get()")}}.

+ +

Métodos

+ +
+
{{domxref("Client.postMessage()")}}
+
Sends a message to the client.
+
+ +

Propriedades

+ +
+
{{domxref("Client.id")}} {{readonlyInline}}
+
The universally unique identifier of the client as a string.
+
{{domxref("Client.type")}} {{readonlyInline}}
+
The client's type as a string. It can be "window", "worker", or "sharedworker".
+
{{domxref("Client.url")}} {{readonlyInline}}
+
The URL of the client as a string.
+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('Service Workers', '#client', 'Client')}}{{Spec2('Service Workers')}}Definitição inicial.
+ +

Compatibilidade de Navegador

+ + + +

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

+ +

Consulte também:

+ + diff --git a/files/pt-pt/web/api/closeevent/closeevent/index.html b/files/pt-pt/web/api/closeevent/closeevent/index.html new file mode 100644 index 0000000000..b12c9d211e --- /dev/null +++ b/files/pt-pt/web/api/closeevent/closeevent/index.html @@ -0,0 +1,71 @@ +--- +title: CloseEvent() +slug: Web/API/CloseEvent/CloseEvent +tags: + - API + - CloseEvent + - Construtor + - Referencia +translation_of: Web/API/CloseEvent/CloseEvent +--- +
{{APIRef("Websockets API")}}
+ +

O construtor CloseEvent() cria um novo {{domxref("CloseEvent")}}.

+ +

Sintaxe

+ +
var event = new CloseEvent(typeArg, closeEventInit);
+ +

Valores

+ +
+
typeArg
+
É uma {{domxref("DOMString")}} que representa o nome do evento.
+
closeEventInit {{optional_inline}}
+
+ +
+
É um dicionário CloseEventInit, com os seguintes campos: + +
    +
  • "wasClean", opcional e pré-definido como false, do tipo long, indica se a conexão foi terminada de forma limpa ou não.
  • +
  • "code", opcional e pré-definido como 0, do tipo unsigned short, é o código de estado do encerrar da conexão enviada pelo servidor.
  • +
  • "reason", opcional e pré-definido como '', do tipo {{domxref("DOMString")}}, é a razão por qual o servidor terminou a conexão escrita para humanos.
  • +
+ +
+

O dicionário CloseEventInit também aceita campos do dicionário {{domxref("Event.Event", "EventInit")}}.

+
+
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('HTML WHATWG','comms.html#closeevent','CloseEvent()')}}{{Spec2('HTML WHATWG')}}Definição inicial.
+ +

Compatibilidade

+ + + +

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

+ +

Ver também

+ + diff --git a/files/pt-pt/web/api/closeevent/index.html b/files/pt-pt/web/api/closeevent/index.html new file mode 100644 index 0000000000..5cece5fd2b --- /dev/null +++ b/files/pt-pt/web/api/closeevent/index.html @@ -0,0 +1,195 @@ +--- +title: CloseEvent +slug: Web/API/CloseEvent +tags: + - API + - Interface + - Referencia + - Web + - WebSocket + - WebSockets +translation_of: Web/API/CloseEvent +--- +
{{APIRef("Websockets API")}}
+ +

Um CloseEvent é enviado a clientes usando {{Glossary("WebSockets")}} quando a conexão é terminada. É enviado ao listner indicado pelo atributo onclose de objeto WebSocket.

+ +

Construtor

+ +
+
{{domxref("CloseEvent.CloseEvent", "CloseEvent()")}}
+
Cria um novo CloseEvent.
+
+ +

Propriedades

+ +

Esta interface também herda propriedades do {{domxref("Event")}} de qual se deriva.

+ +
+
{{domxref("CloseEvent.code")}} {{readOnlyInline}}
+
Devolve uma unsigned short que contem o código enviado pelo servidor. Os seguintes valores são os códigos de estado permitidos, as definições foram traduzidas a partir do site da IANA. Note que os códigos 1xxx são só usados internamente pelo WebSocket e não para uso com os dados transportados (como quando o protocolo da aplicação é invalido). Os únicos códigos que podem ser especificados no Firefox são o código 1000 e a série de 3000 a 4999 inclusivo [Fonte, Bug].
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CódigoNomeDescrição
0999Reservado e não utilizado.
1000Normal Closure +

Encerramento normal; a conexão completou a tarefa para qual foi criada.

+
1001Going Away +

O terminal está a desaparecer, seja devido a uma falha do servidor ou porque o navegador está a navegar para longe da página que abriu a ligação.

+
1002Protocol ErrorO terminal está a terminar a conexão devido a um erro de protocolo.
1003Unsupported DataA conexão está a ser terminada porque o terminal recebeu dados num formato que não aceita (por exemplo um terminal de texto receber dados binarios).
1004Reservado. Uma definição pode ser atribuída no futuro.
1005No Status ReceivedReservado.  Indica que nenhum código de estado foi oferecido, apesar de ser esperado um código.
1006Abnormal ClosureReservado. Usado para indicar que a conexão fechou anormalmente (isto é, sem uma close frame ser enviada) quando um código era esperado.
1007Invalid frame payload dataO terminal está a terminar a conexão porque a mensagem continha dados inconsistentes (e.x. dados não codificados em UTF-8 numa mensagem de texto).
1008Policy ViolationO terminal está a terminar a conexão porque recebeu uma mensagem que viola a sua política. Isto é um código genérico, usado quando os códigos 1003 e 1009 não são apropriados à situação.
1009Message too bigO terminal está a terminar a conexão porque o data frame recebido é demasiado grande.
1010Missing ExtensionO cliente está a terminar a conexão porque esperava que o servidor negociasse uma ou mais extensões, mas não o fez.
1011Internal ErrorO servidor está a terminar a conexão porque encontrou uma condição inesperada que a impede de completar o pedido.
1012Service RestartO servidor está a terminar a conexão porque está a reiniciar. [Ref]
1013Try Again LaterO servidor está a terminar a conexão devido a uma condição temporária, por exemplo está sobrecarregado e está a reduzir o número de clientes. [Ref]
1014Bad GatewayO servidor está a agir como uma gateway ou proxy e recebeu uma resposta inválida dum servidor mais adiante na conexão. Isto é parecido com o código de estado HTTP 502.
1015TLS HandshakeReservado. Indica que a conexão foi terminada devido a uma falha na execução de um aperto de mão TLS (por exemplo, o certificado do servidor não pode ser verificado).
10161999Reservado para o futuro uso de padrões WebSocket.
20002999Reservado para uso de extensões de WebSocket.
30003999Disponivel para uso por bibliotecas e frameworks. Não é para ser utilizado por aplicações. Disponível para registo através da IANA de forma de primeiro a chegar primeiro servido.
40004999Disponível para uso por aplicações.
+
+
{{domxref("CloseEvent.reason")}} {{readOnlyInline}}
+
Devolve uma {{domxref("DOMString")}} a indicar a razão por qual o servidor terminou a conexão. Isto é específico ao servidor e sub-protocolo.
+
{{domxref("CloseEvent.wasClean")}} {{readOnlyInline}}
+
Devolve um {{jsxref("Boolean")}} que indica se a conexão não foi terminada de forma limpa.
+
+ +

Métodos

+ +

Esta interface também herda métodos de {{domxref("Event")}} de qual se deriva.

+ +
+
{{domxref("CloseEvent.initCloseEvent()")}} {{Non-standard_inline}} {{Obsolete_inline}}
+
Inicializa o valor de um CloseEvent. Se o evento já foi enviado, o método não faz nada. Este método é obsoleto, use antes o construtor {{domxref("CloseEvent.CloseEvent", "CloseEvent()")}}.
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{ SpecName('HTML WHATWG', 'web-sockets.html#the-closeevent-interface', 'CloseEvent') }}{{ Spec2('HTML WHATWG') }}Definição inicial.
+ +

Compatibilidade

+ + + +

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

+ +

Ver também

+ + 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/index.html b/files/pt-pt/web/api/document/index.html new file mode 100644 index 0000000000..6710b92f64 --- /dev/null +++ b/files/pt-pt/web/api/document/index.html @@ -0,0 +1,458 @@ +--- +title: Document +slug: Web/API/Document +tags: + - API + - DOM + - Documento + - Interface + - Referencia +translation_of: Web/API/Document +--- +
{{APIRef}}
+ +
 
+ +

A interface Document representa qualquer página da Web carregada no navegador e serve como um ponto de entrada para um conteúdo da página da Web, que é árvore DOM. A árvore DOM inclui elementos, tais como {{HTMLElement("body")}} e {{HTMLElement("table")}}, entre muitos outros. Este fornece funcionalidade globalmente para o documento, tal como obter o URL da página e criar novos elementos no documento.

+ +

{{inheritanceDiagram}}

+ +

The Document interface describes the common properties and methods for any kind of document. Depending on the document's type (e.g. HTML, XML, SVG, …), a larger API is available: HTML documents, served with the text/html content type, also implement the {{domxref("HTMLDocument")}} interface, whereas XML and SVG documents implement the {{domxref("XMLDocument")}} interface.

+ +

Construtor

+ +
+
{{domxref("Document.Document","Document()")}}{{non-standard_inline}}
+
Cria um novo objeto Document.
+
+ +

Propriedades

+ +

This interface also inherits from the {{domxref("Node")}} and {{domxref("EventTarget")}} interfaces.

+ +
+
{{domxref("Document.all")}} {{Deprecated_inline}} {{non-standard_inline}}
+
Provides access to all elements in the document. This is a legacy, non-standard interface and should not be used.
+
{{domxref("Document.async")}} {{Deprecated_inline}}
+
Used with {{domxref("Document.load")}} to indicate an asynchronous request.
+
{{domxref("Document.characterSet")}} {{readonlyinline}}
+
Returns the character set being used by the document.
+
{{domxref("Document.charset")}} {{readonlyinline}} {{Deprecated_inline}}
+
Alias of {{domxref("Document.characterSet")}}. Use this property instead.
+
{{domxref("Document.compatMode")}} {{readonlyinline}} {{experimental_inline}}
+
Indicates whether the document is rendered in quirks or strict mode.
+
{{domxref("Document.contentType")}} {{readonlyinline}} {{experimental_inline}}
+
Returns the Content-Type from the MIME Header of the current document.
+
{{domxref("Document.doctype")}} {{readonlyinline}}
+
Returns the Document Type Definition (DTD) of the current document.
+
{{domxref("Document.documentElement")}} {{readonlyinline}}
+
Returns the {{domxref("Element")}} that is a direct child of the document. For HTML documents, this is normally the {{HTMLElement("html")}} element.
+
{{domxref("Document.documentURI")}} {{readonlyinline}}
+
Returns the document location as a string.
+
{{domxref("Document.domConfig")}} {{Deprecated_inline}}
+
Should return a {{domxref("DOMConfiguration")}} object.
+
{{domxref("Document.fullscreen")}} {{obsolete_inline}}
+
true when the document is in {{domxref("Using_full-screen_mode","full-screen mode")}}.
+
{{domxref("Document.hidden")}} {{readonlyinline}}
+
+
{{domxref("Document.implementation")}} {{readonlyinline}}
+
Returns the DOM implementation associated with the current document.
+
{{domxref("Document.inputEncoding")}} {{readonlyinline}} {{Deprecated_inline}}
+
Alias of {{domxref("Document.characterSet")}}. Use this property instead.
+
{{domxref("Document.lastStyleSheetSet")}} {{readonlyinline}}
+
Returns the name of the style sheet set that was last enabled. Has the value null until the style sheet is changed by setting the value of {{domxref("document.selectedStyleSheetSet","selectedStyleSheetSet")}}.
+
{{domxref("Document.mozSyntheticDocument")}} {{non-standard_inline}} {{gecko_minversion_inline("8.0")}}
+
Returns a {{jsxref("Boolean")}} that is true only if this document is synthetic, such as a standalone image, video, audio file, or the like.
+
{{domxref("Document.mozFullScreenElement")}} {{readonlyinline}} {{non-standard_inline}} {{gecko_minversion_inline("9.0")}}
+
The element that's currently in full screen mode for this document.
+
{{domxref("Document.mozFullScreenEnabled")}} {{readonlyinline}} {{non-standard_inline}} {{gecko_minversion_inline("9.0")}}
+
true if calling {{domxref("Element.mozRequestFullscreen()")}} would succeed in the curent document.
+
{{domxref("Document.pointerLockElement")}} {{readonlyinline}} {{experimental_inline}}
+
Returns the element set as the target for mouse events while the pointer is locked. null if lock is pending, pointer is unlocked, or if the target is in another document.
+
{{domxref("Document.preferredStyleSheetSet")}} {{readonlyinline}}
+
Returns the preferred style sheet set as specified by the page author.
+
{{domxref("Document.scrollingElement")}} {{experimental_inline}} {{readonlyinline}}
+
Returns a reference to the {{domxref("Element")}} that scrolls the document.
+
{{domxref("Document.selectedStyleSheetSet")}}
+
Returns which style sheet set is currently in use.
+
{{domxref("Document.styleSheets")}} {{readonlyinline}}
+
Returns a list of the style sheet objects on the current document.
+
{{domxref("Document.styleSheetSets")}} {{readonlyinline}}
+
Returns a list of the style sheet sets available on the document.
+
{{domxref("Document.timeline")}} {{readonlyinline}}
+
+
{{domxref("Document.undoManager")}} {{readonlyinline}} {{experimental_inline}}
+
+
{{domxref("Document.visibilityState")}} {{readonlyinline}}
+
+

Returns a string denoting the visibility state of the document. Possible values are visiblehiddenprerender, and unloaded.

+
+
{{domxref("Document.xmlEncoding")}} {{Deprecated_inline}}
+
Returns the encoding as determined by the XML declaration.
+
{{domxref("Document.xmlStandalone")}} {{obsolete_inline("10.0")}}
+
Returns true if the XML declaration specifies the document to be standalone (e.g., An external part of the DTD affects the document's content), else false.
+
{{domxref("Document.xmlVersion")}} {{obsolete_inline("10.0")}}
+
Returns the version number as specified in the XML declaration or "1.0" if the declaration is absent.
+
+ +

The Document interface is extended with the {{domxref("ParentNode")}} interface:

+ +

{{page("/en-US/docs/Web/API/ParentNode","Properties")}}

+ +

Extensão para o documento HTML

+ +

The Document interface for HTML documents inherits from the {{domxref("HTMLDocument")}} interface or, since HTML5,  is extended for such documents.

+ +
+
{{domxref("Document.activeElement")}} {{readonlyinline}}
+
Returns the currently focused element.
+
{{domxref("Document.alinkColor")}} {{Deprecated_inline}}
+
Returns or sets the color of active links in the document body.
+
{{domxref("Document.anchors")}}
+
Returns a list of all of the anchors in the document.
+
{{domxref("Document.applets")}} {{Deprecated_inline}}
+
Returns an ordered list of the applets within a document.
+
{{domxref("Document.bgColor")}} {{Deprecated_inline}}
+
Gets/sets the background color of the current document.
+
{{domxref("Document.body")}}
+
Returns the {{HTMLElement("body")}} element of the current document.
+
{{domxref("Document.cookie")}}
+
Returns a semicolon-separated list of the cookies for that document or sets a single cookie.
+
{{domxref("Document.defaultView")}} {{readonlyinline}}
+
Returns a reference to the window object.
+
{{domxref("Document.designMode")}}
+
Gets/sets the ability to edit the whole document.
+
{{domxref("Document.dir")}} {{readonlyinline}}
+
Gets/sets directionality (rtl/ltr) of the document.
+
{{domxref("Document.domain")}}
+
Gets/sets the domain of the current document.
+
{{domxref("Document.embeds")}} {{readonlyinline}}
+
Returns a list of the embedded {{HTMLElement('embed')}} elements within the current document.
+
{{domxref("document.fgColor")}} {{Deprecated_inline}}
+
Gets/sets the foreground color, or text color, of the current document.
+
{{domxref("Document.forms")}} {{readonlyinline}}
+
Returns a list of the {{HTMLElement("form")}} elements within the current document.
+
{{domxref("Document.head")}} {{readonlyinline}}
+
Returns the {{HTMLElement("head")}} element of the current document.
+
{{domxref("Document.height")}} {{non-standard_inline}} {{obsolete_inline}}
+
Gets/sets the height of the current document.
+
{{domxref("Document.images")}} {{readonlyinline}}
+
Returns a list of the images in the current document.
+
{{domxref("Document.lastModified")}} {{readonlyinline}}
+
Returns the date on which the document was last modified.
+
{{domxref("Document.linkColor")}} {{Deprecated_inline}}
+
Gets/sets the color of hyperlinks in the document.
+
{{domxref("Document.links")}} {{readonlyinline}}
+
Returns a list of all the hyperlinks in the document.
+
{{domxref("Document.location")}} {{readonlyinline}}
+
Returns the URI of the current document.
+
{{domxref("Document.plugins")}} {{readonlyinline}}
+
Returns a list of the available plugins.
+
{{domxref("Document.readyState")}} {{readonlyinline}}  {{gecko_minversion_inline("1.9.2")}}
+
Returns loading status of the document.
+
{{domxref("Document.referrer")}} {{readonlyinline}}
+
Returns the URI of the page that linked to this page.
+
{{domxref("Document.scripts")}} {{readonlyinline}}
+
Returns all the {{HTMLElement("script")}} elements on the document.
+
{{domxref("Document.title")}}
+
Sets or gets the title of the current document.
+
{{domxref("Document.URL")}} {{readonlyInline}}
+
Returns the document location as a string.
+
{{domxref("Document.vlinkColor")}} {{Deprecated_inline}}
+
Gets/sets the color of visited hyperlinks.
+
{{domxref("Document.width")}} {{non-standard_inline}} {{obsolete_inline}}
+
Returns the width of the current document.
+
+ +

Event handlers

+ +
+
{{domxref("Document.onafterscriptexecute")}} {{non-standard_inline}}
+
Represents the event handling code for the {{event("afterscriptexecute")}} event.
+
{{domxref("Document.onbeforescriptexecute")}} {{non-standard_inline}}
+
Represents the event handling code for the {{event("beforescriptexecute")}} event.
+
{{domxref("Document.oncopy")}} {{non-standard_inline}}
+
Represents the event handling code for the {{event("copy")}} event.
+
{{domxref("Document.oncut")}} {{non-standard_inline}}
+
Represents the event handling code for the {{event("cut")}} event.
+
{{domxref("Document.onfullscreenchange")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("fullscreenchange")}} event is raised.
+
{{domxref("Document.onfullscreenerror")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("fullscreenerror")}} event is raised.
+
{{domxref("Document.onpaste")}} {{non-standard_inline}}
+
Represents the event handling code for the {{event("paste")}} event.
+
{{domxref("Document.onpointerlockchange")}} {{experimental_inline}}
+
Represents the event handling code for the {{event("pointerlockchange")}} event.
+
{{domxref("Document.onpointerlockerror")}} {{experimental_inline}}
+
Represetnts the event handling code for the {{event("pointerlockerror")}} event.
+
{{domxref("Document.onreadystatechange")}} {{gecko_minversion_inline("1.9.2")}}
+
Represents the event handling code for the {{event("readystatechange")}} event.
+
{{domxref("Document.onselectionchange")}} {{experimental_inline}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("selectionchange")}} event is raised.
+
{{domxref("Document.onvisibilitychange")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("visibilitychange")}} event is raised.
+
{{domxref("Document.onwheel")}} {{non-standard_inline}}
+
Represents the event handling code for the {{event("wheel")}} event.
+
+ +

The Document interface is extended with the {{domxref("GlobalEventHandlers")}} interface:

+ +

{{Page("/en-US/docs/Web/API/GlobalEventHandlers", "Properties")}}

+ +

Methods

+ +

This interface also inherits from the {{domxref("Node")}} and {{domxref("EventTarget")}} interfaces.

+ +
+
{{domxref("Document.adoptNode()")}}
+
Adopt node from an external document.
+
{{domxref("Document.captureEvents()")}} {{Deprecated_inline}}
+
See {{domxref("Window.captureEvents")}}.
+
{{domxref("Document.caretPositionFromPoint()")}}{{experimental_inline}}
+
Gets the {{domxref("CaretPosition")}} at or near the specified coordinates.
+
{{domxref("Document.caretRangeFromPoint()")}}{{non-standard_inline}}
+
Gets a {{Domxref("Range")}} object for the document fragment under the specified coordinates.
+
{{domxref("Document.createAttribute()")}}
+
Creates a new {{domxref("Attr")}} object and returns it.
+
{{domxref("Document.createAttributeNS()")}}
+
Creates a new attribute node in a given namespace and returns it.
+
{{domxref("Document.createCDATASection()")}}
+
Creates a new CDATA node and returns it.
+
{{domxref("Document.createComment()")}}
+
Creates a new comment node and returns it.
+
{{domxref("Document.createDocumentFragment()")}}
+
Creates a new document fragment.
+
{{domxref("Document.createElement()")}}
+
Creates a new element with the given tag name.
+
{{domxref("Document.createElementNS()")}}
+
Creates a new element with the given tag name and namespace URI.
+
{{domxref("Document.createEntityReference()")}} {{obsolete_inline}}
+
Creates a new entity reference object and returns it.
+
{{domxref("Document.createEvent()")}}
+
Creates an event object.
+
{{domxref("Document.createNodeIterator()")}}
+
Creates a {{domxref("NodeIterator")}} object.
+
{{domxref("Document.createProcessingInstruction()")}}
+
Creates a new {{domxref("ProcessingInstruction")}} object.
+
{{domxref("Document.createRange()")}}
+
Creates a {{domxref("Range")}} object.
+
{{domxref("Document.createTextNode()")}}
+
Creates a text node.
+
{{domxref("Document.createTouch()")}} {{Deprecated_inline}}
+
Creates a {{domxref("Touch")}} object.
+
{{domxref("Document.createTouchList()")}}
+
Creates a {{domxref("TouchList")}} object.
+
{{domxref("Document.createTreeWalker()")}}
+
Creates a {{domxref("TreeWalker")}} object.
+
{{domxref("Document.elementFromPoint()")}}{{experimental_inline}}
+
Returns the topmost element at the specified coordinates. 
+
{{domxref("Document.elementsFromPoint()")}}{{experimental_inline}}
+
Returns an array of all elements at the specified coordinates.
+
{{domxref("Document.enableStyleSheetsForSet()")}}
+
Enables the style sheets for the specified style sheet set.
+
{{domxref("Document.exitPointerLock()")}} {{experimental_inline}}
+
Release the pointer lock.
+
{{domxref("Document.getAnimations()")}} {{experimental_inline}}
+
Returns an array of all {{domxref("Animation")}} objects currently in effect, whose target elements are descendants of the document.
+
{{domxref("Document.getElementsByClassName()")}}
+
Returns a list of elements with the given class name.
+
{{domxref("Document.getElementsByTagName()")}}
+
Returns a list of elements with the given tag name.
+
{{domxref("Document.getElementsByTagNameNS()")}}
+
Returns a list of elements with the given tag name and namespace.
+
{{domxref("Document.importNode()")}}
+
Returns a clone of a node from an external document.
+
{{domxref("Document.normalizeDocument()")}} {{obsolete_inline}}
+
Replaces entities, normalizes text nodes, etc.
+
{{domxref("Document.registerElement()")}} {{experimental_inline}}
+
Registers a web component.
+
{{domxref("Document.releaseCapture()")}} {{non-standard_inline}} {{gecko_minversion_inline("2.0")}}
+
Releases the current mouse capture if it's on an element in this document.
+
{{domxref("Document.releaseEvents()")}} {{non-standard_inline}} {{Deprecated_inline}}
+
See {{domxref("Window.releaseEvents()")}}.
+
{{domxref("Document.routeEvent()")}} {{non-standard_inline}} {{obsolete_inline(24)}}
+
See {{domxref("Window.routeEvent()")}}.
+
{{domxref("Document.mozSetImageElement()")}} {{non-standard_inline}} {{gecko_minversion_inline("2.0")}}
+
Allows you to change the element being used as the background image for a specified element ID.
+
+ +

The Document interface is extended with the {{domxref("ParentNode")}} interface:

+ +
+
{{domxref("document.getElementById","document.getElementById(String id)")}}
+
Returns an object reference to the identified element.
+
{{domxref("document.querySelector","document.querySelector(String selector)")}} {{gecko_minversion_inline("1.9.1")}}
+
Returns the first Element node within the document, in document order, that matches the specified selectors.
+
{{domxref("document.querySelectorAll","document.querySelectorAll(String selector)")}} {{gecko_minversion_inline("1.9.1")}}
+
Returns a list of all the Element nodes within the document that match the specified selectors.
+
+ +

The Document interface is extended with the {{domxref("XPathEvaluator")}} interface:

+ +
+
{{domxref("document.createExpression","document.createExpression(String expression, XPathNSResolver resolver)")}}
+
Compiles an XPathExpression which can then be used for (repeated) evaluations.
+
{{domxref("document.createNSResolver","document.createNSResolver(Node resolver)")}}
+
Creates an {{domxref("XPathNSResolver")}} object.
+
{{domxref("document.evaluate","document.evaluate(String expression, Node contextNode, XPathNSResolver resolver, Number type, Object result)")}}
+
Evaluates an XPath expression.
+
+ +

Extension for HTML documents

+ +

The Document interface for HTML documents inherit from the {{domxref("HTMLDocument")}} interface or, since HTML5,  is extended for such documents:

+ +
+
{{domxref("document.clear()")}} {{non-standard_inline}} {{Deprecated_inline}}
+
In majority of modern browsers, including recent versions of Firefox and Internet Explorer, this method does nothing.
+
{{domxref("document.close()")}}
+
Closes a document stream for writing.
+
{{domxref("document.execCommand","document.execCommand(String command[, Boolean showUI[, String value]])")}}
+
On an editable document, executes a formating command.
+
{{domxref("document.getElementsByName","document.getElementsByName(String name)")}}
+
Returns a list of elements with the given name.
+
{{domxref("document.getSelection()")}}
+
Returns a {{domxref("Selection")}} object related to text selected in the document.
+
{{domxref("document.hasFocus()")}}
+
Returns true if the focus is currently located anywhere inside the specified document.
+
{{domxref("document.open()")}}
+
Opens a document stream for writing.
+
{{domxref("document.queryCommandEnabled","document.queryCommandEnabled(String command)")}}
+
Returns true if the formating command can be executed on the current range.
+
{{domxref("document.queryCommandIndeterm","document.queryCommandIndeterm(String command)")}}
+
Returns true if the formating command is in an indeterminate state on the current range.
+
{{domxref("document.queryCommandState","document.queryCommandState(String command)")}}
+
Returns true if the formating command has been executed on the current range.
+
{{domxref("document.queryCommandSupported","document.queryCommandSupported(String command)")}}
+
Returns true if the formating command is supported on the current range.
+
{{domxref("document.queryCommandValue","document.queryCommandValue(String command)")}}
+
Returns the current value of the current range for a formating command.
+
{{domxref("document.write","document.write(String text)")}}
+
Writes text in a document.
+
{{domxref("document.writeln","document.writeln(String text)")}}
+
Writes a line of text in a document.
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('Page Visibility API', '#onvisiblitychange-event-handler', 'onvisibilitychange')}}{{Spec2('Page Visibility API')}}Adds onvisibilitychange.
{{SpecName('Selection API', '', 'Extend Document and GlobalEventHandlers')}}{{Spec2('Selection API')}}Adds onselectstart and onselectionchange.
{{SpecName('DOM1','#i-Document','Document')}}{{Spec2('DOM1')}}Initial definition for the interface
{{SpecName('DOM2 Core','#i-Document','Document')}}{{Spec2('DOM2 Core')}}Supersede DOM 1
{{SpecName('DOM3 Core','#i-Document','Document')}}{{Spec2('DOM3 Core')}}Supersede DOM 2
{{SpecName('DOM WHATWG','#interface-document','Document')}}{{Spec2('DOM WHATWG')}}Intend to supersede DOM 3
{{SpecName('HTML WHATWG','dom.html#the-document-object','Document')}}{{Spec2('HTML WHATWG')}}Turn the {{domxref("HTMLDocument")}} interface into a Document extension.
{{SpecName('DOM3 XPath','xpath.html#XPathEvaluator','XPathEvaluator')}}{{Spec2('DOM3 XPath')}}Define the {{domxref("XPathEvaluator")}} interface which extend document.
{{SpecName('Page Visibility API', '#sec-document-interface', 'Document')}}{{Spec2('Page Visibility API')}}Extend the Document interface with the visibilityState and hidden attributes
{{SpecName('HTML Editing','#dom-document-getselection','Document')}}{{Spec2('HTML Editing')}}Extend the Document interface
{{SpecName('CSSOM View','#extensions-to-the-document-interface','Document')}}{{Spec2('CSSOM View')}}Extend the Document interface
{{SpecName('CSSOM','#extensions-to-the-document-interface','Document')}}{{Spec2('CSSOM')}}Extend the Document interface
{{SpecName('Pointer Lock','#extensions-to-the-document-interface','Document')}}{{Spec2('Pointer Lock')}}Extend the Document interface
+ +

Notas de compatibilidade do navegador

+ +

Notas do Firefox

+ +

Mozilla defines a set of non-standard properties made only for XUL content:

+ +
+
{{domxref("document.currentScript")}} {{non-standard_inline}} {{gecko_minversion_inline("2.0")}}
+
Returns the {{HTMLElement("script")}} element that is currently executing.
+
{{domxref("document.documentURIObject")}} {{gecko_minversion_inline("1.9")}}
+
(Mozilla add-ons only!) Returns the {{Interface("nsIURI")}} object representing the URI of the document. This property only has special meaning in privileged JavaScript code (with UniversalXPConnect privileges).
+
{{domxref("document.popupNode")}}
+
Returns the node upon which a popup was invoked.
+
{{domxref("document.tooltipNode")}}
+
Returns the node which is the target of the current tooltip.
+
+ +

Mozilla also define some non-standard methods:

+ +
+
{{domxref("document.execCommandShowHelp")}} {{obsolete_inline("14.0")}}
+
This method never did anything and always threw an exception, so it was removed in Gecko 14.0 {{geckoRelease("14.0")}}.
+
{{domxref("document.getBoxObjectFor")}} {{obsolete_inline}}
+
Use the {{domxref("Element.getBoundingClientRect()")}} method instead.
+
{{domxref("document.loadOverlay")}} {{Fx_minversion_inline("1.5")}}
+
Loads a XUL overlay dynamically. This only works in XUL documents.
+
{{domxref("document.queryCommandText")}} {{obsolete_inline("14.0")}}
+
This method never did anything but throw an exception, and was removed in Gecko 14.0 {{geckoRelease("14.0")}}.
+
+ +

Notas do Internet Explorer

+ +

Microsoft defines some non-standard properties:

+ +
+
{{domxref("document.fileSize")}}* {{non-standard_inline}} {{obsolete_inline}}
+
Returns size in bytes of the document. Starting with Internet Explorer 11, that property is no longer supported. See MSDN.
+
Internet Explorer does not support all methods from the Node interface in the Document interface:
+
+ +
+
{{domxref("document.contains")}}
+
As a work-around, document.body.contains() can be used.
+
+ +

 

diff --git a/files/pt-pt/web/api/document/queryselector/index.html b/files/pt-pt/web/api/document/queryselector/index.html new file mode 100644 index 0000000000..e979e285d3 --- /dev/null +++ b/files/pt-pt/web/api/document/queryselector/index.html @@ -0,0 +1,134 @@ +--- +title: Document.querySelector() +slug: Web/API/Document/querySelector +tags: + - API + - DOM + - Document + - Elementos DOM + - Referencia + - Selector API + - Seletores CSS + - Seletors + - metodo + - querySelector +translation_of: Web/API/Document/querySelector +--- +
{{ApiRef("DOM")}}
+ +

O método querySelector() de {{domxref("Document")}} retorna o primeiro {{domxref("Element")}} dentro do documento que corresponde ao seletor, ou grupo de seleteores especificados. Se não há elementos que correspondem, null é devolvido como resultado.

+ +
+

Nota: A correspondência é feita através de uma travessia pre-order em profundidade dos nódulos do documento, a começar com o primeiro elemento da marcação do documento e iterando através de nódulos sequenciais por ordem do número de nódulos filhos.

+
+ +

Syntaxe

+ +
element = document.querySelector(selectors);
+
+ +

Parameteros

+ +
+
selectors
+
Um {{domxref("DOMString")}} a conter um ou mais seletores para com que corresponder. Esta string tem de ser um seletor de CSS valido; se não é, uma exception SYNTAX_ERR é lançada. Veja Localizar elementos do DOM a usar seletores para saber mais sobre seletor e como os gerir.
+
+ +
+

Nota: Os carateres que não fazem parte da sintaxe padrão do CSS devem ser evitados ao usar um caráter de barra invertida. Uma vez que o JavaScript também usa barra invertida para escapar, deve ter especial cuidado ao escrever string literals usando estes carateres. Veja {{anch("Escapar carateres especiais")}} para obter mais informação.

+
+ +

Resultado

+ +

Um objeto {{domxref("HTMLElement")}} a representar o primeiro elemento no documento que corresponde aos seletores de CSS, ou null se não há elementos correspondentes.

+ +

Se precisar de uma lista de todos os elementos que correspondem ao seletores especificados, deve usar {{domxref("Document.querySelectorAll", "querySelectorAll()")}}.

+ +

Exeções

+ +
+
SYNTAX_ERR
+
O syntaxe dos selectors especificados está incorrecto.
+
+ +

Notas de uso

+ +

Se o seletor especificado corresponde a um ID que é incorretamente utilizado mais que uma vez num documento, o primeiro elemento com esse ID será devolvido.

+ +

Pseudoelementos de CSS não devolvem elementos, como é especificado na API de seletores.

+ +

Escapar carateres especiais

+ +

Para corresponder a um ID ou seletor que não segue a sintaxe de CSS padrão (ao usar o caráter de dois pontos ou espaço incorretamente), deve escapar o caráter com uma barra invertida ("\"). Como a barra invertida também é um caráter de escapar no JavaScript, se a escrever numa string literal, tem de a escapar duas vezes (primeiro para a string do JavaScript, e depois para o querySelector()):

+ +
<div id="foo\bar"></div>
+<div id="foo:bar"></div>
+
+<script>
+  console.log('#foo\bar');               // "#fooar" (\b é o caráter de controlo para a barra invertida)
+  document.querySelector('#foo\bar');    // Corresponde a nada
+
+  console.log('#foo\\bar');              // "#foo\bar"
+  console.log('#foo\\\\bar');            // "#foo\\bar"
+  document.querySelector('#foo\\\\bar'); // Corresponde ao primeiro div
+
+  document.querySelector('#foo:bar');    // Corresponde a nada
+  document.querySelector('#foo\\:bar');  // Corresponde ao segundo div
+</script>
+ +

Exemplos

+ +

Encontrar o primeiro elemento que corresponde a uma classe

+ +

Neste exemplo, o primeiro elemento no documento com a classe myclass é devolvida:

+ +
var el = document.querySelector(".myclass");
+
+ +

Um seletor mais complexo

+ +

Seletores são muito poderosos, como demonstrado no seguinte exemplo. O primeiro elemento {{HTMLElement("input")}} com o nome "login" (<input name="login"/>) encontrado dentro dum {{HTMLElement("div")}} cuja classe é "user-panel main" (<div class="user-panel main">) no documento é devolvido:

+ +
var el = document.querySelector("div.user-panel.main input[name='login']");
+
+ +

Negação

+ +

Todos os strings de seletores de CSS são válidos, assim também é possivel ter seletores de negação:

+ +
var el = document.querySelector("div.user-panel:not(.main) input[name='login']");
+ +

Isto seléciona um input que tem um div com classe user-panel como parente, mas sem a classe main.

+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoEstado
{{SpecName("DOM WHATWG", "#dom-parentnode-queryselector", "document.querySelector()")}}{{Spec2("DOM WHATWG")}}
+ +

Compatibilidade

+ + + +
{{Compat("api.Document.querySelector")}}
+ +

Veja também

+ + diff --git a/files/pt-pt/web/api/document/visibilitychange_event/index.html b/files/pt-pt/web/api/document/visibilitychange_event/index.html new file mode 100644 index 0000000000..02df020b70 --- /dev/null +++ b/files/pt-pt/web/api/document/visibilitychange_event/index.html @@ -0,0 +1,148 @@ +--- +title: visibilitychange +slug: Web/API/Document/visibilitychange_event +translation_of: Web/API/Document/visibilitychange_event +--- +

O evento visibilitychange é ativado quando o conteúdo de um separador se torna visível ou foi ocultado.

+ +

Informação geral

+ +
+
Especificação
+
{{SpecName("Page Visibility API")}}
+
Interface
+
{{domxref("event")}}
+
Bubbles
+
Sim
+
Cancelável
+
Não
+
Destino
+
{{domxref("Document")}}
+
Ação Predefinida
+
 
+
None
+
+ +

Propriedades

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropriedadeTipoDescrição
target {{readonlyInline}}{{domxref("EventTarget")}}The event target (the topmost target in the DOM tree).
type {{readonlyInline}}{{domxref("DOMString")}}The type of event.
bubbles {{readonlyInline}}{{jsxref("Boolean")}}Whether the event normally bubbles or not.
cancelable {{readonlyInline}}{{jsxref("Boolean")}}Whether the event is cancellable or not.
+ +

Exemplo

+ +
document.addEventListener("visibilitychange", function() {
+  console.log( document.visibilityState );
+});
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('Page Visibility API','#sec-visibilitychange-event','visibilitychange')}}{{Spec2('Page Visibility API')}} 
+ +

Compatibilidade de navegador

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico13 {{property_prefix("webkit")}}
+ 33
{{CompatGeckoDesktop(10)}} {{property_prefix("moz")}}
+ {{CompatGeckoDesktop(18)}}
10 +

12.10[1]

+
6.1
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FuncionalidadeAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Suporte básico4.4 {{property_prefix("webkit")}}{{CompatGeckoMobile(10)}} {{property_prefix("moz")}}
+ {{CompatGeckoMobile(18)}}
{{CompatUnknown}}12.10 [1]7
+
+ +

[1] Doesn't fire the visibilitychange event when the browser window is minimized, nor set hidden to true.

+ +

Consultar também

+ + diff --git a/files/pt-pt/web/api/domstring/index.html b/files/pt-pt/web/api/domstring/index.html new file mode 100644 index 0000000000..abd4b8962e --- /dev/null +++ b/files/pt-pt/web/api/domstring/index.html @@ -0,0 +1,43 @@ +--- +title: DOMString +slug: Web/API/DOMString +tags: + - API + - DOM + - Referencia + - String +translation_of: Web/API/DOMString +--- +
{{APIRef("DOM")}}
+ +

DOMString é uma string codificada em UTF-16. Como a JavaScript já usa strings deste tipo, DOMString é mapeado diretamente a uma {{jsxref("String")}}.

+ +

Passar {{jsxref("null")}} a um método ou parametro que aceita uma DOMString tipicamente é convertido para uma string com o valor "null".

+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('WebIDL', '#idl-DOMString', 'DOMString')}}{{Spec2('WebIDL')}}
+ +

Ver também

+ + diff --git a/files/pt-pt/web/api/eventos_de_luz_ambiente/index.html b/files/pt-pt/web/api/eventos_de_luz_ambiente/index.html new file mode 100644 index 0000000000..32b15a8ea1 --- /dev/null +++ b/files/pt-pt/web/api/eventos_de_luz_ambiente/index.html @@ -0,0 +1,70 @@ +--- +title: Eventos de Luz Ambiente +slug: Web/API/Eventos_de_Luz_Ambiente +tags: + - Luz Ambiente +translation_of: Web/API/Ambient_Light_Events +--- +
{{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/file/index.html b/files/pt-pt/web/api/file/file/index.html new file mode 100644 index 0000000000..a785c59a41 --- /dev/null +++ b/files/pt-pt/web/api/file/file/index.html @@ -0,0 +1,71 @@ +--- +title: File.File() +slug: Web/API/File/File +tags: + - API + - Construtor + - File API + - Referencia +translation_of: Web/API/File/File +--- +
{{APIRef("File")}}
+ +

O construtor File() cria uma instância do objeto {{domxref("File")}}.

+ +

Sintaxe

+ +
new File(bits, name[, options]);
+ +

Parâmetros

+ +
+
bits
+
Uma {{jsxref("Array")}} de objetos {{jsxref("ArrayBuffer")}}, {{domxref("ArrayBufferView")}}, {{domxref("Blob")}}, {{domxref("USVString")}}, ou um misto de tais objetos, que será posto no {{domxref("File")}}. Objetos USVString são codificados em UTF-8.
+
name
+
Uma {{domxref("USVString")}} que representa o nome do ficheiro ou o caminho para o ficheiro.
+
options {{optional_inline}}
+
Um objeto com atributos opcionais para o ficheiro. As opções disponíveis são: +
    +
  • type: Uma {{domxref("DOMString")}} que representa o tipo MIME do conteúdo será posto no ficheiro. Tem um valor pré-definido de "".
  • +
  • lastModified: Um número que representa o número de milissegundos entre o início da era Unix e a última data em que o ficheiro foi modificado. Tem um valor pré-definido de {{jsxref("Date.now()")}}.
  • +
+
+
+ +

Exemplo

+ +
var file = new File(["foo"], "foo.txt", {
+  type: "text/plain",
+});
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentários
{{SpecName('File API')}}{{Spec2('File API')}}Definição inicial
+ +

Compatibilidade

+ + + +

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

+ +

Ver também

+ + diff --git a/files/pt-pt/web/api/file/filename/index.html b/files/pt-pt/web/api/file/filename/index.html new file mode 100644 index 0000000000..0e0ee197ae --- /dev/null +++ b/files/pt-pt/web/api/file/filename/index.html @@ -0,0 +1,37 @@ +--- +title: File.fileName +slug: Web/API/File/fileName +tags: + - API + - DOM + - Ficheiros + - File API + - Non-standard + - Obsoleto + - Propriedade + - Referencia +translation_of: Web/API/File/fileName +--- +
{{APIRef("File API")}}{{non-standard_header}} {{obsolete_header(7.0)}}
+ +

Retorna o nome do ficheiro. Por razões de segurança o caminho é excluído desta propriedade.

+ +
Esta propriedade está obsoleta. Use antes {{domxref("File.name")}}.
+ +

Sintaxe

+ +
var name = instanceOfFile.fileName;
+ +

Valor

+ +

Uma string

+ +

Especificação

+ +

Não faz parte duma especificação.

+ +

Ver também

+ + diff --git a/files/pt-pt/web/api/file/filesize/index.html b/files/pt-pt/web/api/file/filesize/index.html new file mode 100644 index 0000000000..e17676ecee --- /dev/null +++ b/files/pt-pt/web/api/file/filesize/index.html @@ -0,0 +1,37 @@ +--- +title: File.fileSize +slug: Web/API/File/fileSize +tags: + - API + - DOM + - Ficheiros + - File API + - Non-standard + - Obsoleto + - Propriedade + - Referencia +translation_of: Web/API/File/fileSize +--- +

{{APIRef("File API") }}{{non-standard_header}} {{deprecated_header(7.0)}}

+ +

Retorna o tamanho do ficheiro em bytes.

+ +
Esta propriedade está obsoleta. Use antes {{domxref("Blob.size")}}.
+ +

Sintaxe

+ +
var size = instanceOfFile.fileSize;
+ +

Valor

+ +

Um número.

+ +

Especificação

+ +

Não faz parte de nenhuma especificação.

+ +

Ver também

+ + diff --git a/files/pt-pt/web/api/file/getasbinary/index.html b/files/pt-pt/web/api/file/getasbinary/index.html new file mode 100644 index 0000000000..8ec42cf1f2 --- /dev/null +++ b/files/pt-pt/web/api/file/getasbinary/index.html @@ -0,0 +1,77 @@ +--- +title: File.getAsBinary() +slug: Web/API/File/getAsBinary +tags: + - API + - Ficheiros + - File API + - Non-standard + - Obsoleto + - Referencia + - metodo +translation_of: Web/API/File/getAsBinary +--- +

{{APIRef("File API")}}

+ +

{{non-standard_header}}

+ +

{{obsolete_header(7.0)}}

+ +

Sumário

+ +

O método getAsBinary permite aceder aos dados de um ficheiro num formato raw binário.

+ +
+

Nota: Este método é obsoleto; use antes o método {{domxref("FileReader.readAsBinaryString()","readAsBinaryString()")}} ou {{domxref("FileReader.readAsArrayBuffer()","readAsArrayBuffer()")}} de {{domxref("FileReader")}}.

+
+ +

Sintaxe

+ +
var binary = instanceOfFile.getAsBinary();
+ +

Retorna

+ +

Uma string.

+ +

Exemplo

+ +
// fileInput é um HTMLInputElement: <input type="file" id="myfileinput" multiple>
+var fileInput = document.getElementById("myfileinput");
+
+// files é um objeto de FileList (parecido ao NodeList)
+var files = fileInput.files;
+
+// objeto com os tipos de media permitidos
+var accept = {
+  binary : ["image/png", "image/jpeg"],
+  text   : ["text/plain", "text/css", "application/xml", "text/html"]
+};
+
+var file;
+
+for (var i = 0; i < files.length; i++) {
+  file = files[i];
+
+  // se o ficheiro pode ser detetado
+  if (file !== null) {
+    if (accept.binary.indexOf(file.type) > -1) {
+      // file contem dados binarios, num formato permitido
+      var data = file.getAsBinary();
+    } else if (accept.text.indexOf(file.type) > -1) {
+      // file contem texto, num formato permitido
+      var data = file.getAsText();
+      // modificar dados com métodos de string
+    }
+  }
+}
+ +

Especificação

+ +

Não pertence a nenhuma especificação.

+ +

Ver também

+ + diff --git a/files/pt-pt/web/api/file/getasdataurl/index.html b/files/pt-pt/web/api/file/getasdataurl/index.html new file mode 100644 index 0000000000..e3e5bae4b3 --- /dev/null +++ b/files/pt-pt/web/api/file/getasdataurl/index.html @@ -0,0 +1,67 @@ +--- +title: File.getAsDataURL() +slug: Web/API/File/getAsDataURL +tags: + - API + - Ficheiros + - File API + - Non-standard + - Obsoleto + - Referencia + - metodo +translation_of: Web/API/File/getAsDataURL +--- +
{{APIRef("File API") }}
+ +

{{non-standard_header}}

+ +

{{deprecated_header(7.0)}}

+ +

Sumário

+ +

O método getAsDataURL retorna um URL em estilo data: que codifica todo o conteúdo do ficheiro em questão.

+ +
+

Nota: Este método está obsoleto: use antes o método  {{domxref("FileReader.readAsDataURL","readAsDataURL()")}} de {{domxref("FileReader")}}.

+
+ +

Sintaxe

+ +
var url = instanceOfFile.getAsDataURL();
+ +

Retorna

+ +

Uma string a representar um URL de estilo data:

+ +

Exemplo

+ +
// fileInput é um HTMLInputElement: <input type="file" id="myfileinput" multiple>
+var fileInput = document.getElementById("myfileinput");
+
+// files é um objeto FileList (parecido ao NodeList)
+var files = fileInput.files;
+
+// accept é um array com tipos de ficheiros aceites
+var accept = ["image/png"];
+
+// img é um HTMLImgElement: <img id="myimg">
+var img = document.getElementById("myimg");
+
+// se aceitamos o primeiro tipo de ficheiro selecionado
+if (accept.indexOf(files[0].mediaType) > -1) {
+  // apresentar a imagem
+  // igual a <img src="data:image/png,<imagedata>">
+  img.src = files[0].getAsDataURL();
+}
+
+ +

Especificação

+ +

Não pertence a nenhuma especificação.

+ +

Ver também

+ + diff --git a/files/pt-pt/web/api/file/getastext/index.html b/files/pt-pt/web/api/file/getastext/index.html new file mode 100644 index 0000000000..b20229737e --- /dev/null +++ b/files/pt-pt/web/api/file/getastext/index.html @@ -0,0 +1,83 @@ +--- +title: File.getAsText() +slug: Web/API/File/getAsText +tags: + - API + - Ficheiros + - File API + - Non-standard + - Obsoleto + - Referencia + - metodo +translation_of: Web/API/File/getAsText +--- +

{{APIRef("File API") }}{{non-standard_header}}

+ +

{{obsolete_header(7.0)}}

+ +

Sumário

+ +

O método getAsText oferece os dados do ficheiro num formato de texto de acordo com uma codificação.

+ +
+

Note: Este método está obsoleto; use antes o método {{domxref("FileReader.readAsText()","readAsText()")}} de {{domxref("FileReader")}}.

+
+ +

Sintaxe

+ +
var str = instanceOfFile.getAsText(encoding);
+ +

Parâmetros

+ +
+
encoding
+
Uma string a indicar qual a codificação para usar nos dados devolvidos. Se o string estiver vazio, é utilizado UTF-8.
+
+ +

Retorna

+ +

A string que contem os dados do ficheiro num formato de texto especificado pelo encoding.

+ +

Exemplo

+ +
// fileInput é um HTMLInputElement: <input type="file" id="myfileinput" multiple>
+var fileInput = document.getElementById("myfileinput");
+
+// files é um objeto de FileList (parecido ao NodeList)
+var files = fileInput.files;
+
+// object com os formatos de media validos
+var accept = {
+  binary : ["image/png", "image/jpeg"],
+  text   : ["text/plain", "text/css", "application/xml", "text/html"]
+};
+
+var file;
+
+for (var i = 0; i < files.length; i++) {
+  file = files[i];
+
+  // se o formato do ficheiro foi detetado
+  if (file !== null) {
+    if (accept.text.indexOf(file.mediaType) > -1) {
+      // file contem texto, num formato permitido
+      // make sure it's encoded as utf-8
+      var data = file.getAsText("utf-8");
+      // modificar dados com métodos de string
+
+    } else if (accept.binary.indexOf(file.mediaType) > -1) {
+      // binario
+    }
+  }
+}
+ +

Especificação

+ +

Não pertence a nenhuma especificação.

+ +

Ver também

+ + diff --git a/files/pt-pt/web/api/file/index.html b/files/pt-pt/web/api/file/index.html new file mode 100644 index 0000000000..43e85438cb --- /dev/null +++ b/files/pt-pt/web/api/file/index.html @@ -0,0 +1,101 @@ +--- +title: File +slug: Web/API/File +tags: + - API + - File API + - Interface + - NeedsTranslation + - Reference + - TopicStub + - Web +translation_of: Web/API/File +--- +
{{APIRef}}
+ +

The File interface provides information about files and allows JavaScript in a web page to access their content.

+ +

File objects are generally retrieved from a {{DOMxRef("FileList")}} object returned as a result of a user selecting files using the {{HTMLElement("input")}} element, from a drag and drop operation's {{DOMxRef("DataTransfer")}} object, or from the mozGetAsFile() API on an {{DOMxRef("HTMLCanvasElement")}}.

+ +

A File object is a specific kind of a {{DOMxRef("Blob")}}, and can be used in any context that a Blob can. In particular, {{DOMxRef("FileReader")}}, {{DOMxRef("URL.createObjectURL()")}}, {{DOMxRef("ImageBitmapFactories.createImageBitmap()", "createImageBitmap()")}}, and {{DOMxRef("XMLHttpRequest", "", "send()")}} accept both Blobs and Files.

+ +

See Using files from web applications for more information and examples.

+ +

{{InheritanceDiagram}}

+ +

Constructor

+ +
+
{{DOMxRef("File.File", "File()")}}
+
Returns a newly constructed File.
+
+ +

Instance properties

+ +
+
{{DOMxRef("File.prototype.lastModified")}} {{ReadOnlyInline}}
+
Returns the last modified time of the file, in millisecond since the UNIX epoch (January 1st, 1970 at Midnight).
+
{{DOMxRef("File.prototype.lastModifiedDate")}} {{Deprecated_Inline}} {{ReadOnlyInline}}
+
Returns the last modified {{JSxRef("Date")}} of the file referenced by the File object.
+
{{DOMxRef("File.prototype.name")}}{{ReadOnlyInline}}
+
Returns the name of the file referenced by the File object.
+
{{DOMxRef("File.prototype.webkitRelativePath")}} {{Non-standard_Inline}} {{ReadOnlyInline}}
+
Returns the path the URL of the {{DOMxRef("File")}} is relative to.
+
+ +

File implements {{DOMxRef("Blob")}}, so it also has the following properties available to it:

+ +
+
{{DOMxRef("File.prototype.size")}} {{ReadOnlyInline}}
+
Returns the size of the file in bytes.
+
{{DOMxRef("File.prototype.type")}} {{ReadOnlyInline}}
+
Returns the MIME type of the file.
+
+ +

Instance methods

+ +

The File interface doesn't define any methods, but inherits methods from the {{DOMxRef("Blob")}} interface:

+ +
+
{{DOMxRef("Blob.prototype.slice()", "Blob.prototype.slice([start[, end[, contentType]]])")}}
+
Returns a new Blob object containing the data in the specified range of bytes of the source Blob.
+
{{DOMxRef("Blob.prototype.stream()")}}
+
Transforms the File into a {{DOMxRef("ReadableStream")}} that can be used to read the File contents.
+
{{DOMxRef("Blob.prototype.text()")}}
+
Transforms the File into a stream and reads it to completion. It returns a promise that resolves with a {{DOMxRef("USVString")}} (text).
+
{{DOMxRef("Blob.prototype.arrayBuffer()")}}
+
Transforms the File into a stream and reads it to completion. It returns a promise that resolves with an {{DOMxRef("ArrayBuffer")}}.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('File API', "#file-section", "The File interface")}}{{Spec2('File API')}}Initial definition.
+ +

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/pt-pt/web/api/file/lastmodified/index.html b/files/pt-pt/web/api/file/lastmodified/index.html new file mode 100644 index 0000000000..9b05f6f3cf --- /dev/null +++ b/files/pt-pt/web/api/file/lastmodified/index.html @@ -0,0 +1,113 @@ +--- +title: File.lastModified +slug: Web/API/File/lastModified +tags: + - API + - Ficheiros + - File API + - Propriedade + - Referencia +translation_of: Web/API/File/lastModified +--- +
{{APIRef("File")}}
+ +

A propriedade read-only File.lastModified indica a ultima data em que o ficheiro foi modificado, na forma do numero de milissegundos desde o início da era Unix (1 de janeiro de 1970 às 00:00:00). Os ficheiros cuja a data da última modificação não é conhecida devolvem a data actual.

+ +

Sintaxe

+ +
const tempo = instanciaDeFicheiro.lastModified;
+
+ +

Valor

+ +

Um número que representa o número de milissegundos desde o início da época do Unix.

+ +

Exemplo

+ +

Leitura a partir da entrada do ficheiro

+ +
<input type="file" multiple id="entradaDeFicheiro">
+
+ +
const entradaDeFicheiro = document.querySelector('#entradaDeFicheiro');
+entradaDeFicheiro.addEventListener('change', (event) => {
+  // ficheiros é um objeto de FileList (semelhante a NodeList)
+  const ficheiros = event.target.files;
+
+  for (let ficheiro of ficheiros) {
+    const data = new Date(ficheiro.lastModified);
+    console.log(`${ficheiro.name} tem uma última data modificada de ${data}`);
+  }
+});
+
+ +

Veja os resultados abaixo:

+ +

{{ EmbedLiveSample('Leitura_a_partir_da_entrada_do_ficheiro', 300, 50) }}

+ +

Ficheiros criados dinamicamente

+ +

Se um objeto File for criado dinamicamente, a última data modificada pode ser fornecida na função construtor {{domxref("File.File()", "new File()")}}. Se estiver em falta, lastModified herda a hora actual de {{jsxref("Date.now()")}} no momento em que o objeto File é criado.

+ +
const ficheiroComData = new File([], 'file.bin', {
+  lastModified: new Date(2017, 1, 1),
+});
+console.log(ficheiroComData.lastModified); //devolve 1485903600000
+
+const ficheiroSemData = new File([], 'file.bin');
+console.log(ficheiroSemData.lastModified); //devolve data atual em milissegundos
+
+ +

Reduced time precision

+ +

To offer protection against timing attacks and fingerprinting, the precision of someFile.lastModified might get rounded depending on browser settings.
+ In Firefox, the privacy.reduceTimerPrecision  preference is enabled by default and defaults to 20us in Firefox 59; in 60 it will be 2ms.

+ +
// reduced time precision (2ms) in Firefox 60
+someFile.lastModified;
+// 1519211809934
+// 1519211810362
+// 1519211811670
+// ...
+
+
+// reduced time precision with `privacy.resistFingerprinting` enabled
+someFile.lastModified;
+// 1519129853500
+// 1519129858900
+// 1519129864400
+// ...
+
+ +

In Firefox, you can also enabled privacy.resistFingerprinting, the precision will be 100ms or the value of privacy.resistFingerprinting.reduceTimerPrecision.microseconds, whichever is larger.

+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentários
{{SpecName('File API', '#file-attrs', 'lastModified')}}{{Spec2('File API')}}Definição inicial.
+ +

Compatibilidade

+ + + +

{{Compat("api.File.lastModified")}}

+ +

Ver também

+ + diff --git a/files/pt-pt/web/api/file/lastmodifieddate/index.html b/files/pt-pt/web/api/file/lastmodifieddate/index.html new file mode 100644 index 0000000000..10d5d8c932 --- /dev/null +++ b/files/pt-pt/web/api/file/lastmodifieddate/index.html @@ -0,0 +1,80 @@ +--- +title: File.lastModifiedDate +slug: Web/API/File/lastModifiedDate +tags: + - API + - Ficheiros + - File + - File API + - Obsoleto + - Propriedade + - Read-only + - Referencia + - lastDateModified +translation_of: Web/API/File/lastModifiedDate +--- +
{{APIRef("File API") }} {{deprecated_header}}
+ +

A propriedade read-only File.lastModifiedDate devolve a ultima data em que o ficheiro foi modificado. Ficheiros onde a ultima data de modificação é desconhecida devolvem a data atual.

+ +

Sintaxe

+ +
var time = instanceOfFile.lastModifiedDate
+ +

Valor

+ +

Um objeto Date a indicar a data e hora da ultima modificação ao ficheiro.

+ +

Exemplo

+ +
// fileInput é um HTMLInputElement: <input type="file" multiple id="myfileinput">
+var fileInput = document.getElementById("myfileinput");
+
+// files é um objeto de FileList (parecido ao NodeList)
+var files = fileInput.files;
+
+for (var i = 0; i < files.length; i++) {
+  alert(files[i].name + " has a last modified date of " + files[i].lastModifiedDate);
+}
+ +

Precisão reduzida

+ +

Para oferecer proteção contra timing attacks e fingerprinting a precisão de someFile.lastModifiedDate.getTime() pode ser arredondada dependente das preferências no navegador.

+ +

No Firefox, a preferência privacy.reduceTimerPrecision está ligada por pré-definição com valores arredondados aos 20μs mais próximos no Firefox 59; e no Firefox 60 aos 2ms.

+ +
// precisão reduzida (2ms) no Firefox 60
+someFile.lastModifiedDate.getTime();
+// 1519211809934
+// 1519211810362
+// 1519211811670
+// ...
+
+
+// precisão reduzida com a `privacy.resistFingerprinting` ligada
+someFile.lastModifiedDate.getTime();
+// 1519129853500
+// 1519129858900
+// 1519129864400
+// ...
+
+ +

No Firefox, também pode ligar a preferência privacy.resistFingerprinting, a precisão será arredondada aos 100ms mais próximos ou ao valor de privacy.resistFingerprinting.reduceTimerPrecision.microseconds, o que for maior.

+ +

Especificações

+ +

Apesar de estar presente numa versão inicial do esboço do File API spec, esta propriedade foi removida e agora é non-standard. Use antes {{domxref("File.lastModified")}}.

+ +

Compatibilidade

+ +
+ + +

{{Compat("api.File.lastModifiedDate")}}

+
+ +

Ver também

+ + diff --git a/files/pt-pt/web/api/file/mozfullpath/index.html b/files/pt-pt/web/api/file/mozfullpath/index.html new file mode 100644 index 0000000000..24e126847f --- /dev/null +++ b/files/pt-pt/web/api/file/mozfullpath/index.html @@ -0,0 +1,17 @@ +--- +title: File.mozFullPath +slug: Web/API/File/mozFullPath +tags: + - API + - Ficheiros + - File + - File API + - Non-standard + - Propriedade + - Referencia + - mozFullPath +translation_of: Web/API/File/mozFullPath +--- +
{{APIRef("File API")}}{{draft}}{{Non-standard_header}}
+ +

Uma extensão privilegiada para a interface {{domxref("File")}}, a propriedade mozFullPath contém o caminho completo do ficheiro representado. Esta propriedade só está disponível a partir do código do navegador ou de extensões Firefox ao estilo antigo com base no XPCOM. Não está disponível para o conteúdo da web.

diff --git a/files/pt-pt/web/api/file/name/index.html b/files/pt-pt/web/api/file/name/index.html new file mode 100644 index 0000000000..907a08a8e2 --- /dev/null +++ b/files/pt-pt/web/api/file/name/index.html @@ -0,0 +1,74 @@ +--- +title: File.name +slug: Web/API/File/name +tags: + - API + - File API + - Files + - Propriadade + - Referencia +translation_of: Web/API/File/name +--- +
{{APIRef("File API")}}
+ +
Devolve o nome do ficheiro representado por um objeto {{domxref("File")}}. Por razões de segurança, o caminho é excluído desta propriedade.
+ +

Sintaxe

+ +
var name = file.name;
+ +

Valor

+ +

Uma string, que contem o nome do ficheiro sem o caminho, por exemplo "O meu Resumo.rtf".

+ +

Exemplo

+ +
<input type="file" multiple onchange="processSelectedFiles(this)">
+
+ +
function processSelectedFiles(fileInput) {
+  var files = fileInput.files;
+
+  for (var i = 0; i < files.length; i++) {
+    alert("Filename " + files[i].name);
+  }
+}
+ +

Veja os resultados abaixo:

+ +

{{ EmbedLiveSample('Exemplo', 300, 50) }}

+ + + +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('File API', '#file-attrs', 'name')}}{{Spec2('File API')}}Definição inicial.
+ +

Compatibilidade

+ +
+ + +

{{Compat("api.File.name")}}

+
+ +

Ver também

+ + diff --git a/files/pt-pt/web/api/file/type/index.html b/files/pt-pt/web/api/file/type/index.html new file mode 100644 index 0000000000..2b448d3086 --- /dev/null +++ b/files/pt-pt/web/api/file/type/index.html @@ -0,0 +1,75 @@ +--- +title: File.type +slug: Web/API/File/type +tags: + - API + - Ficheiros + - File API + - Propriedade + - Referencia + - Tipo de Ficheiro +translation_of: Web/API/File/type +--- +
{{APIRef("File API")}}
+ +

Retorna a média (MIME) representado por um objeto {{domxref("File")}}.

+ +

Sintaxe

+ +
var name = file.type;
+ +

Valor

+ +

Uma string, que contem o tipo de média (MIME) que indica o tipo do ficheiro, por exemplo "image/png" é devolvido para imagens PNG.

+ +

Exemplo

+ +
<input type="file" multiple onchange="showType(this)">
+
+ +
function showType(fileInput) {
+  var files = fileInput.files;
+
+  for (var i = 0; i < files.length; i++) {
+    var name = files[i].name;
+    var type = files[i].type;
+    alert("Filename: " + name + " , Type: " + type);
+  }
+}
+ +
+


+ Nota: Baseado na atual implementação, navegadores não leem a bytestream dum ficheiro para determinar a sua média. É feito uma ilação baseada na extensão do ficheiro; uma imagem PNG com uma extensão ".txt" é atribuída o tipo "text/plain" e não "image/png". Além disso, file.type é geralmente fiável apenas para ficheiros comuns como imagens, documentos HTML, áudio e vídeo. Extensões de ficheiros pouco comuns devolveriam uma cadeia de caracteres vazia. A configuração do cliente (por exemplo, o Registo do Windows) pode resultar em valores inesperados mesmo para tipos comuns. Os programadores são aconselhados a não confiar nesta propriedade como o único esquema de validação.

+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('File API', '#dfn-type', 'type')}}{{Spec2('File API')}}Definição inicial
+ +

Compatibilidade

+ + + +

{{Compat("api.File.type")}}

+ +

Ver também

+ + diff --git a/files/pt-pt/web/api/file/webkitrelativepath/index.html b/files/pt-pt/web/api/file/webkitrelativepath/index.html new file mode 100644 index 0000000000..35f155c1c6 --- /dev/null +++ b/files/pt-pt/web/api/file/webkitrelativepath/index.html @@ -0,0 +1,80 @@ +--- +title: File.webkitRelativePath +slug: Web/API/File/webkitRelativePath +tags: + - Ficheiro +translation_of: Web/API/File/webkitRelativePath +--- +

{{APIRef("File API")}}

+ +

O File.webkitRelativePath é uma propriedade só de leitura que contém um {{domxref("USVString")}} que especifica o caminho do ficheiro em relação ao diretório selecionado pelo utilizador num elemento {{HTMLElement("input")}} com o seu conjunto de atributos {{htmlattrxref("webkitdirectory", "input")}}.

+ +

Sintaxe

+ +
 relativePath = File.webkitRelativePath
+ +

Valor

+ +

Um {{domxref("USVString")}} que contem o caminho do ficheiro relativo ao diretório dos antepassados que o utilizador selecionou.

+ +

Exemplo

+ +

Neste exemplo, é apresentado um seletor de diretórios que permite ao utilizador escolher um ou mais diretórios. Quando o evento {{event("change")}} ocorre, é gerada e apresentada uma lista de todos os ficheiros contidos dentro das hierarquias de diretórios selecionados.

+ +

Conteúdo HTML

+ +
<input type="file" id="seletorDeFicheiros" name="listaDeFicheiros" webkitdirectory multiple />
+<ul id="listagem"></ul>
+ +

Conteúdo JavaScript

+ +
document.getElementById("seletorDeFicheiros").addEventListener("change", function(event) {
+  let output = document.getElementById("listagem");
+  let ficheiros = event.target.files;
+
+  for (let i = 0; i < ficheiros.length; i++) {
+    let item = document.createElement("li");
+    item.innerHTML = ficheiros[i].webkitRelativePath;
+    output.appendChild(item);
+  };
+}, false);
+
+ +

Resultado

+ +

{{ EmbedLiveSample('Example') }}

+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{ SpecName('File System API', '#dom-file-webkitrelativepath', 'webkitRelativePath') }}{{ Spec2('File System API') }}Definição inicial.
+ +

Esta IPA não tem especificação oficial do W3C ou do WHATWG.

+ +

Compatibilidade

+ + + +

{{Compat("api.File.webkitRelativePath")}}

+ +

Ver também

+ + diff --git a/files/pt-pt/web/api/filereader/abort/index.html b/files/pt-pt/web/api/filereader/abort/index.html new file mode 100644 index 0000000000..3ffeae8ce9 --- /dev/null +++ b/files/pt-pt/web/api/filereader/abort/index.html @@ -0,0 +1,58 @@ +--- +title: FileReader.abort() +slug: Web/API/FileReader/abort +tags: + - API + - Ficheiros + - File API + - FileReader + - Referencia + - abort + - metodo +translation_of: Web/API/FileReader/abort +--- +
{{APIRef("File API")}}
+ +

O método abort aborta a operação de leitura. Ao completar o abortamento, o {{domxref("FileReader.readyState","readyState")}} é DONE.

+ +

Sintaxe

+ +
instanceOfFileReader.abort();
+ +

Exceções

+ +
+
DOM_FILE_ABORT_ERR
+
Lançado quando abort é chamado enquanto não há uma operação de leitura em progresso (ou seja, quando o state não é LOADING).
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName("File API", "#abort", "abort()")}}{{Spec2("File API")}}Definição inicial
+ +

Compatibilidade

+ + + +

{{Compat("api.FileReader.abort")}}

+ +

Ver também

+ + diff --git a/files/pt-pt/web/api/filereader/error/index.html b/files/pt-pt/web/api/filereader/error/index.html new file mode 100644 index 0000000000..b308705d79 --- /dev/null +++ b/files/pt-pt/web/api/filereader/error/index.html @@ -0,0 +1,54 @@ +--- +title: FileReader.error +slug: Web/API/FileReader/error +tags: + - API + - Ficheiros + - File API + - Propriedade + - Referencia +translation_of: Web/API/FileReader/error +--- +
{{APIRef("File API")}}
+ +

A propriedade error de {{domxref("FileReader")}} retorna o erro que ocorreu ao ler o ficheiro.

+ +

Sintaxe

+ +
var error = instanceOfFileReader.error
+
+ +

Valor

+ +

Um {{domxref("DOMError")}} com o erro. Em Chrome 48+/Firefox 58+ esta propriedade retorna uma {{domxref("DOMException")}} porque DOMError foi removido do standard do DOM.

+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentários
{{SpecName("File API", "#dom-filereader-error", "FileReader: error")}}{{Spec2("File API")}}Definição inicial
+ +

Compatibilidade

+ + + +

{{Compat("api.FileReader.error")}}

+ +

Ver também

+ + diff --git a/files/pt-pt/web/api/filereader/index.html b/files/pt-pt/web/api/filereader/index.html new file mode 100644 index 0000000000..0df369c585 --- /dev/null +++ b/files/pt-pt/web/api/filereader/index.html @@ -0,0 +1,172 @@ +--- +title: FileReader +slug: Web/API/FileReader +tags: + - API + - DOM + - File API + - Files + - NeedsTranslation + - Reference + - TopicStub + - WebAPI +translation_of: Web/API/FileReader +--- +

{{ APIRef("File API") }}

+ +

Summary

+ +

The FileReader object lets web applications asynchronously read the contents of files (or raw data buffers) stored on the user's computer, using {{ domxref("File") }} or {{ domxref("Blob") }} objects to specify the file or data to read.

+ +

File objects may be obtained from a {{ domxref("FileList") }} object returned as a result of a user selecting files using the {{ HTMLElement("input") }} element, from a drag and drop operation's DataTransfer object, or from the mozGetAsFile() API on an {{ domxref("HTMLCanvasElement") }}.

+ +

Constructor

+ +
FileReader FileReader();
+ +

See Using files from web applications for details and examples.

+ +

Properties

+ +
+
{{domxref("FileReader.error")}} {{readonlyinline}}
+
A {{domxref("DOMError")}} representing the error that occurred while reading the file.
+
{{domxref("FileReader.readyState")}} {{readonlyinline}}
+
A number indicating the state of the FileReader. This will be one of the {{ anch("State constants") }}.
+
{{domxref("FileReader.result")}} {{readonlyinline}}
+
The file's contents. This property is only valid after the read operation is complete, and the format of the data depends on which of the methods was used to initiate the read operation.
+
+ +

Event handlers

+ +
+
{{domxref("FileReader.onabort")}}
+
A handler for the {{event("abort")}} event. This event is triggered each time the reading operation is aborted.
+
{{domxref("FileReader.onerror")}}
+
A handler for the {{event("error")}} event. This event is triggered each time the reading operation encounter an error.
+
{{domxref("FileReader.onload")}}
+
A handler for the {{event("load")}} event. This event is triggered each time the reading operation is successfully completed.
+
{{domxref("FileReader.onloadstart")}}
+
A handler for the {{event("loadstart")}} event. This event is triggered each time the reading is starting.
+
{{domxref("FileReader.onloadend")}}
+
A handler for the {{event("loadend")}} event. This event is triggered each time the reading operation is completed (either in success or failure).
+
{{domxref("FileReader.onprogress")}}
+
A handler for the {{event("progress")}} event. This event is triggered while reading a {{domxref("Blob")}} content.
+
+ +
+

Note: As FileReader inherits from {{domxref("EventTarget")}}, all those events can also be listened for by using the {{domxref("EventTarget.addEventListener()","addEventListener")}} method.

+
+ +

State constants

+ + + +

Methods

+ +
+
{{domxref("FileReader.abort()")}}
+
Aborts the read operation. Upon return, the readyState will be DONE.
+
{{domxref("FileReader.readAsArrayBuffer()")}} {{ gecko_minversion_inline("7.0") }}
+
Starts reading the contents of the specified {{ domxref("Blob") }}, once finished, the result attribute contains an {{domxref("ArrayBuffer")}} representing the file's data.
+
{{domxref("FileReader.readAsBinaryString()")}}
+
Starts reading the contents of the specified {{ domxref("Blob") }}, once finished, the result attribute contains the raw binary data from the file as a string.
+
{{domxref("FileReader.readAsDataURL()")}}
+
Starts reading the contents of the specified {{ domxref("Blob") }}, once finished, the result attribute contains a data: URL representing the file's data.
+
{{domxref("FileReader.readAsText()")}}
+
Starts reading the contents of the specified {{ domxref("Blob") }}, once finished, the result attribute contains the contents of the file as a text string.
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('File API','#FileReader-interface','FileReader')}}{{Spec2('File API')}}Initial definition.
+ +

Browser compatibility

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox (Gecko)ChromeInternet Explorer*Opera*Safari
Basic support{{ CompatGeckoDesktop("1.9.2") }}71012.026.0.2
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari Mobile
Basic support3231011.56.1
+
+ +

Implementation notes

+ + + +

Gecko-specific notes

+ + + +

See also

+ + diff --git a/files/pt-pt/web/api/filereader/readasarraybuffer/index.html b/files/pt-pt/web/api/filereader/readasarraybuffer/index.html new file mode 100644 index 0000000000..d5122d8096 --- /dev/null +++ b/files/pt-pt/web/api/filereader/readasarraybuffer/index.html @@ -0,0 +1,64 @@ +--- +title: FileReader.readAsArrayBuffer() +slug: Web/API/FileReader/readAsArrayBuffer +tags: + - API + - DOM + - Ficheiros + - File API + - FileReader + - Referencia + - metodo + - readAsArrayBuffer +translation_of: Web/API/FileReader/readAsArrayBuffer +--- +

{{APIRef("File API")}}

+ +

O método readAsArrayBuffer() da interface {{domxref("FileReader")}} é utilizado para começar a ler o conteúdo de um {{domxref("Blob")}} ou {{domxref("File")}} especificado. Quando a operação de leitura termina, o valor de {{domxref("FileReader.readyState","readyState")}} passa a ser DONE, e é acionado o evento {{domxref("FileReader/loadend_event", "loadend")}}. Nessa altura, o atributo {{domxref("FileReader.result","result")}} contém um {{domxref("ArrayBuffer")}} representando os dados do ficheiro.

+ +
+

API mais recente
+ O método {{domxref("Blob.arrayBuffer()")}} é uma API recente que serve para ler um ficheiro como um array buffer, usando Promises.

+
+ +

Sintaxe

+ +
instanceOfFileReader.readAsArrayBuffer(blob);
+ +

Parâmetros

+ +
+
blob
+
O {{domxref("Blob")}} ou {{domxref("File")}} a partir do qual ler.
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName("File API", "#readAsArrayBuffer", "FileReader.readAsArrayBuffer")}}{{Spec2("File API")}}Definição inicial
+ +

Compatibilidade

+ + + +

{{Compat("api.FileReader.readAsArrayBuffer")}}

+ +

Ver também

+ + diff --git a/files/pt-pt/web/api/filereader/readasbinarystring/index.html b/files/pt-pt/web/api/filereader/readasbinarystring/index.html new file mode 100644 index 0000000000..44911105e6 --- /dev/null +++ b/files/pt-pt/web/api/filereader/readasbinarystring/index.html @@ -0,0 +1,85 @@ +--- +title: FileReader.readAsBinaryString() +slug: Web/API/FileReader/readAsBinaryString +tags: + - API + - Ficheiros + - File API + - Referencia + - metodo +translation_of: Web/API/FileReader/readAsBinaryString +--- +

{{APIRef("File API")}}

+ +

O método readAsBinaryString é usado para iniciar a leitura dos conteúdos do {{domxref("Blob")}} ou {{domxref("File")}} indicado. Quando a operação da leitura é terminada, o {{domxref("FileReader.readyState","readyState")}} retorna DONE, e o {{event("loadend")}} é acionado. A propriedade {{domxref("FileReader.result","result")}} depois contem o binário bruto do ficheiro.

+ +

Note que este método foi removido do File API, mas foi reintroduzido por motivos de compatibilidade com versões antigas.
+ É recomendado usar {{domxref("FileReader.readAsArrayBuffer()")}}.

+ +

Sintaxe

+ +
instanceOfFileReader.readAsBinaryString(blob);
+ +

Parâmetros

+ +
+
blob
+
O {{domxref("Blob")}} ou {{domxref("File")}} a ser lido.
+
+ +

Exemplo

+ +
var canvas = document.createElement('canvas');
+var height = 200;
+var width  = 200;
+
+canvas.width  = width;
+canvas.height = height;
+
+var ctx = canvas.getContext('2d');
+
+ctx.strokeStyle = '#090';
+ctx.beginPath();
+ctx.arc(width/2, height/2, width/2 - width/10, 0, Math.PI*2);
+ctx.stroke();
+
+canvas.toBlob(function (blob) {
+  var reader = new FileReader();
+
+  reader.onloadend = function () {
+    console.log(reader.result);
+  }
+
+  reader.readAsBinaryString(blob);
+});
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentários
{{SpecName('File API','#readAsBinaryString','readAsBinaryString')}}{{Spec2('File API')}}
+ +

Compatibilidade

+ + + +

{{Compat("api.FileReader.readAsBinaryString")}}

+ +

Ver também

+ + diff --git a/files/pt-pt/web/api/filereader/readasdataurl/index.html b/files/pt-pt/web/api/filereader/readasdataurl/index.html new file mode 100644 index 0000000000..321d50d3ce --- /dev/null +++ b/files/pt-pt/web/api/filereader/readasdataurl/index.html @@ -0,0 +1,133 @@ +--- +title: FileReader.readAsDataURL() +slug: Web/API/FileReader/readAsDataURL +tags: + - API + - Base 64 + - Ficheiros + - File API + - FileReader + - Referencia + - metodo +translation_of: Web/API/FileReader/readAsDataURL +--- +

O método readAsDataURL é utilizado para ler os conteúdos dum {{domxref("Blob")}} ou {{domxref("File")}} especificado. Quando a operação de leitura é terminada, a propriedade {{domxref("FileReader.readyState","readyState")}} é atualizada para DONE, e o evento {{event("loadend")}} é lançado. Nessa altura, o atributo {{domxref("FileReader.result","result")}} contem os dados na forma data: URL que representa os dados do ficheiro em base 64 numa string.

+ +
+

Nota: O{{domxref("FileReader.result","result")}} da Blob não pode ser diretamente descodificado como Base64 sem remover a declaração Data-URL que precede os dados em Base64. Para ter só a string em Base64, primeiro tem de remover o data:*/*;base64, do resultado.

+
+ +

Sintaxe

+ +
instanceOfFileReader.readAsDataURL(blob);
+ +

Parametros

+ +
+
blob
+
O {{domxref("Blob")}} ou {{domxref("File")}} para ler.
+
+ +

Exemplo

+ +

HTML

+ +
<input type="file" onchange="previewFile()"><br>
+<img src="" height="200" alt="Image preview...">
+ +

JavaScript

+ +
function previewFile() {
+  const preview = document.querySelector('img');
+  const file = document.querySelector('input[type=file]').files[0];
+  const reader = new FileReader();
+
+  reader.addEventListener("load", function () {
+    // converter o file de imagem oara uma string de base 64
+    preview.src = reader.result;
+  }, false);
+
+  if (file) {
+    reader.readAsDataURL(file);
+  }
+}
+ +

Resultado

+ +

{{EmbedLiveSample("Exemplo", "100%", 240)}}

+ +

Exemplo de vários files

+ +

HTML

+ +
<input id="browse" type="file" onchange="previewFiles()" multiple>
+<div id="preview"></div>
+ +

JavaScript

+ +
function previewFiles() {
+
+  var preview = document.querySelector('#preview');
+  var files   = document.querySelector('input[type=file]').files;
+
+  function readAndPreview(file) {
+
+    // Make sure `file.name` matches our extensions criteria
+    if ( /\.(jpe?g|png|gif)$/i.test(file.name) ) {
+      var reader = new FileReader();
+
+      reader.addEventListener("load", function () {
+        var image = new Image();
+        image.height = 100;
+        image.title = file.name;
+        image.src = this.result;
+        preview.appendChild( image );
+      }, false);
+
+      reader.readAsDataURL(file);
+    }
+
+  }
+
+  if (files) {
+    [].forEach.call(files, readAndPreview);
+  }
+
+}
+
+ +
Nota: O construtor FileReader() não é apoiado pela Internet Explorer anterior à versão 10. Para obter código totalmente compatível veja a nossa solução crossbrowser para pré-visualizar imagens. Veja também este exemplo mais complexo.
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName("File API", "#readAsDataURL", "readAsDataURL()")}}{{Spec2("File API")}}Definição inicial
+ +

Compatibilidade

+ + + +

{{Compat("api.FileReader.readAsDataURL")}}

+ +

Ver também

+ + + +
{{APIRef("File API")}}
diff --git a/files/pt-pt/web/api/filereader/readastext/index.html b/files/pt-pt/web/api/filereader/readastext/index.html new file mode 100644 index 0000000000..d8f821e7ab --- /dev/null +++ b/files/pt-pt/web/api/filereader/readastext/index.html @@ -0,0 +1,63 @@ +--- +title: FileReader.readAsText() +slug: Web/API/FileReader/readAsText +tags: + - API + - Ficheiros + - File API + - Referencia + - metodo +translation_of: Web/API/FileReader/readAsText +--- +
{{APIRef("File API")}}
+ +

O método readAsText() é utilizado para ler os conteúdos do {{domxref("Blob")}} ou {{domxref("File")}} indicado. Quando a operação de leitura é terminada, a propriedade {{domxref("FileReader.readyState","readyState")}} é modificada para DONE, o evento {{event("loadend")}} é lançado, e a propriedade {{domxref("FileReader.result","result")}} fica com os conteúdos do ficheiro em forma de string.

+ +
+

API mais recente disponível
+ {{domxref("Blob.text()")}} é um método mais recente, baseado na API de promessas, para ler um ficheiro como uma string.

+
+ +

Sintaxe

+ +
instanceOfFileReader.readAsText(blob[, encoding]);
+ +

Parâmetros

+ +
+
blob
+
O {{domxref("Blob")}} ou {{domxref("File")}} de qual ler.
+
encoding {{optional_inline}}
+
Uma string a especificar qual codificação usar para os dados devolvidos. A UTF-8 é utilizada se não for definido.
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentários
{{SpecName("File API", "#readAsDataText", "readAsText()")}}{{Spec2("File API")}}Definição inicial
+ +

Compatibilidade

+ + + +

{{Compat("api.FileReader.readAsText")}}

+ +

Ver também

+ + diff --git a/files/pt-pt/web/api/filereader/readystate/index.html b/files/pt-pt/web/api/filereader/readystate/index.html new file mode 100644 index 0000000000..1147e43f29 --- /dev/null +++ b/files/pt-pt/web/api/filereader/readystate/index.html @@ -0,0 +1,96 @@ +--- +title: FileReader.readyState +slug: Web/API/FileReader/readyState +tags: + - API + - Ficheiros + - File API + - Propriedade + - Referencia +translation_of: Web/API/FileReader/readyState +--- +
{{APIRef("File API")}}
+ +

A propriedade readyState de {{domxref("FileReader")}} fornece o estado actual da operação de leitura em que se encontra um FileReader.  Um FileReader existe num dos seguintes estados:

+ + + + + + + + + + + + + + + + + + + + + + + + +
ValorEstadoDescrição
0EMPTYFoi criado um leitor. Nenhum dos métodos de leitura foi ainda chamado.
1LOADINGFoi chamado um método de leitura.
2DONEA operação está concluída.
+ +
+
EMPTY
+
O FileReader foi criado, mas ainda não foi chamado o método readAs.
+
LOADING
+
Foi invocado o método readAs. O {{domxref("File")}} ou {{domxref("Blob")}} está a ser lido, e ainda não ocorreu qualquer erro.
+
DONE
+
A operação lida está concluída. Isto pode significar que: todo o {{domxref("File")}} ou {{domxref("Blob")}} foi lido na memória, ocorreu um erro de leitura de ficheiro, ou {{domxref("FileReader.abort()", "abort()")}} foi chamado e a leitura foi cancelada.
+
+ +

Exemplo

+ +
var reader = new FileReader();
+console.log('EMPTY', reader.readyState); // readyState é 0
+
+reader.readAsText(blob);
+console.log('LOADING', reader.readyState); // readyState é 1
+
+reader.onloadend = function () {
+  console.log('DONE', reader.readyState); // readyState é 2
+};
+
+ +

Valor

+ +

Um número que é uma das três constantes de estado possíveis definidas para o {{domxref("FileReader")}} API.

+ +

Especificação

+ + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentários
{{SpecName("File API", "#dom-filereader-readystate", "readyState")}}{{Spec2("File API")}}Definição inicial
+ +

Compatibilidade

+ + + +

{{Compat("api.FileReader.readyState")}}

+ +

Ver também

+ + diff --git a/files/pt-pt/web/api/filereader/result/index.html b/files/pt-pt/web/api/filereader/result/index.html new file mode 100644 index 0000000000..ea7ddd4bbd --- /dev/null +++ b/files/pt-pt/web/api/filereader/result/index.html @@ -0,0 +1,105 @@ +--- +title: FileReader.result +slug: Web/API/FileReader/result +tags: + - API + - Ficheiros + - File API + - FileReader + - Propriedade + - Referencia + - result +translation_of: Web/API/FileReader/result +--- +
{{APIRef("File API")}}
+ +

A propriedade result de {{domxref("FileReader")}} devolve os conteúdo do ficheiro. Esta propriedade só é válida após a operação de leitura estar concluída, e o formato dos dados depende de qual método foi utilizado para iniciar a operação de leitura.

+ +

Sintaxe

+ +
var file = instanceOfFileReader.result
+
+ +

Valor

+ +

Uma string ou {{jsxref("ArrayBuffer")}} apropriado com base em qual dos métodos de leitura foi utilizado para iniciar a operação de leitura. O valor é null se a leitura ainda não estiver completa ou não foi bem sucedida.

+ +

Os resultados são descritos abaixo.

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
MétodoDescrição
{{domxref("FileReader/readAsArrayBuffer", "readAsArrayBuffer()")}}O result é um {{jsxref("Global_Objects/ArrayBuffer", "ArrayBuffer")}} de JavaScript que contem dados binários.
{{domxref("FileReader/readAsBinaryString", "readAsBinaryString()")}}O result contém os dados binários brutos do ficheiro numa string.
{{domxref("FileReader/readAsDataURL", "readAsDataURL()")}}O result é uma string com uma data: URL que representa os dados do ficheiro.
{{domxref("FileReader/readAsText", "readAsText()")}}O result ié texto numa string.
+ +

Exemplo

+ +

Este exemplo apresenta uma função, read(), que lê um ficheiro a partir de uma entrada de ficheiro. Funciona criando um objecto {{domxref("FileReader")}} e criando um ouvinte para eventos {{domxref("FileReader/load_event", "load")}}, de modo que quando o ficheiro é lido, o result é obtido e passado para a função callback fornecida para read().

+ +

O conteúdo é tratado como dados de texto brutos.

+ +
var fileInput = document.querySelector('input[type="file"]');
+
+function read(callback) {
+  var file = fileInput.files.item(0);
+  var reader = new FileReader();
+
+  reader.onload = function() {
+    callback(reader.result);
+  }
+
+  reader.readAsText(file);
+}
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName("File API", "#dom-filereader-result", "result")}}{{Spec2("File API")}}Definição inicial
+ +

Compatibilidade

+ + + +

{{Compat("api.FileReader.result")}}

+ +

Ver também

+ + diff --git a/files/pt-pt/web/api/geolocation/index.html b/files/pt-pt/web/api/geolocation/index.html new file mode 100644 index 0000000000..39a22949bb --- /dev/null +++ b/files/pt-pt/web/api/geolocation/index.html @@ -0,0 +1,223 @@ +--- +title: Geolocalização +slug: Web/API/Geolocation +tags: + - API + - API de Geolocalização + - Avançada + - Contexto de segurança + - Interface + - Referencia +translation_of: Web/API/Geolocation +--- +
{{securecontext_header}}{{APIRef("Geolocation API")}}
+ +

A interface de Geolocalização representa um objeto capaz de obter programaticamente a posição do dispositivo. Esta dá acesso ao conteúdo da Web para a localização do dispositivo. Isto permite que um site da Web ou aplicação ofereça resultados personalizados com base na localização do utilizador.

+ +

Um objeto com esta interface é obtido utilizando a propriedade {{domxref("navigator.geolocation")}} implementada pelo objeto {{domxref("Navigator")}}.

+ +
+

Nota: por motivos de segurança, quando uma página da Web tenta aceder à informação da localização, o utilizador é notificado e é-lhe solicitado para dar permissão. Tenha em atenção que cada navegador tem as suas próprias políticas e métodos para solicitarem esta permissão.

+
+ +

Propriedades

+ +

A interface de Geolocalização não implementa, nem adquire qualquer propriedade.

+ +

Métodos

+ +

A interface de Geolocalização não adquire qualquer propriedade.

+ +
+
{{domxref("Geolocation.getCurrentPosition()")}} {{securecontext_inline}}
+
Determina a localização do dispositivo e devolve um objeto de {{domxref("Position")}} com os dados.
+
{{domxref("Geolocation.watchPosition()")}} {{securecontext_inline}}
+
Devolve um valor longo representando a nova função estabelecida callback para ser invocada sempre que a localização do dispositivo for alterada.
+
{{domxref("Geolocation.clearWatch()")}} {{securecontext_inline}}
+
Remove o manipulador particular instalado anteriormente, utilizando watchPosition().
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('Geolocation')}}{{Spec2('Geolocation')}}Especificação inicial.
+ +

Compatibilidade de navegador

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico5{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.1")}}910.60
+ Removed in 15.0
+ Reintroduced in 16.0
5
Apenas contexto de segurança47{{CompatUnknown()}}{{CompatGeckoDesktop("55")}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatUnknown()}}{{CompatUnknown()}}{{CompatVersionUnknown}}{{CompatGeckoMobile("4")}}{{CompatUnknown()}}10.60{{CompatUnknown()}}
Apenas contexto de segurança{{CompatNo}}47{{CompatUnknown()}}{{CompatGeckoDesktop("55")}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Consulte 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 new file mode 100644 index 0000000000..40fb7ce571 --- /dev/null +++ b/files/pt-pt/web/api/geolocation/utilizacao_da_geolocalizacao/index.html @@ -0,0 +1,242 @@ +--- +title: API de Geolocalização +slug: Web/API/Geolocation/Utilizacao_da_geolocalizacao +tags: + - API de Geolocalização + - Guía + - Intermediário +translation_of: Web/API/Geolocation_API +--- +

{{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/index.html b/files/pt-pt/web/api/index.html new file mode 100644 index 0000000000..196c30c28f --- /dev/null +++ b/files/pt-pt/web/api/index.html @@ -0,0 +1,14 @@ +--- +title: APIs da Web (Interfaces) +slug: Web/API +tags: + - API + - DOM + - JavaScript + - Referencia + - Web +translation_of: Web/API +--- +

Quando escrever código para a Web com Javascript, estão disponíveis muitas APIs excelentes. Em baixo, tem uma lista de interfaces (ou seja, tipos de objetos) que poderá utilizar durante o desenvolvimento da sua aplicaçao ou site da Web.

+ +

{{APIListAlpha}}

diff --git a/files/pt-pt/web/api/mathmlelement/index.html b/files/pt-pt/web/api/mathmlelement/index.html new file mode 100644 index 0000000000..ee2504017a --- /dev/null +++ b/files/pt-pt/web/api/mathmlelement/index.html @@ -0,0 +1,72 @@ +--- +title: MathMLElement +slug: Web/API/MathMLElement +tags: + - API + - Interface + - MathML + - MathMLElement + - Referencia +translation_of: Web/API/MathMLElement +--- +
{{APIRef("MathML")}}
+ +

A interface MathMLElement representa qualquer elemento MathML.

+ +

Propiedades

+ +

Esta interface não tem propriedades, mas herda propriedades de: {{DOMxRef("DocumentAndElementEventHandlers")}}, {{DOMxRef("Element")}}, {{DOMxRef("ElementCSSInlineStyle")}}, {{DOMxRef("GlobalEventHandlers")}}, {{DOMxRef("HTMLOrForeignElement")}}

+ + + +

Métodos

+ +

Esta interface não tem métodos, mas herda métodos de: {{DOMxRef("DocumentAndElementEventHandlers")}}, {{DOMxRef("Element")}}, {{DOMxRef("ElementCSSInlineStyle")}}, {{DOMxRef("GlobalEventHandlers")}}, {{DOMxRef("HTMLOrForeignElement")}}

+ +

Exemplos

+ +

MathML

+ +
<math xmlns="http://www.w3.org/1998/Math/MathML">
+  <msqrt>
+    <mi>x</mi>
+  </msqrt>
+</math>
+ +

JavaScript

+ +
document.querySelector('msqrt').constructor.name; // MathMLElement
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
MathMLElement interface
+ +

Compatibilidade

+ + + +

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

+ +

Ver também

+ + diff --git a/files/pt-pt/web/api/mediadevices/index.html b/files/pt-pt/web/api/mediadevices/index.html new file mode 100644 index 0000000000..68ea5de783 --- /dev/null +++ b/files/pt-pt/web/api/mediadevices/index.html @@ -0,0 +1,263 @@ +--- +title: MediaDevices +slug: Web/API/MediaDevices +tags: + - API + - Devices + - Interface + - Media + - Media Capture and Streams API + - Media Streams API + - MediaDevices + - NeedsTranslation + - Reference + - TopicStub + - WebRTC +translation_of: Web/API/MediaDevices +--- +
{{APIRef("Media Capture and Streams")}}{{SeeCompatTable}}
+ +

The MediaDevices interface provides access to connected media input devices like cameras and microphones, as well as screen sharing. In essence, it lets you obtain access to any hardware source of media data.

+ +

Properties

+ +

Inherits properties from its parent {{domxref("EventTarget")}}.

+ +

Event handlers

+ +
+
{{ domxref("MediaDevices.ondevicechange") }}
+
The event handler for the {{event("devicechange")}} event. This event is delivered to the MediaDevices object when a media input or output device is attached to or removed from the user's computer.
+
+ +

Methods

+ +

Inherits methods from its parent {{domxref("EventTarget")}}.

+ +
+
{{ domxref("EventTarget.addEventListener()") }}
+
Registers an event handler to a specific event type.
+
{{ domxref("MediaDevices.enumerateDevices()") }}
+
Obtains an array of information about the media input and output devices available on the system.
+
{{domxref("MediaDevices.getSupportedConstraints()")}}
+
Returns an object conforming to {{domxref("MediaTrackSupportedConstraints")}} indicating which constrainable properties are supported on the {{domxref("MediaStreamTrack")}} interface. See {{SectionOnPage("/en-US/docs/Web/API/Media_Streams_API", "Capabilities and constraints")}} to learn more about constraints and how to use them.
+
{{ domxref("MediaDevices.getUserMedia()") }}
+
With the user's permission through a prompt, turns on a camera or screensharing and/or a microphone on the system and provides a {{domxref("MediaStream")}} containing a video track and/or an audio track with the input.
+
{{ domxref("EventTarget.removeEventListener()") }}
+
Removes an event listener.
+
+ +

Example

+ +
'use strict';
+
+// Put variables in global scope to make them available to the browser console.
+var video = document.querySelector('video');
+var constraints = window.constraints = {
+  audio: false,
+  video: true
+};
+var errorElement = document.querySelector('#errorMsg');
+
+navigator.mediaDevices.getUserMedia(constraints)
+.then(function(stream) {
+  var videoTracks = stream.getVideoTracks();
+  console.log('Got stream with constraints:', constraints);
+  console.log('Using video device: ' + videoTracks[0].label);
+  stream.onremovetrack = function() {
+    console.log('Stream ended');
+  };
+  window.stream = stream; // make variable available to browser console
+  video.srcObject = stream;
+})
+.catch(function(error) {
+  if (error.name === 'ConstraintNotSatisfiedError') {
+    errorMsg('The resolution ' + constraints.video.width.exact + 'x' +
+        constraints.video.width.exact + ' px is not supported by your device.');
+  } else if (error.name === 'PermissionDeniedError') {
+    errorMsg('Permissions have not been granted to use your camera and ' +
+      'microphone, you need to allow the page access to your devices in ' +
+      'order for the demo to work.');
+  }
+  errorMsg('getUserMedia error: ' + error.name, error);
+});
+
+function errorMsg(msg, error) {
+  errorElement.innerHTML += '<p>' + msg + '</p>';
+  if (typeof error !== 'undefined') {
+    console.error(error);
+  }
+}
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Media Capture', '#mediadevices', 'MediaDevices')}}{{Spec2('Media Capture')}}Initial definition
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(47)}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("36.0")}}{{CompatNo}}{{CompatOpera(30)}}{{CompatNo}}
enumerateDevices(){{CompatChrome(51)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatNo}}{{CompatOpera(38)}}{{CompatNo}}
getSupportedConstraints(){{CompatChrome(53)}}{{CompatUnknown}}{{CompatGeckoDesktop(44)}}{{CompatNo}}{{CompatOpera(40)}}{{CompatNo}}
ondevicechange and devicechange events{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop(51)}}[1]{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}
Stereo audio capture{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop(55)}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidEdgeFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatChrome(47)}}{{CompatChrome(47)}}{{CompatVersionUnknown}}{{CompatGeckoMobile("36.0")}}2.2{{CompatNo}}{{CompatOperaMobile(30)}}{{CompatNo}}{{CompatNo}}
enumerateDevices(){{CompatChrome(51)}}{{CompatChrome(51)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatNo}}{{CompatOperaMobile(38)}}{{CompatNo}}{{CompatNo}}
getSupportedConstraints(){{CompatChrome(53)}}{{CompatChrome(52)}}{{CompatUnknown}}{{CompatGeckoMobile(50)}}{{CompatUnknown}}{{CompatNo}}{{CompatOperaMobile(40)}}{{CompatNo}}{{CompatNo}}
ondevicechange and devicechange events{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(51)}}[1]{{CompatUnknown}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}
Stereo audio capture{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatNo}}
+ +

[1] Support for the devicechange event and for {{domxref("MediaDevices.ondevicechange")}} landed in Firefox 51, but only for Mac, and disabled by default. It can be enabled by setting the preference media.ondevicechange.enabled to true. Support for this event was added for Linux and Windows—and it was enabled by default—starting in Firefox 52.

+
+ +

See also

+ + diff --git a/files/pt-pt/web/api/messageevent/index.html b/files/pt-pt/web/api/messageevent/index.html new file mode 100644 index 0000000000..f69342523b --- /dev/null +++ b/files/pt-pt/web/api/messageevent/index.html @@ -0,0 +1,139 @@ +--- +title: MessageEvent +slug: Web/API/MessageEvent +tags: + - API + - Canais + - Interface + - Mensagens + - Referencia + - WebSockets + - Window + - Workers +translation_of: Web/API/MessageEvent +--- +
{{APIRef("HTML DOM")}}
+ +

A interface MessageEvent representa a mensagem recebida pelo objeto alvo.

+ +

É usado para representar mensagens em:

+ + + +

A ação acionada por este evento é definida na função escolhida para ser o event handler do evento {{event("message")}} relevante (e.x. usar um handler onmessage como é menciondo antriormente).

+ +

{{AvailableInWorkers}}
+ {{InheritanceDiagram(600, 80)}}

+ +

Construtor

+ +
+
{{domxref("MessageEvent.MessageEvent", "MessageEvent()")}}
+
Cria um MessageEvent.
+
+ +

Propriedades

+ +

Esta interface também herda propriedades da interface {{domxref("Event")}}, de qual se deriva.

+ +
+
{{domxref("MessageEvent.data")}} {{readonlyInline}}
+
Os dados enviados pelo emissor da mensagem.
+
{{domxref("MessageEvent.origin")}} {{readonlyInline}}
+
Uma {{domxref("USVString")}} que representa a origem do emissor da mensagem.
+
{{domxref("MessageEvent.lastEventId")}} {{readonlyInline}}
+
Uma {{domxref("DOMString")}} que representa um ID único para o evento.
+
{{domxref("MessageEvent.source")}} {{readonlyInline}}
+
Uma MessageEventSource (que pode ser um objeto {{domxref("WindowProxy")}}, {{domxref("MessagePort")}}, ou {{domxref("ServiceWorker")}}) que representa o emissor da mensagem.
+
{{domxref("MessageEvent.ports")}} {{readonlyInline}}
+
Uma matriz de objetos {{domxref("MessagePort")}} que representam as portas ao canal por qual as mensagens são enviadas (onde for apropriado, por exemplo em mensagens via canais ou ao enviar uma mensagem a um worker partilhado).
+
+ +

Métodos

+ +

Esta interface também herda métodos de {{domxref("Event")}}, de qual se deriva.

+ +
+
{{domxref("MessageEvent.initMessageEvent","initMessageEvent()")}} {{deprecated_inline}}
+
Inicializa um evento de mensagem. Não useuse antes o construtor {{domxref("MessageEvent.MessageEvent", "MessageEvent()")}}.
+
+ +

Exemplos

+ +

No nossoexemplo básico dum worker partilhado, temos duas páginas de HTML, cada qual usa JavaScript para fazer um simples cálculo. Os scripts diferentes estão a utilizar o mesmo ficheiro de worker para fazer os cálculos — ambos podem-no aceder, mesmo se as páginas estiverem a correr em janelas diferentes.

+ +

O seguinte snippet de código demonstra a criação dum objeto {{domxref("SharedWorker")}} usando o construtor {{domxref("SharedWorker.SharedWorker", "SharedWorker()")}}. Ambas scripts contêm isto:

+ +
var myWorker = new SharedWorker('worker.js');
+
+ +

Ambas scripts acedem ao worker através dum objeto {{domxref("MessagePort")}} criado usando a propriedade {{domxref("SharedWorker.port")}}. Se o evento onmessage foi adicionado usando addEventListener, a porta é manualmente criada usando o seu método start():

+ +
myWorker.port.start();
+ +

Quando a porta é iniciada, ambos scripts enviam mensagens ao worker e processão mensagens vindas do worker usando port.postMessage() e port.onmessage, respetivamente:

+ +
first.onchange = function() {
+  myWorker.port.postMessage([first.value,second.value]);
+  console.log('Mensagem enviada ao worker');
+}
+
+second.onchange = function() {
+  myWorker.port.postMessage([first.value,second.value]);
+  console.log('Mensagem enviada ao worker');
+}
+
+myWorker.port.onmessage = function(e) {
+  result1.textContent = e.data;
+  console.log('Mensagem recebida do worker');
+}
+ +

Dentro do worker usamos o handler {{domxref("SharedWorkerGlobalScope.onconnect")}} para nos ligarmos à mesma porta a que referimos antes. As portas associadas a esse worker são acessíveis através da propriedade ports do evento {{event("connect")}} — nós depois usamos o método start() de {{domxref("MessagePort")}} para iniciar a porta, e o handler onmessage para lidar com as mensagens enviadas dos threads principais.

+ +
onconnect = function(e) {
+  var port = e.ports[0];
+
+  port.addEventListener('message', function(e) {
+    var workerResult = 'Result: ' + (e.data[0] * e.data[1]);
+    port.postMessage(workerResult);
+  });
+
+  port.start(); // Necessário quando se usa addEventListener. Senão é chamado implicitamente pelo setter onmessage.
+}
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('HTML WHATWG', "#messageevent", "MessageEvent")}}{{Spec2('HTML WHATWG')}}
+ +

Compatibilidade

+ + + +

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

+ +

Ver também

+ + diff --git a/files/pt-pt/web/api/metadados/index.html b/files/pt-pt/web/api/metadados/index.html new file mode 100644 index 0000000000..dd1c16c91d --- /dev/null +++ b/files/pt-pt/web/api/metadados/index.html @@ -0,0 +1,116 @@ +--- +title: Metadados +slug: Web/API/Metadados +tags: + - API + - API Entradas de Diretoria e Ficheiro + - API do Sistema de Ficheiros + - Ficheiros + - Interface + - Não Padrão + - Pff-line + - Referencia + - metadados +translation_of: Web/API/Metadata +--- +

{{ 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 new file mode 100644 index 0000000000..43aed9ed94 --- /dev/null +++ b/files/pt-pt/web/api/navigatoronline/eventos_online_e_offline/index.html @@ -0,0 +1,97 @@ +--- +title: Eventos online e offline +slug: Web/API/NavigatorOnLine/Eventos_online_e_offline +tags: + - AJAX + - DOM + - Desenvolvimento_Web + - Todas_as_Categorias +translation_of: Web/API/NavigatorOnLine/Online_and_offline_events +--- +

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/index.html b/files/pt-pt/web/api/navigatoronline/index.html new file mode 100644 index 0000000000..91197b69ef --- /dev/null +++ b/files/pt-pt/web/api/navigatoronline/index.html @@ -0,0 +1,134 @@ +--- +title: NavigatorOnLine +slug: Web/API/NavigatorOnLine +tags: + - API + - HTML-DOM + - NeedsTranslation + - TopicStub +translation_of: Web/API/NavigatorOnLine +--- +

{{APIRef("HTML DOM")}}

+ +

The NavigatorOnLine interface contains methods and properties related to the connectivity status of the browser.

+ +

There is no object of type NavigatorOnLine, but other interfaces, like {{domxref("Navigator")}} or {{domxref("WorkerNavigator")}}, implement it.

+ +

Properties

+ +

The NavigatorOnLine interface doesn't inherit any property.

+ +
+
{{domxref("NavigatorOnLine.onLine")}} {{readonlyInline}}
+
Returns a {{domxref("Boolean")}} indicating whether the browser is working online.
+
+ +

Methods

+ +

The NavigatorOnLine interface neither implements, nor inherit any method.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#navigatoronline', 'NavigatorOnLine')}}{{Spec2('HTML WHATWG')}}No change from the latest snapshot, {{SpecName('HTML5 W3C')}}
{{SpecName('HTML5 W3C', '#navigatoronline', 'NavigatorOnLine')}}{{Spec2('HTML5 W3C')}}Snapshot of {{SpecName('HTML WHATWG')}} with its initial specification.
+ +

Browser compatibility

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
on {{domxref("WorkerNavigator")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop(29)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
on {{domxref("WorkerNavigator")}}{{CompatUnknown}}{{CompatGeckoMobile(29)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

See also

+ + diff --git a/files/pt-pt/web/api/node/index.html b/files/pt-pt/web/api/node/index.html new file mode 100644 index 0000000000..d1ea8d3557 --- /dev/null +++ b/files/pt-pt/web/api/node/index.html @@ -0,0 +1,407 @@ +--- +title: Node +slug: Web/API/Node +tags: + - API + - DOM + - Element + - Interface + - Node + - WebAPI +translation_of: Web/API/Node +--- +
+ {{Apiref}}
+

Node é uma interface da qual uma varidade de tipos do DOM herdam e permite que estes vários tipos seja tratados (ou testados) de forma similar.

+

As seguintes interfaces todas herdam de Node os seus métodos e propriedades:{{domxref("Document")}}, {{domxref("Element")}}, {{domxref("CharacterData")}} (que {{domxref("Text")}}, {{domxref("Comment")}}, e {{domxref("CDATASection")}} herdam), {{domxref("ProcessingInstruction")}}, {{domxref("DocumentFragment")}}, {{domxref("DocumentType")}}, {{domxref("Notation")}}, {{domxref("Entity")}}, {{domxref("EntityReference")}}

+

Estas interfaces podem retornar null em casos particulares, em que estes métodos e propriedades não são relevantes. Podem lançar uma excepção - por exempo, ao adicionar nós-filho a um tipo de nó para o qual não está prevista a existência de nós descendentes.

+

 

+

Propriedades

+

Herda propriedades do seu pai {{domxref("EventTarget")}}.[1]

+
+
+ {{domxref("Node.attributes")}} {{deprecated_inline}}
+
+ ...
+
+ {{domxref("Node.baseURI")}} {{readonlyInline}}
+
+ Retorna uma {{domxref("DOMString")}} que represente o URL base. O conceito de URL base varia de língua para língua; em HTML corresponde: ao protocolo, nome do domínio e estrutura de directórios, ou seja, tudo até à última '/'.
+
+ {{domxref("Node.baseURIObject")}} {{Non-standard_inline()}} {{ Fx_minversion_inline("3") }}
+
+ (Não disponível para conteúdo Web). O objecto {{ Interface("nsIURI") }} apenas de leitura representa o URI base para o elemento.
+
+ {{domxref("Node.childNodes")}} {{readonlyInline}}
+
+ Retorna uma {{domxref("NodeList")}} activa quem contém todos os descendentes desse nó. Sendo {{domxref("NodeList")}} uma lista activa, significa que os descendentes do Node mudam, o objecto {{domxref("NodeList")}} é automaticamente actualizado.
+
+ {{domxref("Node.firstChild")}} {{readonlyInline}}
+
+ Retorna um {{domxref("Node")}} que representa o primeiro descendente directo do nó ou null se o nó não tiver descendentes.
+
+ {{domxref("Node.lastChild")}} {{readonlyInline}}
+
+ Retorna um {{domxref("Node")}} que representa o último descendente directo do Node, ou null caso o node não tenha descendentes.
+
+ {{domxref("Node.localName")}} {{readonlyInline}}{{obsolete_inline}}
+
+ Retorna uma {{domxref("DOMString")}} que representa a parte local do nome qualificado do elemento. No Firefox 3.5 e anteriores, a propriedade exibe o nome local do elemento HTML em maiúsculas (mas não o faz para elementos XHTML). Em versões posteriores, isto não se verifica, portanto a propriedade é exibida em letras minúsculas para ambos HTML e XHTML. {{ gecko_minversion_inline("1.9.2") }}. Apesar da especificação requerer que localName seja definido no interface {{domxref("Node")}}, browsers Gecko-based implementam-no no interface {{domxref("Element")}}.
+
+ {{domxref("Node.namespaceURI")}} {{readonlyInline}}{{obsolete_inline}}
+
+ O URI do namspace do node em causa, ou null, se não possuir namespace. No Firefox 3.5 e anteriores, elementos HTML não se encontravam em qualquer namespace. Em versões posteriores, elementos HTML estão no namespace http://www.w3.org/1999/xhtml quer na tree de HTML, quer na de XHTML {{ gecko_minversion_inline("1.9.2") }}
+
+ Apesar da especificação requerer namespaceURI definido no interface {{domxref("Node")}}, browsers Gecko-based implementam-no no interface {{domxref("Element")}}.
+
+ {{domxref("Node.nextSibling")}} {{readonlyInline}}
+
+ Retorna um {{domxref("Node")}} que representa o próximo node na tree, ou null caso esse node não exista.
+
+ {{domxref("Node.nodeName")}} {{readonlyInline}}
+
+ Retorna uma {{domxref("DOMString")}} que contém o nome do Node. A estrutura do nome difere do tipo do nome. Exemplo: um {{domxref("HTMLElement")}} irá conter o nome da tag correspondente, como 'audio' para um {{domxref("HTMLAudioElement")}}, um {{domxref("Text")}} node irá ter a string '#text', ou então um {{domxref("Document")}} node irá ter uma string '#document'.
+
+ {{domxref("Node.nodePrincipal")}} {{Non-standard_inline()}}{{ Fx_minversion_inline("3") }}
+
+ Um {{ Interface("nsIPrincipal") }} representa um node principal.
+
+ {{domxref("Node.nodeType")}}{{readonlyInline}}
+
+ Retorna um unsigned short que representa o tipo de node. Os valores possíveis são:
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NomeValor
ELEMENT_NODE1
ATTRIBUTE_NODE {{deprecated_inline()}}2
TEXT_NODE3
CDATA_SECTION_NODE {{deprecated_inline()}}4
ENTITY_REFERENCE_NODE {{deprecated_inline()}}5
ENTITY_NODE {{deprecated_inline()}}6
PROCESSING_INSTRUCTION_NODE7
COMMENT_NODE8
DOCUMENT_NODE9
DOCUMENT_TYPE_NODE10
DOCUMENT_FRAGMENT_NODE11
NOTATION_NODE {{deprecated_inline()}}12
+
+
+ {{domxref("Node.nodeValue")}}
+
+ É a {{domxref("DOMString")}} que representa o valor de um objecto. Para a maioria dos tipos de Node, isto retorna null e qualquer operação é ignorada. Para nodes do tipo TEXT_NODE (objectos {{domxref("Text")}}), COMMENT_NODE ({{domxref("Comment")}} objects), e PROCESSING_INSTRUCTION_NODE ({{domxref("ProcessingInstruction")}} objects), o valor corresponde ao valor textual contido no objecto.
+
+ {{domxref("Node.ownerDocument")}} {{readonlyInline}}
+
+ Retorna o {{domxref("Document")}} a que este node pertence. Se nenhum documento está associado com este, retorna null.
+
+ {{domxref("Node.parentNode")}} {{readonlyInline}}
+
+ Retorna um {{domxref("Node")}} que é o ascendente deste node. Se não existir tal node, como por exemplo se este node se encontra no nível raiz da tree ou se não consta nesta, esta propriedade retorna null.
+
+ {{domxref("Node.parentElement")}} {{readonlyInline}}
+
+ Retorna um {{domxref("Element")}} que é o ascendente deste node. Caso este node não tenha ascendente ou se o seu ascendente não é um {{domxref("Element")}}, esta propriedade retorna null.
+
+ {{domxref("Node.prefix")}} {{obsolete_inline}}
+
+ É uma {{domxref("DOMString")}} que representa o prefixo do namespace do node, ou null caso nenhum prefixo seja especificado.
+
+ Apesar da especificação requerer localName para ser definida no interface {{domxref("Node")}}, browsers Gecko-based implementam-no no interface {{domxref("Element")}}.
+
+ {{domxref("Node.previousSibling")}} {{readonlyInline}}
+
+ Retorna um {{domxref("Node")}} que representa o node anterior na tree ou null caso o node não exista.
+
+ {{domxref("Node.textContent")}}
+
+ É uma {{domxref("DOMString")}} que representa o valor textual de um elemento e todos os seus descendentes.
+
+

Métodos

+

Herda métodos dos seus pais {{domxref("EventTarget")}}.[1]

+
+
+ {{domxref("Node.appendChild()")}}
+
+ Insere um {{domxref("Node")}} como último descendente do elemento em causa.
+
+ {{domxref("Node.cloneNode()")}}
+
+ Clona um {{domxref("Node")}} e, opcionalmente, todo o seu conteúdo. Por omissão, clona o conteúdo do node.
+
+ {{domxref("Node.compareDocumentPosition()")}}
+
+  
+
+ {{domxref("Node.contains()")}}
+
+  
+
+ {{domxref("Node.getFeature()")}} {{obsolete_inline}}
+
+ ...
+
+ {{domxref("Node.getUserData()")}} {{deprecated_inline}}
+
+ Permite ao utilizador extrair alguma {{domxref("DOMUserData")}} do node.
+
+ {{domxref("Node.hasAttributes()")}} {{obsolete_inline}}
+
+ Retorna um {{domxref("Boolean")}} que indica se o elemento tem atributos ou não.
+
+ {{domxref("Node.hasChildNodes()")}}
+
+ Retorna um {{domxref("Boolean")}} que indica se o elemento tem descendentes ou não.
+
+ {{domxref("Node.insertBefore")}}
+
+ Insere o primeiro {{domxref("Node")}} dado num parâmetro imediatamente antes do segundo descendente deste {{domxref("Node")}}.
+
+ {{domxref("Node.isDefaultNamespace")}}
+
+  
+
+ {{domxref("Node.isEqualNode")}}
+
+  
+
+ {{domxref("Node.isSameNode")}} {{obsolete_inline}}
+
+  
+
+ {{domxref("Node.isSupported")}} {{deprecated_inline}}
+
+ Retorna uma flag Boolean que contém o resultado de um teste à implementação do DOM para aferir o suporte deste ou do node a uma determinada propriedade.
+
+ {{domxref("Node.lookupPrefix")}}
+
+  
+
+ {{domxref("Node.lookupNamespaceURI")}}
+
+  
+
+ {{domxref("Node.normalize")}}
+
+ Limpa todos os nodes textuais abaixo deste (converge os adjacentes e remove os vazios)
+
+ {{domxref("Node.removeChild")}}
+
+ Remove um node descendenter do elemento actual. Este deve ser um descendente do node actual.
+
+ {{domxref("Node.replaceChild")}}
+
+ Substitui um {{domxref("Node")}} descendente do actual com o fornecido no segundo parâmetro.
+
+ {{domxref("Node.setUserData")}} {{deprecated_inline}}
+
+ Permite a um utilizador anexar, ou remover {{domxref("DOMUserData")}} do node.
+
+  
+
+

Exemplos

+

Percorrer todos os nodes descendentes

+

A seguinte função itera sobre os nodes descendentes de um node recursivamente e executa uma função de callback sobre os mesmos (e sobre o próprio node-pai).

+
function DOMComb (oParent, oCallback) {
+  if (oParent.hasChildNodes()) {
+    for (var oNode = oParent.firstChild; oNode; oNode = oNode.nextSibling) {
+      DOMComb(oNode, oCallback);
+    }
+  }
+  oCallback.call(oParent);
+}
+

Síntaxe

+
DOMComb(parentNode, callbackFunction);
+

Descrição

+

Recursivamente iterar sobre os nodes descendentes de um parentNode e o próprio parentNode, executando uma callbackFunction sobre estes como objectos this.

+

Parâmetros

+
+
+ parentNode
+
+ O node ascendente (Node Object).
+
+ callbackFunction
+
+ A função de callback (Function).
+
+

Exemplo de utilização

+

O exemplo seguinte envia para a console.log o conteúdo textual do body:

+
function printContent () {
+  if (this.nodeValue) { console.log(this.nodeValue); }
+}
+
+onload = function () {
+  DOMComb(document.body, printContent);
+};
+

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentários
{{SpecName('DOM WHATWG', '#interface-node', 'Node')}}{{Spec2('DOM WHATWG')}}Removidas as seguintes propriedades: attributes, namespaceURI, prefix, e localName.
+ Removidos os seguintes métodos: isSupported(), hasAttributes(), isSameNode(), getFeature(), setUserData(), e getUserData().
{{SpecName('DOM3 Core', 'core.html#ID-1950641247', 'Node')}}{{Spec2('DOM3 Core')}}Os métodos insertBefore(), replaceChild(), removeChild(), e appendChild() retornam mais um tipo de erro  (NOT_SUPPORTED_ERR) caso sejam chamados no {{domxref("Document")}}.
+ O método normalize() foi modificado para que o node {{domxref("Text")}} possa também ser normalizado se a flag correcta de {{domxref("DOMConfiguration")}} estiver definida.
+ Adicionados os seguintes métodos: compareDocumentPosition(), isSameNode(), lookupPrefix(), isDefaultNamespace(), lookupNamespaceURI(), isEqualNode(), getFeature(), setUserData(), e getUserData().
+ Adicionadas as seguintes propriedades: baseURI e textContent.
{{SpecName('DOM2 Core', 'core.html#ID-1950641247', 'Node')}}{{Spec2('DOM2 Core')}}A propriedade ownerDocument foi ligeiramente alterada para que um  {{domxref("DocumentFragment")}} possa também retornar null.
+ Adicionadas as seguintes propriedades: namespaceURI, prefix, e localName.
+ Adicionados os seguintes métodos: normalize(), isSupported() and hasAttributes().
{{SpecName('DOM1', 'level-one-core.html#ID-1950641247', 'Node')}}{{Spec2('DOM1')}}Definição inicial.
+

 

+

Compatibilidade por browser

+

{{CompatibilityTable}}

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
getFeature(){{obsolete_inline}}{{CompatNo}}Suportada desde: {{CompatGeckoDesktop("1.0")}} até {{CompatGeckoDesktop("6.0")}}.
+ Removida em: {{CompatGeckoDesktop("7.0")}}
{{CompatUnknown}}{{CompatNo}}{{CompatNo}}
getUserData(), setUserData() e hasAttributes() {{deprecated_inline}}{{CompatNo}}Suportada desde: {{CompatGeckoDesktop("1.0")}} até {{CompatGeckoDesktop("21.0")}}.
+ Removida em: {{CompatGeckoDesktop("22.0")}}
{{CompatUnknown}}{{CompatNo}}{{CompatNo}}
isSameNode() {{obsolete_inline}}{{CompatNo}}Suportada desde: {{CompatGeckoDesktop("1.0")}} até {{CompatGeckoDesktop("9.0")}}.
+ Removida em: {{CompatGeckoDesktop("10.0")}}
{{CompatUnknown}}{{CompatNo}}{{CompatNo}}
isSupported() {{obsolete_inline}}{{CompatUnknown}}Suportada desde: {{CompatGeckoDesktop("1.0")}} até {{CompatGeckoDesktop("21.0")}}.
+ Removida em: {{CompatGeckoDesktop("22.0")}}
{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
getFeature(){{obsolete_inline}}{{CompatNo}}Suportade desde: {{CompatGeckoDesktop("1.0")}} até {{CompatGeckoDesktop("6.0")}}.
+ Removida em: {{CompatGeckoDesktop("7.0")}}
{{CompatUnknown}}{{CompatNo}}{{CompatNo}}
+
+

[1] Webkit e Blink incorrectamente não fazem com que  Node herde de {{domxref("EventTarget")}}.

diff --git a/files/pt-pt/web/api/notification/index.html b/files/pt-pt/web/api/notification/index.html new file mode 100644 index 0000000000..d584cb349c --- /dev/null +++ b/files/pt-pt/web/api/notification/index.html @@ -0,0 +1,316 @@ +--- +title: Notificação +slug: Web/API/notification +translation_of: Web/API/Notification +--- +

{{APIRef("Web Notifications")}}

+ +

The Notification interface of the {{domxref('Notifications_API','Notifications API')}} is used to configure and display desktop notifications to the user.

+ +

Criador

+ +
+
{{domxref("Notification.Notification()")}}
+
Cria uma nova instância do objeto de {{domxref('Notificação')}}.
+
+ +

Propriedades

+ +

Propriedades estáticas

+ +

These properties are available only on the Notification object itself.

+ +
+
{{domxref("Notification.permission")}} {{readonlyinline}}
+
A string representing the current permission to display notifications. Possible value are: denied (the user refuses to have notifications displayed), granted (the user accepts having notifications displayed), or default (the user choice is unknown and therefore the browser will act as if the value were denied).
+
+ +

Propriedades de instância

+ +

These properties are available only on instances of the Notification object.

+ +
+
{{domxref("Notification.title")}} {{readonlyinline}}
+
The title of the notification as specified in the options parameter of the constructor.
+
{{domxref("Notification.dir")}} {{readonlyinline}}
+
The text direction of the notification as specified in the options parameter of the constructor.
+
{{domxref("Notification.lang")}} {{readonlyinline}}
+
The language code of the notification as specified in the options parameter of the constructor.
+
{{domxref("Notification.body")}} {{readonlyinline}}
+
The body string of the notification as specified in the options parameter of the constructor.
+
{{domxref("Notification.tag")}} {{readonlyinline}}
+
The ID of the notification (if any) as specified in the options parameter of the constructor.
+
{{domxref("Notification.icon")}} {{readonlyinline}}
+
The URL of the image used as an icon of the notification as specified in the options parameter of the constructor.
+
{{domxref("Notification.data")}} {{readonlyinline}}
+
Returns a structured clone of the notification’s data.
+
+ +

Unsupported properties

+ +

The following properties are listed in the most up-to-date spec, but are not supported in any browsers yet. It is advisable to keep checking back regularly to see if the status of these has updated, and let us know if you find any out of date information.

+ +
+
{{domxref("Notification.noscreen")}} {{readonlyinline}}
+
Specifies whether the notification firing should enable the device's screen or not.
+
{{domxref("Notification.renotify")}} {{readonlyinline}}
+
Specifies whether the user should be notified after a new notification replaces an old one.
+
{{domxref("Notification.silent")}} {{readonlyinline}}
+
Specifies whether the notification should be silent, i.e. no sounds or vibrations should be issued, regardless of the device settings.
+
{{domxref("Notification.sound")}} {{readonlyinline}}
+
Specifies a sound resource to play when the notification fires, in place of the default system notification sound.
+
{{domxref("Notification.sticky")}} {{readonlyinline}}
+
Specifies whether the notification should be 'sticky', i.e. not easily clearable by the user.
+
{{domxref("Notification.vibrate")}} {{readonlyinline}}
+
Specifies a vibration pattern for devices with vibration hardware to emit.
+
+ +

Event handlers

+ +
+
{{domxref("Notification.onclick")}}
+
A handler for the {{event("click")}} event. It is triggered each time the user clicks on the notification.
+
{{domxref("Notification.onerror")}}
+
A handler for the {{event("error")}} event. It is triggered each time the notification encounters an error.
+
+ +

Obsolete handlers

+ +

The following event handlers are still supported as listed in the {{anch("browser compatibility")}} section below, but are no longer listed in the current spec. I is safe therefore to assume they are obsolete, and may stop working in future browser versions.

+ +
+
{{domxref("Notification.onclose")}}
+
A handler for the {{event("close")}} event. It is triggered when the user closes the notification.
+
{{domxref("Notification.onshow")}}
+
A handler for the {{event("show")}} event. It is triggered when the notification is displayed.
+
+ +

Métodos

+ +

Métodos estáticos

+ +

These methods are available only on the Notification object itself.

+ +
+
{{domxref("Notification.requestPermission()")}}
+
Requests permission from the user to display notifications.
+
+ +

Métodos de instância

+ +

These properties are available only on an instance of the Notification object or through its prototype. The Notification object also inherits from the {{domxref("EventTarget")}} interface.

+ +
+
{{domxref("Notification.close()")}}
+
Programmatically closes a notification.
+
+ +

Exemplo

+ +

Assume this basic HTML:

+ +
<button onclick="notifyMe()">Notify me!</button>
+ +

It's possible to send a notification as follows — here we present a fairly verbose and complete set of code you could use if you wanted to first check whether notifications are supported, then check if permission has been granted for the current origin to send notifications, then request permission if required, before then sending a notification.

+ +
function notifyMe() {
+  // Let's check if the browser supports notifications
+  if (!("Notification" in window)) {
+    alert("This browser does not support desktop notification");
+  }
+
+  // Let's check whether notification permissions have alredy been granted
+  else if (Notification.permission === "granted") {
+    // If it's okay let's create a notification
+    var notification = new Notification("Hi there!");
+  }
+
+  // Otherwise, we need to ask the user for permission
+  else if (Notification.permission !== 'denied') {
+    Notification.requestPermission(function (permission) {
+      // If the user accepts, let's create a notification
+      if (permission === "granted") {
+        var notification = new Notification("Hi there!");
+      }
+    });
+  }
+
+  // At last, if the user has denied notifications, and you
+  // want to be respectful there is no need to bother them any more.
+}
+ +

{{ EmbedLiveSample('Example', '100%', 30) }}

+ +

In many cases, you don't need to be this verbose. For example, in our Emogotchi demo (see source code), we simply run {{domxref("Notification.requestPermission")}} regardless to make sure we can get permission to send notifications:

+ +
Notification.requestPermission();
+ +

Then we run a simple spawnNotification() function when we want to fire a notification — this is passed arguments to specify the body, icon and title we want, then it creates the necessary options object and fires the notification using the {{domxref("Notification.Notification","Notification()")}} constructor.

+ +
function spawnNotification(theBody,theIcon,theTitle) {
+  var options = {
+      body: theBody,
+      icon: theIcon
+  }
+  var n = new Notification(theTitle,options);
+}
+ +

Especificações

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Notifications')}}{{Spec2('Web Notifications')}}Living standard
+ +

Compatibilidade do navegador

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support5 {{ property_prefix("webkit") }} (see notes)
+ 22
4.0 {{ property_prefix("moz") }} (see notes)
+ 22
{{ CompatNo() }}256 (see notes)
icon5 {{ property_prefix("webkit") }} (see notes)
+ 22
4.0 {{ property_prefix("moz") }} (see notes)
+ 22
{{ CompatNo() }}25{{ CompatNo() }}
silent{{CompatChrome(43.0)}}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
noscreen, renotify, sound, sticky{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{ CompatUnknown() }} +

{{CompatVersionUnknown}}

+
4.0 {{ property_prefix("moz") }} (see notes)
+ 22
1.0.1 {{ property_prefix("moz") }} (see notes)
+ 1.2
{{ CompatNo() }}{{ CompatUnknown() }}{{ CompatNo() }} +

{{CompatVersionUnknown}}

+
icon{{ CompatUnknown() }}{{CompatVersionUnknown}}4.0 {{ property_prefix("moz") }} (see notes)
+ 22
1.0.1 {{ property_prefix("moz") }} (see notes)
+ 1.2
{{ CompatNo() }}{{ CompatUnknown() }}{{ CompatNo() }}{{CompatVersionUnknown}}
silent{{ CompatNo() }}{{CompatChrome(43.0)}}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}{{CompatChrome(43.0)}}
noscreen, renotify, sound, sticky{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +

Notas do Firefox OS

+ +

{{Page("/en-US/docs/Web/API/Notifications_API", "Firefox OS notes")}}

+ +

Notas do Chrome

+ +

{{Page("/en-US/docs/Web/API/Notifications_API", "Chrome notes")}}

+ +

Notas do Safari

+ +

{{Page("/en-US/docs/Web/API/Notifications_API", "Safari notes")}}

+ +

Ver também

+ + diff --git a/files/pt-pt/web/api/notifications_api/index.html b/files/pt-pt/web/api/notifications_api/index.html new file mode 100644 index 0000000000..c41db167ce --- /dev/null +++ b/files/pt-pt/web/api/notifications_api/index.html @@ -0,0 +1,194 @@ +--- +title: Notifications API +slug: Web/API/Notifications_API +tags: + - Landing + - NeedsTranslation + - Notifications + - TopicStub + - permission + - system +translation_of: Web/API/Notifications_API +--- +

{{DefaultAPISidebar("Web Notifications")}}

+ +

The Notifications API allows web pages to control the display of system notifications to the end user — these are outside the top-level browsing context viewport, so therefore can be displayed even the user has switched tabs or moved to a different app. The API is designed to be compatible with existing notification systems across different platforms.

+ +

Concepts and usage

+ +

On supported platforms, showing a system notification generally involves two things. First, the user needs to grant the current origin permission to display system notifications, which is generally done when the app or site initialises, using the {{domxref("Notification.requestPermission()")}} method. This will spawn a request dialog, along the following lines:

+ +

+ +

From here the user can choose to allow notifications from this origin, block notifications from this origin , or to not choose a this point. Once a choice has been made, the setting will generally persist for the current session. 

+ +

Next, a new notification is created using the {{domxref("Notification.Notification","Notification()")}} constructor. This has to be passed a title argument, and can optionally be passed an options object to specify options such as text direction, body text, icon to display, notification sound to play, and more.

+ +

{{AvailableInWorkers}}

+ +

In addition, the Notifications API spec specifies a number of additions to the ServiceWorker API, to allow service workers to fire notifications.

+ +
+

Note: To find out more about using notifications in your own app, read Using the Notifications API.

+
+ +

Notifications interfaces

+ +
+
{{domxref("Notification")}}
+
Defines a notification object.
+
+ +

Service worker additions

+ +
+
{{domxref("ServiceWorkerRegistration")}}
+
Includes the {{domxref("ServiceWorkerRegistration.showNotification()")}} and {{domxref("ServiceWorkerRegistration.getNotifications()")}} method for controlling the display of notifications.
+
{{domxref("ServiceWorkerGlobalScope")}}
+
Includes the {{domxref("ServiceWorkerGlobalScope.onnotificationclick")}} handler for firing custom functions when a notification is clicked.
+
{{domxref("NotificationEvent")}}
+
A specific type of event object, based on {{domxref("ExtendableEvent")}}, which represents a notification that has fired.
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Notifications')}}{{Spec2('Web Notifications')}}Living standard
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support5{{property_prefix("webkit")}}[1]
+ 22
{{CompatGeckoDesktop("2.0")}}{{property_prefix("moz")}}[2]
+ {{CompatGeckoDesktop("22.0")}}
{{CompatNo}}256[3]
Available in workers{{CompatUnknown}}{{CompatGeckoDesktop("41.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Service worker additions +

{{CompatChrome(42.0)}}

+
{{CompatGeckoDesktop("42.0")}}[4]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}} +

{{CompatVersionUnknown}}

+
{{CompatGeckoMobile(2.0)}}{{property_prefix("moz")}}[2]
+ {{CompatGeckoMobile(22.0)}}
1.0.1{{property_prefix("moz")}}[2]
+ 1.2
{{CompatNo}}{{CompatUnknown}}{{CompatNo}} +

{{CompatVersionUnknown}}

+
Available in workers{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(41.0)}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Service worker additions{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile(42.0)}}[4]{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(42.0)}}
+
+ +

[1] Before Chrome 22, the support for notification followed an old prefixed version of the specification and used the {{domxref("window.navigator.webkitNotifications","navigator.webkitNotifications")}} object to instantiate a new notification. Before Chrome 32, {{domxref("Notification.permission")}} was not supported.

+ +

[2] Prior to Firefox 22 (Firefox OS <1.2), the instantiation of a new notification was done with the {{domxref("window.navigator.mozNotification", "navigator.mozNotification")}} object through its createNotification() method. In addition, the Notification was displayed when calling the show() method and supported only the click and close events (Nick Desaulniers wrote a Notification shim to cover both newer and older implementations.)

+ +

[3] Safari started to support notification with Safari 6, but only on Mac OSX 10.8+ (Mountain Lion).

+ +

[4] Firefox 42 has shipped with web notifications from Service Workers disabled.

+ +

Firefox OS permissions

+ +

When using notifications  in a Firefox OS app, be sure to add the desktop-notification permission in your manifest file. Notifications can be used at any permission level, hosted or above:

+ +
"permissions": {
+  "desktop-notification": {}
+}
+ +

See also

+ + 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" new file mode 100644 index 0000000000..ca76a8b6bd --- /dev/null +++ "b/files/pt-pt/web/api/notifications_api/utilizar_api_notifica\303\247\303\265es/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/page_visibility_api/index.html b/files/pt-pt/web/api/page_visibility_api/index.html new file mode 100644 index 0000000000..de3ee0b3ab --- /dev/null +++ b/files/pt-pt/web/api/page_visibility_api/index.html @@ -0,0 +1,271 @@ +--- +title: Page Visibility API +slug: Web/API/Page_Visibility_API +tags: + - API + - DOM + - Intermediário + - Tutoriais +translation_of: Web/API/Page_Visibility_API +--- +
{{DefaultAPISidebar("Page Visibility API")}}
+ +

A Page Visibility API permite-lhe saber quando uma página da Web está visível ou em foco. Com a navegação por separadores, existe uma chance razoável de que qualquer página da Web esteja em segundo plano e, portanto, não seja visível para o utilizador. Quando o utilizador minimiza a página da Web ou move-se para outro separador, a API envia um evento {{event('visibilitychange')}} sobre a visibilidade da página. Pode detetar o evento e executar algumas ações ou comportar-se de forma diferente. Por exemplo, se a sua aplicação da Web estiver a reproduzir um vídeo, esta pausará o momento em que o utilizador olha para outro navegador, e reproduz novamente quando o utilizador volta ao separador. O utilizador não perde o seu lugar no vídeo e pode continuar a assistir.

+ +

Estados de visibilidade de uma {{HTMLElement("iframe")}} são iguais ao documento original. Ocultar a iframe com propriedades CSS não desencadeia eventos de visibilidade nem altera o estado do documento de conteúdo.

+ +

Benefícios

+ +

The API is particularly useful for saving resources by giving developers the opportunity to not perform unnecessary tasks when the webpage is not visible.

+ + + +

Casos de utilização

+ +

Alguns exemplos:

+ + + +

Developers have historically used imperfect proxies to detect this. For example, registering an onblur/onfocus handler on the window helps you know when your page is not the active page, but it does not tell you that your page is hidden to the user. The Page Visibility API addresses this. (When compared with registering onblur/onfocus handlers on the window, a key difference is that a page does not become hidden when another window is made active and the browser window loses focus. A page only becomes hidden when the user switches to a different tab or minimizes the browser window.)

+ +

Políticas em vigor para auxiliar o desempenho da página de fundo

+ +

Along with the Page Visibility API, there are a number of policies in place to mitigate negative performance effects associated with background tabs:

+ + + +

Exemplo

+ +

Ver exemplo live (vídeo com som).

+ +

O exemplo, que pausa o vídeo quando muda para outro separador e reproduz novamente quando volta ao seu separador, foi criado com o seguinte código:

+ +
// Set the name of the hidden property and the change event for visibility
+var hidden, visibilityChange;
+if (typeof document.hidden !== "undefined") { // Opera 12.10 and Firefox 18 and later support
+  hidden = "hidden";
+  visibilityChange = "visibilitychange";
+} else if (typeof document.msHidden !== "undefined") {
+  hidden = "msHidden";
+  visibilityChange = "msvisibilitychange";
+} else if (typeof document.webkitHidden !== "undefined") {
+  hidden = "webkitHidden";
+  visibilityChange = "webkitvisibilitychange";
+}
+
+var videoElement = document.getElementById("videoElement");
+
+// If the page is hidden, pause the video;
+// if the page is shown, play the video
+function handleVisibilityChange() {
+  if (document[hidden]) {
+    videoElement.pause();
+  } else {
+    videoElement.play();
+  }
+}
+
+// Warn if the browser doesn't support addEventListener or the Page Visibility API
+if (typeof document.addEventListener === "undefined" || typeof document.hidden === "undefined") {
+  console.log("This demo requires a browser, such as Google Chrome or Firefox, that supports the Page Visibility API.");
+} else {
+  // Handle page visibility change
+  document.addEventListener(visibilityChange, handleVisibilityChange, false);
+
+  // When the video pauses, set the title.
+  // This shows the paused
+  videoElement.addEventListener("pause", function(){
+    document.title = 'Paused';
+  }, false);
+
+  // When the video plays, set the title.
+  videoElement.addEventListener("play", function(){
+    document.title = 'Playing';
+  }, false);
+
+}
+
+ +

Resumo das propriedades

+ +
+
+

{{domxref("document.hidden")}} Read only

+
+
+

Returns true if the page is in a state considered to be hidden to the user, and false otherwise.

+
+
+

{{domxref("document.visibilityState")}} Read only

+
+
+

Is a string denoting the visibility state of the document. Possible values:

+ +
    +
  • visible : the page content may be at least partially visible. In practice this means that the page is the foreground tab of a non-minimized window.
  • +
  • hidden : the page content is not visible to the user. In practice this means that the document is either a background tab or part of a minimized window, or the OS screen lock is active.
  • +
  • prerender : the page content is being prerendered and is not visible to the user (considered hidden for purposes of document.hidden). The document may start in this state, but will never transition to it from another value. Note: browser support is optional.
  • +
  • unloaded : the page is being unloaded from memory. Note: browser support is optional.
  • +
+ +
//startSimulation and pauseSimulation defined elsewhere
+function handleVisibilityChange() {
+  if (document.hidden) {
+    pauseSimulation();
+  } else  {
+    startSimulation();
+  }
+}
+
+document.addEventListener("visibilitychange", handleVisibilityChange, false);
+
+
+
+

{{domxref("document.onvisibilitychange")}}

+
+
+

Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("visibilitychange")}} event is raised.

+
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('Page Visibility API')}}{{Spec2('Page Visibility API')}}Initial definition.
+ +

Compatibilidade de navegador

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico13 {{property_prefix("webkit")}}
+ 33
{{CompatGeckoDesktop(18)}}[2]1012.10[1]7
onvisibilitychange{{CompatVersionUnknown}}{{CompatGeckoDesktop(56)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Budget-based background timeout throttling57{{CompatGeckoDesktop(58)}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Suporte básico5.0[3]{{CompatGeckoMobile(18)}}[2]1012.10[1]7[4]
onvisibilitychange{{CompatVersionUnknown}}{{CompatGeckoMobile(56)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Budget-based background timeout throttling{{CompatNo}}{{CompatGeckoMobile(58)}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

[1] Doesn't fire the {{event("visibilitychange")}} event when the browser window is minimized, nor set hidden to true.

+ +

[2] From Firefox 10 to Firefox 51 included, this property could be used prefixed with moz.

+ +

[3] Android 4.4 supports this feature if prefixed with webkit.

+ +

[4] From iOS 11.0.2 onwards, the values are not correct in standalone mode (when you press "Add to Homescreen") and when the screen is locked (you pressed the power button). The value for hidden is false and visibilityState is visible.

+ +

Consultar também

+ + diff --git a/files/pt-pt/web/api/push_api/index.html b/files/pt-pt/web/api/push_api/index.html new file mode 100644 index 0000000000..9e94962adc --- /dev/null +++ b/files/pt-pt/web/api/push_api/index.html @@ -0,0 +1,175 @@ +--- +title: Push API +slug: Web/API/Push_API +tags: + - API + - Experimental + - Landing + - Notificações + - Push + - Referencia + - Service Workers +translation_of: Web/API/Push_API +--- +
{{DefaultAPISidebar("Push API")}}{{SeeCompatTable}}
+ +

Push API permite que as aplicações da Web recebam as mensagens submetidas para as mesmas a partir de um servidor, se a aplicação da Web está em primeiro plano, ou mesmo atualmente carregada, num agente de utilizador. Isto permite que os programadores entreguem notificações e atualizações assíncronas aos utilizadores que optem, resultando num melhor compromisso com os novos conteúdos atualizados.

+ +

Conceitos e utilização de Push

+ +

For an app to receive push messages, it has to have an active service worker. When the service worker is active, it can subscribe to push notifications, using {{domxref("PushManager.subscribe()")}}.

+ +

The resulting {{domxref("PushSubscription")}} includes all the information that the application needs to send a push message: an endpoint and the encryption key needed for sending data.

+ +

The service worker will be started as necessary to handle incoming push messages, which are delivered to the {{domxref("ServiceWorkerGlobalScope.onpush")}} event handler. This allows apps to react to push messages being received, for example, by displaying a notification (using {{domxref("ServiceWorkerRegistration.showNotification()")}}.)

+ +

Each subscription is unique to a service worker.  The endpoint for the subscription is a unique capability URL: knowledge of the endpoint is all that is necessary to send a message to your application. The endpoint URL therefore needs to be kept secret, or other applications might be able to send push messages to your application.

+ +

Activating a service worker to deliver a push message can result in increased resource usage, particularly of the battery. Different browsers have different schemes for handling this, there is currently no standard mechanism. Firefox allows a limited number (quota) of push messages to be sent to an application, although Push messages that generate notifications are exempt from this limit. The limit is refreshed each time the site is visited. In comparison, Chrome applies no limit, but requires that every push message causes a notification to be displayed.

+ +
+

Nota: As of Gecko 44, the allowed quota of push messages per application is not incremented when a new notification fires, when another is still visible, for a period of three seconds. This handles cases where a burst of notifications is received, and not all generate a visible notification.

+
+ +
+

Nota: Chrome versions earlier than 52 require you to set up a project on Google Cloud Messaging to send push messages, and use the associated project number and API key when sending push notifications. It also requires an app manifest, with some special parameters to use this service.

+
+ +

Interfaces

+ +
+
{{domxref("PushEvent")}}
+
Represents a push action, sent to the global scope of a {{domxref("ServiceWorker")}}. It contains information sent from an application to a {{domxref("PushSubscription")}}.
+
{{domxref("PushManager")}}
+
Provides a way to receive notifications from third-party servers, as well as request URLs for push notifications. This interface has replaced the functionality offered by the obsolete {{domxref("PushRegistrationManager")}} interface.
+
{{domxref("PushMessageData")}}
+
Provides access to push data sent by a server, and includes methods to manipulate the received data.
+
{{domxref("PushSubscription")}}
+
Provides a subcription's URL endpoint, and allows unsubscription from a push service.
+
+ +

Service worker additions

+ +

The following additions to the Service Worker API have been specified in the Push API spec to provide an entry point for using Push messages. They also monitor and respond to push and subscription change events.

+ +
+
{{domxref("ServiceWorkerRegistration.pushManager")}} {{readonlyinline}}
+
Returns a reference to the {{domxref("PushManager")}} interface for managing push subscriptions including subscribing, getting an active subscription, and accessing push permission status. This is the entry point into using Push messaging.
+
{{domxref("ServiceWorkerGlobalScope.onpush")}}
+
An event handler fired whenever a {{Event("push")}} event occurs; that is, whenever a server push message is received.
+
{{domxref("ServiceWorkerGlobalScope.onpushsubscriptionchange")}}
+
An event handler fired whenever a {{Event("pushsubscriptionchange")}} event occurs; for example, when a push subscription has been invalidated, or is about to be invalidated (e.g. when a push service sets an expiration time.)
+
+ +

Exemplos

+ +

Mozilla's ServiceWorker Cookbook contains many useful Push examples.

+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName("Push API")}}{{Spec2("Push API")}}Definição inicial
+ +

Compatibilidade de navegador

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico{{CompatChrome(42.0)}}{{CompatGeckoDesktop(44.0)}}[1][3]{{CompatNo}}[2]{{CompatUnknown}}{{CompatUnknown}}
{{domxref("PushEvent.data")}},
+ {{domxref("PushMessageData")}}
{{CompatNo}}{{CompatGeckoDesktop(44.0)}}[3]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Suporte básico{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile(48.0)}}[4]{{CompatNo}}{{CompatUnknown}}[2]{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(42.0)}}
{{domxref("PushEvent.data")}},
+ {{domxref("PushMessageData")}}
{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile(48.0)}}[4]{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ + + +

Consulte também

+ + diff --git a/files/pt-pt/web/api/service_worker_api/index.html b/files/pt-pt/web/api/service_worker_api/index.html new file mode 100644 index 0000000000..343635d6c2 --- /dev/null +++ b/files/pt-pt/web/api/service_worker_api/index.html @@ -0,0 +1,335 @@ +--- +title: API de Service Worker +slug: Web/API/Service_Worker_API +tags: + - API + - Landing + - Off-line + - Referencia + - Resumo + - Service Workers + - Sinopse + - Workers +translation_of: Web/API/Service_Worker_API +--- +
+

{{ServiceWorkerSidebar}}

+ +

Os service workers atuam essencialmente como servidores de proxy que ficam entre as aplicações da Web, e o navegador e a rede (quando disponível). Eles são destinados para (entre outras coisas) ativar a criação de experiências efetivas, intercetar pedidos de rede e tomando medidas adequadas com base na disponibilidade da rede e na atualização dos ativos no servidor. Eles também irão permitir o acesso para solicitar notificações e sincronizar as APIs em segundo plano.

+
+ +

Conceitos e utilização do service worker

+ +

A service worker is an event-driven worker registered against an origin and a path. It takes the form of a JavaScript file that can control the web page/site it is associated with, intercepting and modifying navigation and resource requests, and caching resources in a very granular fashion to give you complete control over how your app behaves in certain situations (the most obvious one being when the network is not available.)

+ +

A service worker is run in a worker context: it therefore has no DOM access, and runs on a different thread to the main JavaScript that powers your app, so it is not blocking. It is designed to be fully async; as a consequence, APIs such as synchronous XHR and localStorage can't be used inside a service worker.

+ +

Service workers only run over HTTPS, for security reasons. Having modified network requests wide open to man in the middle attacks would be really bad. In Firefox, Service Worker APIs are also hidden and cannot be used when the user is in private browsing mode.

+ +
+

Nota: Service Workers win over previous attempts in this area such as AppCache because they don't make assumptions about what you are trying to do and then break when those assumptions are not exactly right; you have granular control over everything.

+
+ +
+

Nota: Service workers make heavy use of promises, as generally they will wait for responses to come through, after which they will respond with a success or failure action. The promises architecture is ideal for this.

+
+ +

Registo

+ +

A service worker is first registered using the {{domxref("ServiceWorkerContainer.register()")}} method. If successful, your service worker will be downloaded to the client and attempt installation/activation (see below) for URLs accessed by the user inside the whole origin, or inside a subset specified by you.

+ +

Transferir, instalar e ativar

+ +

Neste ponto, o seu service worker observará o seguinte ciclo vital:

+ +
    +
  1. Transferir
  2. +
  3. Instalar
  4. +
  5. Ativar
  6. +
+ +

The service worker is immediately downloaded when a user first accesses a service worker–controlled site/page.

+ +

After that it is downloaded every 24 hours or so. It may be downloaded more frequently, but it must be downloaded every 24h to prevent bad scripts from being annoying for too long.

+ +

Installation is attempted when the downloaded file is found to be new — either different to an existing service worker (byte-wise compared), or the first service worker encountered for this page/site.

+ +

If this is the first time a service worker has been made available, installation is attempted, then after a successful installation it is activated.

+ +

If there is an existing service worker available, the new version is installed in the background, but not yet activated — at this point it is called the worker in waiting. It is only activated when there are no longer any pages loaded that are still using the old service worker. As soon as there are no more such pages still loaded, the new service worker activates (becoming the active worker).  Activation can happen sooner using {{domxref("ServiceWorkerGlobalScope.skipWaiting()")}} and existing pages can be claimed by the active worker using {{domxref("Clients.claim()")}}.

+ +

You can listen out for the {{domxref("InstallEvent")}}; a standard action is to prepare your service worker for usage when this fires, for example by creating a cache using the built in storage API, and placing assets inside it that you'll want for running your app offline.

+ +

There is also an activate event. The point where this event fires is generally a good time to clean up old caches and other things associated with the previous version of your service worker.

+ +

Your service worker can respond to requests using the {{domxref("FetchEvent")}} event. You can modify the response to these requests in any way you want, using the {{domxref("FetchEvent.respondWith")}} method.

+ +
+

Nota: Because oninstall/onactivate could take a while to complete, the service worker spec provides a waitUntil method that, when called oninstall or onactivate, passes a promise. Functional events are not dispatched to the service worker until the promise successfully resolves.

+
+ +

Para um tutorial completo para mostrars como crair o seu primeiro exemplo básico, leia Utilização de Service Workers.

+ +

Outras ideas de casos de utilização

+ +

Service workers are also intended to be used for such things as:

+ + + +

In the future, service workers will be able to do a number of other useful things for the web platform that will bring it closer towards native app viability. Interestingly, other specifications can and will start to make use of the service worker context, for example:

+ + + +

Interfaces

+ +
+
{{domxref("Cache")}}
+
Represents the storage for {{domxref("Request")}} / {{domxref("Response")}} object pairs that are cached as part of the {{domxref("ServiceWorker")}} life cycle.
+
{{domxref("CacheStorage")}}
+
Represents the storage for {{domxref("Cache")}} objects. It provides a master directory of all the named caches that a {{domxref("ServiceWorker")}} can access and maintains a mapping of string names to corresponding {{domxref("Cache")}} objects.
+
{{domxref("Client")}}
+
Represents the scope of a service worker client. A service worker client is either a document in a browser context or a {{domxref("SharedWorker")}}, which is controlled by an active worker.
+
{{domxref("Clients")}}
+
Represents a container for a list of {{domxref("Client")}} objects; the main way to access the active service worker clients at the current origin.
+
{{domxref("ExtendableEvent")}}
+
Extends the lifetime of the install and activate events dispatched on the {{domxref("ServiceWorkerGlobalScope")}} as part of the service worker lifecycle. This ensures that any functional events (like {{domxref("FetchEvent")}} ) are not dispatched to the {{domxref("ServiceWorker")}} until it upgrades database schemas, deletes outdated cache entries, etc.
+
{{domxref("ExtendableMessageEvent")}}
+
The event object of a {{event("message_(ServiceWorker)","message")}} event fired on a service worker (when a channel message is received on the {{domxref("ServiceWorkerGlobalScope")}} from another context) — extends the lifetime of such events.
+
{{domxref("FetchEvent")}}
+
The parameter passed into the {{domxref("ServiceWorkerGlobalScope.onfetch")}} handler, FetchEvent represents a fetch action that is dispatched on the {{domxref("ServiceWorkerGlobalScope")}} of a {{domxref("ServiceWorker")}}. It contains information about the request and resulting response, and provides the {{domxref("FetchEvent.respondWith", "FetchEvent.respondWith()")}} method, which allows us to provide an arbitrary response back to the controlled page.
+
{{domxref("InstallEvent")}}
+
The parameter passed into the {{domxref("ServiceWorkerGlobalScope.oninstall", "oninstall")}} handler, the InstallEvent interface represents an install action that is dispatched on the {{domxref("ServiceWorkerGlobalScope")}} of a {{domxref("ServiceWorker")}}. As a child of {{domxref("ExtendableEvent")}}, it ensures that functional events such as {{domxref("FetchEvent")}} are not dispatched during installation. 
+
{{domxref("NavigationPreloadManager")}}
+
Provides methods for managing the preloading of resources with a service worker. 
+
{{domxref("Navigator.serviceWorker")}}
+
Returns a {{domxref("ServiceWorkerContainer")}} object, which provides access to registration, removal, upgrade, and communication with the {{domxref("ServiceWorker")}} objects for the associated document.
+
{{domxref("NotificationEvent")}}
+
The parameter passed into the {{domxref("ServiceWorkerGlobalScope.onnotificationclick", "onnotificationclick")}} handler, the NotificationEvent interface represents a notification click event that is dispatched on the {{domxref("ServiceWorkerGlobalScope")}} of a {{domxref("ServiceWorker")}}.
+
{{domxref("ServiceWorker")}}
+
Represents a service worker. Multiple browsing contexts (e.g. pages, workers, etc.) can be associated with the same ServiceWorker object.
+
{{domxref("ServiceWorkerContainer")}}
+
Provides an object representing the service worker as an overall unit in the network ecosystem, including facilities to register, unregister and update service workers, and access the state of service workers and their registrations.
+
{{domxref("ServiceWorkerGlobalScope")}}
+
Represents the global execution context of a service worker.
+
{{domxref("ServiceWorkerMessageEvent")}} {{deprecated_inline}}
+
Represents a message sent to a {{domxref("ServiceWorkerGlobalScope")}}. Note that this interface is deprecated in modern browsers. Service worker messages will now use the {{domxref("MessageEvent")}} interface, for consistency with other web messaging features.
+
{{domxref("ServiceWorkerRegistration")}}
+
Represents a service worker registration.
+
{{domxref("ServiceWorkerState")}} {{experimental_inline}}
+
Associated with its ServiceWorker's state.
+
{{domxref("SyncEvent")}} {{non-standard_inline}}
+
+

The SyncEvent interface represents a sync action that is dispatched on the {{domxref("ServiceWorkerGlobalScope")}} of a ServiceWorker. 

+
+
{{domxref("SyncManager")}} {{non-standard_inline}}
+
Provides an interface for registering and listing sync registrations.
+
{{domxref("WindowClient")}}
+
Represents the scope of a service worker client that is a document in a browser context, controlled by an active worker. This is a special type of {{domxref("Client")}} object, with some additional methods and properties available.
+
+ +

Especificações

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Service Workers')}}{{Spec2('Service Workers')}}Initial definition.
+ +

Compatibilidade de navegador

+ +
{{ CompatibilityTable() }}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(40)}}{{CompatNo}}[1]{{ CompatGeckoDesktop("44.0") }}[2]{{ CompatNo() }}24{{ CompatNo() }}[3]
install/activate events{{ CompatChrome(40) }}{{CompatNo}}[1]{{ CompatGeckoDesktop("44.0") }}[2]{{ CompatNo() }}{{ CompatVersionUnknown() }}{{ CompatNo() }}
fetch event/request/
+ respondWith()
{{CompatChrome(40)}}{{CompatNo}}[1]{{ CompatGeckoDesktop("44.0") }}[2]{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
caches/cache +

{{CompatChrome(42)}}

+
{{CompatNo}}[1]{{ CompatGeckoDesktop("39.0") }}[2]{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
{{domxref("ServiceWorkerMessageEvent")}} deprecated in favour of {{domxref("MessageEvent")}} +

{{CompatChrome(57)}}

+
{{ CompatNo() }}{{ CompatGeckoDesktop("55.0") }}[2]{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
NavigationPreloadManager{{CompatChrome(59)}}{{ CompatNo() }}{{ CompatNo() }}{{CompatOpera(46)}}{{ CompatNo() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeAndroid WebviewChrome for AndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{ CompatNo() }}{{CompatChrome(40)}}{{CompatNo}}[1]{{ CompatGeckoMobile("44.0") }}{{ CompatNo() }}{{ CompatVersionUnknown() }}{{ CompatNo() }}[3]
 install/activate events{{ CompatNo() }}{{CompatChrome(40)}}{{CompatNo}}[1]{{ CompatGeckoMobile("44.0") }}{{ CompatNo() }}{{ CompatVersionUnknown() }}{{ CompatNo() }}
fetch event/request/
+ respondWith()
{{ CompatNo() }}{{CompatChrome(40)}}{{CompatNo}}[1]{{ CompatGeckoMobile("44.0") }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
caches/cache{{ CompatNo() }}{{CompatChrome(40)}}{{CompatNo}}[1]{{ CompatGeckoMobile("39.0") }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
{{domxref("ServiceWorkerMessageEvent")}} deprecated in favour of {{domxref("MessageEvent")}}{{ CompatNo() }} +

{{CompatChrome(57)}}

+
{{ CompatNo() }}{{ CompatGeckoMobile("55.0") }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
NavigationPreloadManager{{ CompatNo() }}{{CompatChrome(59)}}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}{{CompatOperaMobile(46)}}{{ CompatNo() }}
+
+ +

[1] This feature is not supported yet, though it's already in development.

+ +

[2] Service workers (and Push) have been disabled in the Firefox 45 & 52 Extended Support Releases (ESR.)

+ +

[3] This feature is not supported yet, though it's currently in development.

+ +

Consulte também:

+ + diff --git a/files/pt-pt/web/api/service_worker_api/using_service_workers/index.html b/files/pt-pt/web/api/service_worker_api/using_service_workers/index.html new file mode 100644 index 0000000000..bce8c7d4f1 --- /dev/null +++ b/files/pt-pt/web/api/service_worker_api/using_service_workers/index.html @@ -0,0 +1,459 @@ +--- +title: Utilização de "Service Workers" +slug: Web/API/Service_Worker_API/Using_Service_Workers +tags: + - Guía + - ServiceWorker + - Serviço + - Workers + - básicos +translation_of: Web/API/Service_Worker_API/Using_Service_Workers +--- +

{{ServiceWorkerSidebar}}

+ +
+

This article provides information on getting started with service workers, including basic architecture, registering a service worker, the install and activation process for a new service worker, updating your service worker, cache control and custom responses, all in the context of a simple app with offline functionality. 

+
+ +

The premise of service workers

+ +

One overriding problem that web users have suffered with for years is loss of connectivity. The best web app in the world will provide a terrible user experience if you can’t download it. There have been various attempts to create technologies to solve this problem, as our Offline page shows, and some of the issues have been solved. But the overriding problem is that there still isn’t a good overall control mechanism for asset caching and custom network requests.
+
+ The previous attempt — AppCache — seemed to be a good idea because it allowed you to specify assets to cache really easily. However, it made many assumptions about what you were trying to do and then broke horribly when your app didn’t follow those assumptions exactly. Read Jake Archibald's (unfortunately-titled but well-written) Application Cache is a Douchebag for more details.

+ +
+

Nota: As of Firefox 44, when AppCache is used to provide offline support for a page a warning message is now displayed in the console advising developers to use Service workers instead ({{bug("1204581")}}.)

+
+ +

Service workers should finally fix these issues. Service worker syntax is more complex than that of AppCache, but the trade off is that you can use JavaScript to control your AppCache-implied behaviors with a fine degree of granularity, allowing you to handle this problem and many more. Using a Service worker you can easily set an app up to use cached assets first, thus providing a default experience even when offline, before then getting more data from the network (commonly known as Offline First). This is already available with native apps, which is one of the main reasons native apps are often chosen over web apps.

+ +

Setting up to play with service workers

+ +

Many service workers features are now enabled by default in newer versions of supporting browsers. If however you find that demo code is not working in your installed versions, you might need to enable a pref:

+ + + +

You’ll also need to serve your code via HTTPS — Service workers are restricted to running across HTTPS for security reasons. GitHub is therefore a good place to host experiments, as it supports HTTPS. In order to facilitate local development, localhost is considered a secure origin by browsers as well.

+ +

Basic architecture

+ +

With service workers, the following steps are generally observed for basic set up:

+ +
    +
  1. The service worker URL is fetched and registered via {{domxref("serviceWorkerContainer.register()")}}.
  2. +
  3. If successful, the service worker is executed in a {{domxref("ServiceWorkerGlobalScope") }}; this is basically a special kind of worker context, running off the main script execution thread, with no DOM access.
  4. +
  5. The service worker is now ready to process events.
  6. +
  7. Installation of the worker is attempted when service worker-controlled pages are accessed subsequently. An Install event is always the first one sent to a service worker (this can be used to start the process of populating an IndexedDB, and caching site assets). This is really the same kind of procedure as installing a native or Firefox OS app — making everything available for use offline.
  8. +
  9. When the oninstall handler completes, the service worker is considered installed.
  10. +
  11. Next is activation. When the service worker is installed, it then receives an activate event. The primary use of onactivate is for cleanup of resources used in previous versions of a Service worker script.
  12. +
  13. The Service worker will now control pages, but only those opened after the register() is successful. i.e. a document starts life with or without a Service worker and maintains that for its lifetime. So documents will have to be reloaded to actually be controlled.
  14. +
+ +

+ +

The below graphic shows a summary of the available service worker events:

+ +

install, activate, message, fetch, sync, push

+ +

Promises

+ +

Promises are a great mechanism for running async operations, with success dependant on one another. This is central to the way service workers work.
+
+ Promises can do a variety of things, but all you need to know for now is that if something returns a promise, you can attach .then() to the end and include callbacks inside it for success cases, or you can insert .catch() on the end if you want to include a failure callback.

+ +

Let’s compare a traditional synchronous callback structure to its asynchronous promise equivalent.

+ +

sync

+ +
try {
+  const value = myFunction();
+  console.log(value);
+} catch(err) {
+  console.log(err);
+}
+ +

async

+ +
myFunction().then((value) => {
+  console.log(value);
+}).catch((err) => {
+  console.log(err);
+});
+ +

In the first example, we have to wait for myFunction() to run and return value before any more of the code can execute. In the second example, myFunction() returns a promise for value, then the rest of the code can carry on running. When the promise resolves, the code inside then will be run, asynchronously.
+
+ Now for a real example — what if we wanted to load images dynamically, but we wanted to make sure the images were loaded before we tried to display them? This is a standard thing to want to do, but it can be a bit of a pain. We can use .onload to only display the image after it’s loaded, but what about events that start happening before we start listening to them? We could try to work around this using .complete, but it’s still not foolproof, and what about multiple images? And, ummm, it’s still synchronous, so blocks the main thread.
+
+ Instead, we could build our own promise to handle this kind of case. (See our Promises test example for the source code, or look at it running live.)

+ +

{{note("A real service worker implementation would use caching and onfetch rather than the deprecated XMLHttpRequest API. Those features are not used here so that you can focus on understanding Promises.")}}

+ +
const imgLoad = (url) => {
+  return new Promise((resolve, reject) => {
+    var request = new XMLHttpRequest();
+    request.open('GET', url);
+    request.responseType = 'blob';
+
+    request.onload = () => {
+      if (request.status == 200) {
+        resolve(request.response);
+      } else {
+        reject(Error('Image didn\'t load successfully; error code:' + request.statusText));
+      }
+    };
+
+    request.onerror = () => {
+      reject(Error('There was a network error.'));
+    };
+
+    request.send();
+  });
+}
+ +

We return a new promise using the Promise() constructor, which takes as an argument a callback function with resolve and reject parameters. Somewhere in the function, we need to define what happens for the promise to resolve successfully or be rejected — in this case return a 200 OK status or not — and then call resolve on success, or reject on failure. The rest of the contents of this function is fairly standard XHR stuff, so we won’t worry about that for now.

+ +

When we come to call the imgLoad() function, we call it with the url to the image we want to load, as we might expect, but the rest of the code is a little different:

+ +
let body = document.querySelector('body');
+let myImage = new Image();
+
+imgLoad('myLittleVader.jpg').then((response) => {
+  var imageURL = window.URL.createObjectURL(response);
+  myImage.src = imageURL;
+  body.appendChild(myImage);
+}, (Error) => {
+  console.log(Error);
+});
+ +

On to the end of the function call, we chain the promise then() method, which contains two functions — the first one is executed when the promise successfully resolves, and the second is called when the promise is rejected. In the resolved case, we display the image inside myImage and append it to the body (it’s argument is the request.response contained inside the promise’s resolve method); in the rejected case we return an error to the console.

+ +

This all happens asynchronously.

+ +
+

Note: You can also chain promise calls together, for example:
+ myPromise().then(success, failure).then(success).catch(failure);

+
+ +
+

Note: You can find a lot more out about promises by reading Jake Archibald’s excellent JavaScript Promises: there and back again.

+
+ +

Service workers demo

+ +

To demonstrate just the very basics of registering and installing a service worker, we have created a simple demo called sw-test, which is a simple Star wars Lego image gallery. It uses a promise-powered function to read image data from a JSON object and load the images using Ajax, before displaying the images in a line down the page. We’ve kept things static and simple for now. It also registers, installs, and activates a service worker, and when more of the spec is supported by browsers it will cache all the files required so it will work offline!

+ +


+
+
+ You can see the source code on GitHub, and view the example live. The one bit we’ll call out here is the promise (see app.js lines 22-47), which is a modified version of what you read about above, in the Promises test demo. It is different in the following ways:

+ +
    +
  1. In the original, we only passed in a URL to an image we wanted to load. In this version, we pass in a JSON fragment containing all the data for a single image (see what they look like in image-list.js). This is because all the data for each promise resolve has to be passed in with the promise, as it is asynchronous. If you just passed in the url, and then tried to access the other items in the JSON separately when the for() loop is being iterated through later on, it wouldn’t work, as the promise wouldn’t resolve at the same time as the iterations are being done (that is a synchronous process.)
  2. +
  3. We actually resolve the promise with an array, as we want to make the loaded image blob available to the resolving function later on in the code, but also the image name, credits and alt text (see app.js lines 31-34). Promises will only resolve with a single argument, so if you want to resolve with multiple values, you need to use an array/object.
  4. +
  5. To access the resolved promise values, we then access this function as you’d then expect (see app.js lines 60-64). This may seem a bit odd at first, but this is the way promises work.
  6. +
+ +

Enter service workers

+ +

NOTE : We're using the es6 arrow functions syntax in the Service Worker Implementation

+ +

Now let’s get on to service workers!

+ +

Registering your worker

+ +

The first block of code in our app’s JavaScript file — app.js — is as follows. This is our entry point into using service workers.

+ +
if ('serviceWorker' in navigator) {
+  navigator.serviceWorker.register('./sw-test/sw.js', {scope: './sw-test/'})
+  .then((reg) => {
+    // registration worked
+    console.log('Registration succeeded. Scope is ' + reg.scope);
+  }).catch((error) => {
+    // registration failed
+    console.log('Registration failed with ' + error);
+  });
+}
+ +
    +
  1. The outer block performs a feature detection test to make sure service workers are supported before trying to register one.
  2. +
  3. Next, we use the {{domxref("ServiceWorkerContainer.register()") }} function to register the service worker for this site, which is just a JavaScript file residing inside our app (note this is the file's URL relative to the origin, not the JS file that references it.)
  4. +
  5. The scope parameter is optional, and can be used to specify the subset of your content that you want the service worker to control. In this case, we have specified '/sw-test/', which means all content under the app's origin. If you leave it out, it will default to this value anyway, but we specified it here for illustration purposes.
  6. +
  7. The .then() promise function is used to chain a success case onto our promise structure.  When the promise resolves successfully, the code inside it executes.
  8. +
  9. Finally, we chain a .catch() function onto the end that will run if the promise is rejected.
  10. +
+ +

This registers a service worker, which runs in a worker context, and therefore has no DOM access. You then run code in the service worker outside of your normal pages to control their loading.
+
+ A single service worker can control many pages. Each time a page within your scope is loaded, the service worker is installed against that page and operates on it. Bear in mind therefore that you need to be careful with global variables in the service worker script: each page doesn’t get its own unique worker.

+ +
+

Note: Your service worker functions like a proxy server, allowing you to modify requests and responses, replace them with items from its own cache, and more.

+
+ +
+

Note: One great thing about service workers is that if you use feature detection like we’ve shown above, browsers that don’t support service workers can just use your app online in the normal expected fashion. Furthermore, if you use AppCache and SW on a page, browsers that don’t support SW but do support AppCache will use that, and browsers that support both will ignore the AppCache and let SW take over.

+
+ +

Why is my service worker failing to register?

+ +

This could be for the following reasons:

+ +
    +
  1. You are not running your application through HTTPS.
  2. +
  3. The path to your service worker file is not written correctly — it needs to be written relative to the origin, not your app’s root directory. In our example, the worker is at https://mdn.github.io/sw-test/sw.js, and the app’s root is https://mdn.github.io/sw-test/. But the path needs to be written as /sw-test/sw.js, not /sw.js.
  4. +
  5. The service worker being pointed to is on a different origin to that of your app. This is also not allowed.
  6. +
+ +

+ +

Also note:

+ + + +

Install and activate: populating your cache

+ +

After your service worker is registered, the browser will attempt to install then activate the service worker for your page/site.
+
+ The install event is fired when an install is successfully completed. The install event is generally used to populate your browser’s offline caching capabilities with the assets you need to run your app offline. To do this, we use Service Worker’s brand new storage API — {{domxref("cache")}} — a global object on the service worker that allows us to store assets delivered by responses, and keyed by their requests. This API works in a similar way to the browser’s standard cache, but it is specific to your domain. It persists until you tell it not to — again, you have full control.

+ +
+

Note: The Cache API is not supported in every browser. (See the {{anch("Browser compatibility")}} section for more information.) If you want to use this now, you could consider using a polyfill like the one available in Google's Topeka demo, or perhaps store your assets in IndexedDB.

+
+ +

Let’s start this section by looking at a code sample — this is the first block you’ll find in our service worker:

+ +
self.addEventListener('install', (event) => {
+  event.waitUntil(
+    caches.open('v1').then((cache) => {
+      return cache.addAll([
+        './sw-test/',
+        './sw-test/index.html',
+        './sw-test/style.css',
+        './sw-test/app.js',
+        './sw-test/image-list.js',
+        './sw-test/star-wars-logo.jpg',
+        './sw-test/gallery/',
+        './sw-test/gallery/bountyHunters.jpg',
+        './sw-test/gallery/myLittleVader.jpg',
+        './sw-test/gallery/snowTroopers.jpg'
+      ]);
+    })
+  );
+});
+ +
    +
  1. Here we add an install event listener to the service worker (hence self), and then chain a {{domxref("ExtendableEvent.waitUntil()") }} method onto the event — this ensures that the service worker will not install until the code inside waitUntil() has successfully occurred.
  2. +
  3. Inside waitUntil() we use the caches.open() method to create a new cache called v1, which will be version 1 of our site resources cache. This returns a promise for a created cache; once resolved, we then call a function that calls addAll() on the created cache, which for its parameter takes an array of origin-relative URLs to all the resources you want to cache.
  4. +
  5. If the promise is rejected, the install fails, and the worker won’t do anything. This is ok, as you can fix your code and then try again the next time registration occurs.
  6. +
  7. After a successful installation, the service worker activates. This doesn’t have much of a distinct use the first time your service worker is installed/activated, but it means more when the service worker is updated (see the {{anch("Updating your service worker") }} section later on.)
  8. +
+ +
+

Note: localStorage works in a similar way to service worker cache, but it is synchronous, so not allowed in service workers.

+
+ +
+

Note: IndexedDB can be used inside a service worker for data storage if you require it.

+
+ +

Custom responses to requests

+ +

Now you’ve got your site assets cached, you need to tell service workers to do something with the cached content. This is easily done with the fetch event.

+ +

+ +

A fetch event fires every time any resource controlled by a service worker is fetched, which includes the documents inside the specified scope, and any resources referenced in those documents (for example if index.html makes a cross origin request to embed an image, that still goes through its service worker.)

+ +

You can attach a fetch event listener to the service worker, then call the respondWith() method on the event to hijack our HTTP responses and update them with your own magic.

+ +
self.addEventListener('fetch', (event) => {
+  event.respondWith(
+    // magic goes here
+  );
+});
+ +

We could start by simply responding with the resource whose url matches that of the network request, in each case:

+ +
self.addEventListener('fetch', (event) => {
+  event.respondWith(
+    caches.match(event.request)
+  );
+});
+ +

caches.match(event.request) allows us to match each resource requested from the network with the equivalent resource available in the cache, if there is a matching one available. The matching is done via url and vary headers, just like with normal HTTP requests.

+ +

Let’s look at a few other options we have when defining our magic (see our Fetch API documentation for more information about {{domxref("Request")}} and {{domxref("Response")}} objects.)

+ +
    +
  1. +

    The {{domxref("Response.Response","Response()")}} constructor allows you to create a custom response. In this case, we are just returning a simple text string:

    + +
    new Response('Hello from your friendly neighbourhood service worker!');
    +
  2. +
  3. +

    This more complex Response below shows that you can optionally pass a set of headers in with your response, emulating standard HTTP response headers. Here we are just telling the browser what the content type of our synthetic response is:

    + +
    new Response('<p>Hello from your friendly neighbourhood service worker!</p>', {
    +  headers: { 'Content-Type': 'text/html' }
    +});
    +
  4. +
  5. +

    If a match wasn’t found in the cache, you could tell the browser to simply {{domxref("GlobalFetch.fetch","fetch")}} the default network request for that resource, to get the new resource from the network if it is available:

    + +
    fetch(event.request);
    +
  6. +
  7. +

    If a match wasn’t found in the cache, and the network isn’t available, you could just match the request with some kind of default fallback page as a response using {{domxref("CacheStorage.match","match()")}}, like this:

    + +
    caches.match('./fallback.html');
    +
  8. +
  9. +

    You can retrieve a lot of information about each request by calling parameters of the {{domxref("Request")}} object returned by the {{domxref("FetchEvent")}}:

    + +
    event.request.url
    +event.request.method
    +event.request.headers
    +event.request.body
    +
  10. +
+ +

Recovering failed requests

+ +

So caches.match(event.request) is great when there is a match in the service worker cache, but what about cases when there isn’t a match? If we didn’t provide any kind of failure handling, our promise would resolve with undefined and we wouldn't get anything returned.

+ +

Fortunately service workers’ promise-based structure makes it trivial to provide further options towards success. We could do this:

+ +
self.addEventListener('fetch', (event) => {
+  event.respondWith(
+    caches.match(event.request).then((response) => {
+      return response || fetch(event.request);
+    })
+  );
+});
+ +

If the resources aren't in the cache, they are requested from the network.

+ +

If we were being really clever, we would not only request the resource from the network; we would also save it into the cache so that later requests for that resource could be retrieved offline too! This would mean that if extra images were added to the Star Wars gallery, our app could automatically grab them and cache them. The following would do the trick:

+ +
self.addEventListener('fetch', (event) => {
+  event.respondWith(
+    caches.match(event.request).then((resp) => {
+      return resp || fetch(event.request).then((response) => {
+        return caches.open('v1').then((cache) => {
+          cache.put(event.request, response.clone());
+          return response;
+        });
+      });
+    })
+  );
+});
+ +

Here we return the default network request with return fetch(event.request), which returns a promise. When this promise is resolved, we respond by running a function that grabs our cache using caches.open('v1'); this also returns a promise. When that promise resolves, cache.put() is used to add the resource to the cache. The resource is grabbed from event.request, and the response is then cloned with response.clone() and added to the cache. The clone is put in the cache, and the original response is returned to the browser to be given to the page that called it.

+ +

Cloning the response is necessary because request and response streams can only be read once.  In order to return the response to the browser and put it in the cache we have to clone it. So the original gets returned to the browser and the clone gets sent to the cache.  They are each read once.

+ +

The only trouble we have now is that if the request doesn’t match anything in the cache, and the network is not available, our request will still fail. Let’s provide a default fallback so that whatever happens, the user will at least get something:

+ +
self.addEventListener('fetch', (event) => {
+  event.respondWith(
+    caches.match(event.request).then((resp) => {
+      return resp || fetch(event.request).then((response) => {
+        let responseClone = response.clone();
+        caches.open('v1').then((cache) => {
+          cache.put(event.request, responseClone);
+        });
+
+        return response;
+      });
+    }).catch(() => {
+      return caches.match('./sw-test/gallery/myLittleVader.jpg');
+    })
+  );
+});
+ +

We have opted for this fallback image because the only updates that are likely to fail are new images, as everything else is depended on for installation in the install event listener we saw earlier.

+ +

Updating your service worker

+ +

If your service worker has previously been installed, but then a new version of the worker is available on refresh or page load, the new version is installed in the background, but not yet activated. It is only activated when there are no longer any pages loaded that are still using the old service worker. As soon as there are no more such pages still loaded, the new service worker activates.

+ +

You’ll want to update your install event listener in the new service worker to something like this (notice the new version number):

+ +
self.addEventListener('install', (event) => {
+  event.waitUntil(
+    caches.open('v2').then((cache) => {
+      return cache.addAll([
+        './sw-test/',
+        './sw-test/index.html',
+        './sw-test/style.css',
+        './sw-test/app.js',
+        './sw-test/image-list.js',
+
+        …
+
+        // include other new resources for the new version...
+      ]);
+    })
+  );
+});
+ +

While this happens, the previous version is still responsible for fetches. The new version is installing in the background. We are calling the new cache v2, so the previous v1 cache isn't disturbed.

+ +

When no pages are using the current version, the new worker activates and becomes responsible for fetches.

+ +

Deleting old caches

+ +

You also get an activate event. This is a generally used to do stuff that would have broken the previous version while it was still running, for example getting rid of old caches. This is also useful for removing data that is no longer needed to avoid filling up too much disk space — each browser has a hard limit on the amount of cache storage that a given service worker can use. The browser does its best to manage disk space, but it may delete the Cache storage for an origin.  The browser will generally delete all of the data for an origin or none of the data for an origin.

+ +

Promises passed into waitUntil() will block other events until completion, so you can rest assured that your clean-up operation will have completed by the time you get your first fetch event on the new cache.

+ +
self.addEventListener('activate', (event) => {
+  var cacheKeeplist = ['v2'];
+
+  event.waitUntil(
+    caches.keys().then((keyList) => {
+      return Promise.all(keyList.map((key) => {
+        if (cacheKeeplist.indexOf(key) === -1) {
+          return caches.delete(key);
+        }
+      }));
+    })
+  );
+});
+ +

Developer tools

+ +

Chrome has chrome://inspect/#service-workers, which shows current service worker activity and storage on a device, and chrome://serviceworker-internals, which shows more detail and allows you to start/stop/debug the worker process. In the future they will have throttling/offline modes to simulate bad or non-existent connections, which will be a really good thing.

+ +

Firefox has also started to implement some useful tools related to service workers:

+ + + +
+

Note: You may serve your app from http://localhost (e.g. using me@localhost:/my/app$ python -m SimpleHTTPServer) for local development. See Security considerations

+
+ +

See also

+ + diff --git a/files/pt-pt/web/api/sharedworker/index.html b/files/pt-pt/web/api/sharedworker/index.html new file mode 100644 index 0000000000..5f7babaa6f --- /dev/null +++ b/files/pt-pt/web/api/sharedworker/index.html @@ -0,0 +1,200 @@ +--- +title: SharedWorker +slug: Web/API/SharedWorker +tags: + - API + - Interface + - Referencia + - SharedWorker + - Web Workers + - Workers +translation_of: Web/API/SharedWorker +--- +
{{APIRef("Web Workers API")}}
+ +

A interface SharedWorker representa um tipo de worker específico que pode ser acedido  a partir de vários contextos de navegação, tais como várias janelas, iframes ou até workers. Eles implementam uma interface diferente do que os workers dedicados e têm um âmbito global diferente, {{domxref("SharedWorkerGlobalScope")}}.

+ +
+

Nota:  Se o SharedWorker puder ser acedido a partir de vários contextos de navegação, todos esses contextos de navegação devem partilhar exatamente a mesma origem (mesmo protocolo, anfitrião e porto).

+
+ +

Construtor

+ +
+
{{domxref("SharedWorker.SharedWorker", "SharedWorker()")}}
+
Cria um web worker partilhado que executa uma script na URL indicada.
+
+ +

Propriedades

+ +

Esta interface também herda propriedades de {{domxref("EventTarget")}} de qual se deriva, e implementa propriedades de {{domxref("AbstractWorker")}}.

+ +
+
{{domxref("AbstractWorker.onerror")}}
+
É um {{domxref("EventListener")}} chamado quando um {{domxref("ErrorEvent")}} do tipo error sai do worker.
+
{{domxref("SharedWorker.port")}} {{readonlyInline}}
+
Devolve um objeto {{domxref("MessagePort")}} usado para controlar e comunicar com o worker partilhado.
+
+ +
+
+ +

Métodos

+ +

Esta interface também herda métodos de {{domxref("EventTarget")}} de qual se deriva, e implementa métodos de {{domxref("AbstractWorker")}}.

+ +

Exemplo

+ +

No nosso exemplo básico dum worker partilhado, temos duas páginas de HTML, cada qual usa JavaScript para fazer um simples cálculo. Os scripts diferentes estão a utilizar o mesmo ficheiro de worker para fazer os cálculos — ambos podem-no aceder, mesmo se as páginas estiverem a correr em janelas diferentes.

+ +

O seguinte snippet de código demonstra a criação dum objeto {{domxref("SharedWorker")}} usando o construtor {{domxref("SharedWorker.SharedWorker", "SharedWorker()")}}. Ambas scripts contêm isto:

+ +
var myWorker = new SharedWorker('worker.js');
+
+ +

Ambas scripts acedem ao worker através dum objeto {{domxref("MessagePort")}} criado usando a propriedade {{domxref("SharedWorker.port")}}. Se o evento onmessage foi adicionado usando addEventListener, a porta é manualmente criada usando o seu método start():

+ +
myWorker.port.start();
+ +

Quando a porta é iniciada, ambos scripts enviam mensagens ao worker e processão mensagens vindas do worker usando port.postMessage() e port.onmessage, respetivamente:

+ +
first.onchange = function() {
+  myWorker.port.postMessage([first.value,second.value]);
+  console.log(' Mensagem enviada ao worker');
+}
+
+second.onchange = function() {
+  myWorker.port.postMessage([first.value,second.value]);
+  console.log(' Mensagem enviada ao worker');
+}
+
+myWorker.port.onmessage = function(e) {
+  result1.textContent = e.data;
+  console.log(' Mensagem recebida do worker');
+}
+ +

Dentro do worker usamos o handler {{domxref("SharedWorkerGlobalScope.onconnect")}} para nos ligarmos à mesma porta a que referimos antes. As portas associadas a esse worker são acessíveis através da propriedade ports do evento {{event("connect")}} — nós depois usamos o método start() de {{domxref("MessagePort")}} para iniciar a porta, e o handler onmessage para lidar com as mensagens enviadas dos threads principais.

+ +
onconnect = function(e) {
+  var port = e.ports[0];
+
+  port.addEventListener('message', function(e) {
+    var workerResult = 'Result: ' + (e.data[0] * e.data[1]);
+    port.postMessage(workerResult);
+  });
+
+  port.start(); // Necessário quando se usa addEventListener. Senão é chamado implicitamente pelo setter de onmessage.
+}
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('HTML WHATWG', "#sharedworker", "SharedWorker")}}{{Spec2('HTML WHATWG')}}Sem diferenças em comparação a {{SpecName("Web Workers")}}.
+ +

Compatibilidade

+ + + +

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

+ +

Ver também

+ + + +
+ + + + + +
diff --git a/files/pt-pt/web/api/sistema_de_ficheiros/index.html b/files/pt-pt/web/api/sistema_de_ficheiros/index.html new file mode 100644 index 0000000000..76c4db9d6c --- /dev/null +++ b/files/pt-pt/web/api/sistema_de_ficheiros/index.html @@ -0,0 +1,54 @@ +--- +title: Sistema de Ficheiros +slug: Web/API/Sistema_de_ficheiros +tags: + - API + - File API + - File System API + - File and Directory Entries API + - Interface + - Não Standard + - Offline + - filesystem +translation_of: Web/API/FileSystem +--- +
+

{{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/urlsearchparams/index.html b/files/pt-pt/web/api/urlsearchparams/index.html new file mode 100644 index 0000000000..3cbed3eea5 --- /dev/null +++ b/files/pt-pt/web/api/urlsearchparams/index.html @@ -0,0 +1,207 @@ +--- +title: URLSearchParams +slug: Web/API/URLSearchParams +translation_of: Web/API/URLSearchParams +--- +

{{ApiRef("URL API")}}

+ +

O interface URLSearchParams define métodos que permitem trabalhar com uma query string de um URL.

+ +

Um objeto que implemente URLSearchParams pode ser utilizado diretamente numa estrutura {{jsxref("Statements/for...of", "for...of")}}, em vez de {{domxref('URLSearchParams.entries()', 'entries()')}}: for (var p of mySearchParams) é equivalente a for (var p of mySearchParams.entries()).

+ +

Construtor

+ +
+
{{domxref("URLSearchParams.URLSearchParams", 'URLSearchParams()')}}
+
O construtor devolve um objeto URLSearchParams.
+
+ +

Propriedades

+ +

Este interface não herda nehuma propriedade.

+ +

Métodos

+ +

Este interface não herda nehum método.

+ +
+
{{domxref("URLSearchParams.append()")}}
+
Adiciona um par chave/valor como um novo parâmetro de pesquisa.
+
{{domxref("URLSearchParams.delete()")}}
+
Elimina o parâmetro de pesquisa e o seu valor, da lista de parâmetros de pesquisa.
+
{{domxref("URLSearchParams.entries()")}}
+
Devolve um {{jsxref("Iteration_protocols","iterator")}} que permite iterar pelos pares chave/valor neste objeto.
+
{{domxref("URLSearchParams.get()")}}
+
Devolve o primeiro valor relacionado com o parâmetro de pesquisa enviado.
+
{{domxref("URLSearchParams.getAll()")}}
+
Devolve todos os valores relacionados com um determinado parâmetro de pesquisa.
+
{{domxref("URLSearchParams.has()")}}
+
Devolve um {{jsxref("Boolean")}} , indicando de um determinado parâmetro de pesquisa existe.
+
{{domxref("URLSearchParams.keys()")}}
+
Devolve um {{jsxref("Iteration_protocols", "iterator")}} permitindo interar pelas chaves de todos os pares chave/valor existentes no objeto.
+
{{domxref("URLSearchParams.set()")}}
+
Define o valor associado a um parâmetro de pesquisa. Elimina outros valores se existirem.
+
{{domxref("URLSearchParams.toString()")}}
+
Devolve uma string com os parâmetros válidos para serem utilizados num URL.
+
{{domxref("URLSearchParams.values()")}}
+
Devolve um {{jsxref("Iteration_protocols", "iterator")}} que permite iterar por todos os valores dos pares chave/valor existentes neste objeto.
+
+ +

Exemplo

+ +
var paramsString = "q=URLUtils.searchParams&topic=api"
+var searchParams = new URLSearchParams(paramsString);
+
+//Iterar pelos parâmetros de pesquisa.
+for (let p of searchParams) {
+  console.log(p);
+}
+
+searchParams.has("topic") === true; // true
+searchParams.get("topic") === "api"; // true
+searchParams.getAll("topic"); // ["api"]
+searchParams.get("foo") === null; // true
+searchParams.append("topic", "webdev");
+searchParams.toString(); // "q=URLUtils.searchParams&topic=api&topic=webdev"
+searchParams.set("topic", "More webdev");
+searchParams.toString(); // "q=URLUtils.searchParams&topic=More+webdev"
+searchParams.delete("topic");
+searchParams.toString(); // "q=URLUtils.searchParams"
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('URL', '#urlsearchparams', "URLSearchParams")}}{{Spec2('URL')}}Definição inicial.
+ +

Compatibilidade Browsers

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatChrome(49)}}{{CompatGeckoDesktop("29.0")}}{{CompatNo}}3610.1
entries(), keys(), values(), e suporte de for...of{{CompatChrome(49)}}{{CompatGeckoDesktop("44.0")}}{{CompatNo}}36{{CompatUnknown}}
USVString for constructor init object{{CompatVersionUnknown}}{{CompatGeckoDesktop("53.0")}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatUnknown}}
Record for constructor init object{{CompatUnknown}}{{CompatGeckoDesktop("54.0")}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome para Android
Suporte básico{{CompatNo}}{{CompatChrome(49)}}{{CompatGeckoMobile("29.0")}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatChrome(49)}}
entries(), keys(), values(), e suport de for...of{{CompatNo}}{{CompatChrome(49)}}{{CompatGeckoMobile("44.0")}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatChrome(49)}}
USVString for constructor init object{{CompatNo}}{{CompatVersionUnknown}}{{CompatGeckoMobile("53.0")}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
Record for constructor init object{{CompatNo}}{{CompatUnknown}}{{CompatGeckoMobile("54.0")}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Ver também

+ + + +
+
diff --git a/files/pt-pt/web/api/web_audio_api/index.html b/files/pt-pt/web/api/web_audio_api/index.html new file mode 100644 index 0000000000..815ab1ad91 --- /dev/null +++ b/files/pt-pt/web/api/web_audio_api/index.html @@ -0,0 +1,512 @@ +--- +title: API de Áudio da Web +slug: Web/API/Web_Audio_API +tags: + - API + - API de Áudio da Web + - Exemplo + - Guía + - Landing + - Overview + - Resumo + - Web Audio API +translation_of: Web/API/Web_Audio_API +--- +
+

The Web Audio API provides a powerful and versatile system for controlling audio on the Web, allowing developers to choose audio sources, add effects to audio, create audio visualizations, apply spatial effects (such as panning)  and much more.

+
+ +

Conceitos e utilização de áudio da Web

+ +

The Web Audio API involves handling 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. Several sources — with different types of channel layout — are supported even within a single context. This modular design provides the flexibility to create complex audio functions with dynamic effects.

+ +

Audio nodes are linked into chains and simple webs by their inputs and outputs. They typically start with one or more sources. Sources provide arrays of sound intensities (samples) at very small timeslices, often tens of thousands of them per second. These could be either computed mathematically (such as {{domxref("OscillatorNode")}}), or they can be recordings from sound/video files (like {{domxref("AudioBufferSourceNode")}} and {{domxref("MediaElementAudioSourceNode")}}) and audio streams ({{domxref("MediaStreamAudioSourceNode")}}). In fact, sound files are just recordings of sound intensities themselves, which come in from microphones or electric instruments, and get mixed down into a single, complicated wave.

+ +

Outputs of these nodes could be linked to inputs of others, which mix or modify these streams of sound samples into different streams. A common modification is multiplying the samples by a value to make them louder or quieter (as is the case with {{domxref("GainNode")}}). Once the sound has been sufficiently processed for the intended effect, it can be linked to the input of a destination ({{domxref("AudioContext.destination")}}), which sends the sound to the speakers or headphones. This last connection is only necessary if the user is supposed to hear the audio.

+ +

A simple, typical workflow for web audio would look something like this:

+ +
    +
  1. Create audio context
  2. +
  3. Inside the context, create sources — such as <audio>, oscillator, stream
  4. +
  5. Create effects nodes, such as reverb, biquad filter, panner, compressor
  6. +
  7. Choose final destination of audio, for example your system speakers
  8. +
  9. Connect the sources up to the effects, and the effects to the destination.
  10. +
+ +

A simple box diagram with an outer box labeled Audio context, and three inner boxes labeled Sources, Effects and Destination. The three inner boxes have arrow between them pointing from left to right, indicating the flow of audio information.

+ +

Timing is controlled with high precision and low latency, allowing developers to write code that responds accurately to events and is able to target specific samples, even at a high sample rate. So applications such as drum machines and sequencers are well within reach.

+ +

The Web Audio API also allows us to control how audio is spatialized. Using a system based on a source-listener model, it allows control of the panning model and deals with distance-induced attenuation or doppler shift induced by a moving source (or moving listener).

+ +
+

You can read about the theory of the Web Audio API in a lot more detail in our article Basic concepts behind Web Audio API.

+
+ +

Interfaces de API de Áudio da Web

+ +

The Web Audio API has a number of interfaces and associated events, which we have split up into nine categories of functionality.

+ +

General audio graph definition

+ +

General containers and definitions that shape audio graphs in Web Audio API usage.

+ +
+
{{domxref("AudioContext")}}
+
The AudioContext interface represents an audio-processing graph built from audio modules linked together, each represented by an {{domxref("AudioNode")}}. An audio context controls the creation of the nodes it contains and the execution of the audio processing, or decoding. You need to create an AudioContext before you do anything else, as everything happens inside a context.
+
{{domxref("AudioNode")}}
+
The AudioNode interface represents an audio-processing module like an audio source (e.g. an HTML {{HTMLElement("audio")}} or {{HTMLElement("video")}} element), audio destination, intermediate processing module (e.g. a filter like {{domxref("BiquadFilterNode")}}, or volume control like {{domxref("GainNode")}}).
+
{{domxref("AudioParam")}}
+
The AudioParam interface represents an audio-related parameter, like one of an {{domxref("AudioNode")}}. It can be set to a specific value or a change in value, and can be scheduled to happen at a specific time and following a specific pattern.
+
The {{event("ended")}} event
+
The ended event is fired when playback has stopped because the end of the media was reached.
+
+ +

Defining audio sources

+ +

Interfaces that define audio sources for use in the Web Audio API.

+ +
+
{{domxref("OscillatorNode")}}
+
The OscillatorNode interface represents a periodic waveform, such as a sine or triangle wave. It is an {{domxref("AudioNode")}} audio-processing module that causes a given frequency of wave to be created.
+
{{domxref("AudioBuffer")}}
+
The AudioBuffer interface represents a short audio asset residing in memory, created from an audio file using the {{ domxref("AudioContext.decodeAudioData()") }} method, or created with raw data using {{ domxref("AudioContext.createBuffer()") }}. Once decoded into this form, the audio can then be put into an {{ domxref("AudioBufferSourceNode") }}.
+
{{domxref("AudioBufferSourceNode")}}
+
The AudioBufferSourceNode interface represents an audio source consisting of in-memory audio data, stored in an {{domxref("AudioBuffer")}}. It is an {{domxref("AudioNode")}} that acts as an audio source.
+
{{domxref("MediaElementAudioSourceNode")}}
+
The MediaElementAudioSourceNode interface represents an audio source consisting of an HTML5 {{ htmlelement("audio") }} or {{ htmlelement("video") }} element. It is an {{domxref("AudioNode")}} that acts as an audio source.
+
{{domxref("MediaStreamAudioSourceNode")}}
+
The MediaStreamAudioSourceNode interface represents an audio source consisting of a WebRTC {{domxref("MediaStream")}} (such as a webcam, microphone, or a stream being sent from a remote computer). It is an {{domxref("AudioNode")}} that acts as an audio source.
+
+ +

Defining audio effects filters

+ +

Interfaces for defining effects that you want to apply to your audio sources.

+ +
+
{{domxref("BiquadFilterNode")}}
+
The BiquadFilterNode interface represents a simple low-order filter. It is an {{domxref("AudioNode")}} that can represent different kinds of filters, tone control devices, or graphic equalizers. A BiquadFilterNode always has exactly one input and one output.
+
{{domxref("ConvolverNode")}}
+
The ConvolverNode interface is an {{domxref("AudioNode")}} that performs a Linear Convolution on a given {{domxref("AudioBuffer")}}, and is often used to achieve a reverb effect.
+
{{domxref("DelayNode")}}
+
The DelayNode interface represents a delay-line; an {{domxref("AudioNode")}} audio-processing module that causes a delay between the arrival of an input data and its propagation to the output.
+
{{domxref("DynamicsCompressorNode")}}
+
The DynamicsCompressorNode interface provides a compression effect, which lowers the volume of the loudest parts of the signal in order to help prevent clipping and distortion that can occur when multiple sounds are played and multiplexed together at once.
+
{{domxref("GainNode")}}
+
The GainNode interface represents a change in volume. It is an {{domxref("AudioNode")}} audio-processing module that causes a given gain to be applied to the input data before its propagation to the output.
+
{{domxref("StereoPannerNode")}}
+
The StereoPannerNode interface represents a simple stereo panner node  that can be used to pan an audio stream left or right.
+
{{domxref("WaveShaperNode")}}
+
The WaveShaperNode interface represents a non-linear distorter. It is an {{domxref("AudioNode")}} that use a curve to apply a waveshaping distortion to the signal. Beside obvious distortion effects, it is often used to add a warm feeling to the signal.
+
{{domxref("PeriodicWave")}}
+
Describes a periodic waveform that can be used to shape the output of an {{ domxref("OscillatorNode") }}.
+
+ +

Defining audio destinations

+ +

Once you are done processing your audio, these interfaces define where to output it.

+ +
+
{{domxref("AudioDestinationNode")}}
+
The AudioDestinationNode interface represents the end destination of an audio source in a given context — usually the speakers of your device.
+
{{domxref("MediaStreamAudioDestinationNode")}}
+
The MediaStreamAudioDestinationNode interface represents an audio destination consisting of a WebRTC {{domxref("MediaStream")}} with a single AudioMediaStreamTrack, which can be used in a similar way to a {{domxref("MediaStream")}} obtained from {{ domxref("MediaDevices.getUserMedia", "getUserMedia()") }}. It is an {{domxref("AudioNode")}} that acts as an audio destination.
+
+ +

Data analysis and visualization

+ +

If you want to extract time, frequency, and other data from your audio, the AnalyserNode is what you need.

+ +
+
{{domxref("AnalyserNode")}}
+
The AnalyserNode interface represents a node able to provide real-time frequency and time-domain analysis information, for the purposes of data analysis and visualization.
+
+ +

Splitting and merging audio channels

+ +

To split and merge audio channels, you'll use these interfaces.

+ +
+
{{domxref("ChannelSplitterNode")}}
+
The ChannelSplitterNode interface separates the different channels of an audio source out into a set of mono outputs.
+
{{domxref("ChannelMergerNode")}}
+
The ChannelMergerNode interface reunites different mono inputs into a single output. Each input will be used to fill a channel of the output.
+
+ +

Audio spatialization

+ +

These interfaces allow you to add audio spatialization panning effects to your audio sources.

+ +
+
{{domxref("AudioListener")}}
+
The AudioListener interface represents the position and orientation of the unique person listening to the audio scene used in audio spatialization.
+
{{domxref("PannerNode")}}
+
The PannerNode interface represents the behavior of a signal in space. It is an {{domxref("AudioNode")}} audio-processing module describing its position with right-hand Cartesian coordinates, its movement using a velocity vector and its directionality using a directionality cone.
+
+ +

Audio processing in JavaScript

+ +

You can write JavaScript code to process audio data. To do so, you use the interfaces and events listed below.

+ +
+

As of the August 29, 2014 version of the Web Audio API spec. these features have been marked as deprecated, and are soon to be replaced by {{ anch("Audio_Workers") }}.

+
+ +
+
{{domxref("ScriptProcessorNode")}}
+
The ScriptProcessorNode interface allows the generation, processing, or analyzing of audio using JavaScript. It is an {{domxref("AudioNode")}} audio-processing module that is linked to two buffers, one containing the current input, one containing the output. An event, implementing the {{domxref("AudioProcessingEvent")}} interface, is sent to the object each time the input buffer contains new data, and the event handler terminates when it has filled the output buffer with data.
+
{{event("audioprocess")}} (event)
+
The audioprocess event is fired when an input buffer of a Web Audio API {{domxref("ScriptProcessorNode")}} is ready to be processed.
+
{{domxref("AudioProcessingEvent")}}
+
The Web Audio API AudioProcessingEvent represents events that occur when a {{domxref("ScriptProcessorNode")}} input buffer is ready to be processed.
+
+ +

Offline/background audio processing

+ +

It is possible to process/render an audio graph very quickly in the background — rendering it to an {{domxref("AudioBuffer")}} rather than to the device's speakers — with the following.

+ +
+
{{domxref("OfflineAudioContext")}}
+
The OfflineAudioContext interface is an {{domxref("AudioContext")}} interface representing an audio-processing graph built from linked together {{domxref("AudioNode")}}s. In contrast with a standard AudioContext, an OfflineAudioContext doesn't really render the audio but rather generates it, as fast as it can, in a buffer.
+
{{event("complete")}} (event)
+
The complete event is fired when the rendering of an {{domxref("OfflineAudioContext")}} is terminated.
+
{{domxref("OfflineAudioCompletionEvent")}}
+
The OfflineAudioCompletionEvent represents events that occur when the processing of an {{domxref("OfflineAudioContext")}} is terminated. The {{event("complete")}} event implements this interface.
+
+ +

Audio Workers

+ +

Audio workers provide the ability for direct scripted audio processing to be done inside a web worker context, and are defined by a couple of interfaces (new as of 29th August 2014). These are not implemented in any browsers yet. When implemented, they will replace {{domxref("ScriptProcessorNode")}}, and the other features discussed in the Audio processing in JavaScript section above.

+ +
+
{{domxref("AudioWorkerNode")}}
+
The AudioWorkerNode interface represents an {{domxref("AudioNode")}} that interacts with a worker thread to generate, process, or analyse audio directly.
+
{{domxref("AudioWorkerGlobalScope")}}
+
The AudioWorkerGlobalScope interface is a DedicatedWorkerGlobalScope-derived object representing a worker context in which an audio processing script is run; it is designed to enable the generation, processing, and analysis of audio data directly using JavaScript in a worker thread.
+
{{domxref("AudioProcessEvent")}}
+
This is an Event object that is dispatched to {{domxref("AudioWorkerGlobalScope")}} objects to perform processing.
+
+ +

Interfaces obsoletas

+ +

The following interfaces were defined in old versions of the Web Audio API spec, but are now obsolete and have been replaced by other interfaces.

+ +
+
{{domxref("JavaScriptNode")}}
+
Used for direct audio processing via JavaScript. This interface is obsolete, and has been replaced by {{domxref("ScriptProcessorNode")}}.
+
{{domxref("WaveTableNode")}}
+
Used to define a periodic waveform. This interface is obsolete, and has been replaced by {{domxref("PeriodicWave")}}.
+
+ +

Exemplo

+ +

This example shows a wide variety of Web Audio API functions being used. You can see this code in action on the Voice-change-o-matic demo (also check out the full source code at Github) — this is an experimental voice changer toy demo; keep your speakers turned down low when you use it, at least to start!

+ +

The Web Audio API lines are highlighted; if you want to find out more about what the different methods, etc. do, have a search around the reference pages.

+ +
var audioCtx = new (window.AudioContext || window.webkitAudioContext)(); // define audio context
+// Webkit/blink browsers need prefix, Safari won't work without window.
+
+var voiceSelect = document.getElementById("voice"); // select box for selecting voice effect options
+var visualSelect = document.getElementById("visual"); // select box for selecting audio visualization options
+var mute = document.querySelector('.mute'); // mute button
+var drawVisual; // requestAnimationFrame
+
+var analyser = audioCtx.createAnalyser();
+var distortion = audioCtx.createWaveShaper();
+var gainNode = audioCtx.createGain();
+var biquadFilter = audioCtx.createBiquadFilter();
+
+function makeDistortionCurve(amount) { // function to make curve shape for distortion/wave shaper node to use
+  var k = typeof amount === 'number' ? amount : 50,
+    n_samples = 44100,
+    curve = new Float32Array(n_samples),
+    deg = Math.PI / 180,
+    i = 0,
+    x;
+  for ( ; i < n_samples; ++i ) {
+    x = i * 2 / n_samples - 1;
+    curve[i] = ( 3 + k ) * x * 20 * deg / ( Math.PI + k * Math.abs(x) );
+  }
+  return curve;
+};
+
+navigator.getUserMedia (
+  // constraints - only audio needed for this app
+  {
+    audio: true
+  },
+
+  // Success callback
+  function(stream) {
+    source = audioCtx.createMediaStreamSource(stream);
+    source.connect(analyser);
+    analyser.connect(distortion);
+    distortion.connect(biquadFilter);
+    biquadFilter.connect(gainNode);
+    gainNode.connect(audioCtx.destination); // connecting the different audio graph nodes together
+
+    visualize(stream);
+    voiceChange();
+
+  },
+
+  // Error callback
+  function(err) {
+    console.log('The following gUM error occured: ' + err);
+  }
+);
+
+function visualize(stream) {
+  WIDTH = canvas.width;
+  HEIGHT = canvas.height;
+
+  var visualSetting = visualSelect.value;
+  console.log(visualSetting);
+
+  if(visualSetting == "sinewave") {
+    analyser.fftSize = 2048;
+    var bufferLength = analyser.frequencyBinCount; // half the FFT value
+    var dataArray = new Uint8Array(bufferLength); // create an array to store the data
+
+    canvasCtx.clearRect(0, 0, WIDTH, HEIGHT);
+
+    function draw() {
+
+      drawVisual = requestAnimationFrame(draw);
+
+      analyser.getByteTimeDomainData(dataArray); // get waveform data and put it into the array created above
+
+      canvasCtx.fillStyle = 'rgb(200, 200, 200)'; // draw wave with canvas
+      canvasCtx.fillRect(0, 0, WIDTH, HEIGHT);
+
+      canvasCtx.lineWidth = 2;
+      canvasCtx.strokeStyle = 'rgb(0, 0, 0)';
+
+      canvasCtx.beginPath();
+
+      var sliceWidth = WIDTH * 1.0 / bufferLength;
+      var x = 0;
+
+      for(var i = 0; i < bufferLength; i++) {
+
+        var v = dataArray[i] / 128.0;
+        var y = v * HEIGHT/2;
+
+        if(i === 0) {
+          canvasCtx.moveTo(x, y);
+        } else {
+          canvasCtx.lineTo(x, y);
+        }
+
+        x += sliceWidth;
+      }
+
+      canvasCtx.lineTo(canvas.width, canvas.height/2);
+      canvasCtx.stroke();
+    };
+
+    draw();
+
+  } else if(visualSetting == "off") {
+    canvasCtx.clearRect(0, 0, WIDTH, HEIGHT);
+    canvasCtx.fillStyle = "red";
+    canvasCtx.fillRect(0, 0, WIDTH, HEIGHT);
+  }
+
+}
+
+function voiceChange() {
+  distortion.curve = new Float32Array;
+  biquadFilter.gain.value = 0; // reset the effects each time the voiceChange function is run
+
+  var voiceSetting = voiceSelect.value;
+  console.log(voiceSetting);
+
+  if(voiceSetting == "distortion") {
+    distortion.curve = makeDistortionCurve(400); // apply distortion to sound using waveshaper node
+  } else if(voiceSetting == "biquad") {
+    biquadFilter.type = "lowshelf";
+    biquadFilter.frequency.value = 1000;
+    biquadFilter.gain.value = 25; // apply lowshelf filter to sounds using biquad
+  } else if(voiceSetting == "off") {
+    console.log("Voice settings turned off"); // do nothing, as off option was chosen
+  }
+
+}
+
+// event listeners to change visualize and voice settings
+
+visualSelect.onchange = function() {
+  window.cancelAnimationFrame(drawVisual);
+  visualize(stream);
+}
+
+voiceSelect.onchange = function() {
+  voiceChange();
+}
+
+mute.onclick = voiceMute;
+
+function voiceMute() { // toggle to mute and unmute sound
+  if(mute.id == "") {
+    gainNode.gain.value = 0; // gain set to 0 to mute sound
+    mute.id = "activated";
+    mute.innerHTML = "Unmute";
+  } else {
+    gainNode.gain.value = 1; // gain set to 1 to unmute sound
+    mute.id = "";
+    mute.innerHTML = "Mute";
+  }
+}
+
+ +

Especificações

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API')}}{{Spec2('Web Audio API')}} 
+ +

Compatibilidade do navegador

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support14 {{property_prefix("webkit")}}{{CompatVersionUnknown}}23{{CompatNo}}15 {{property_prefix("webkit")}}
+ 22 (unprefixed)
6 {{property_prefix("webkit")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChromeEdgeFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Basic support{{CompatNo}}28 {{property_prefix("webkit")}}{{CompatVersionUnknown}}251.2{{CompatNo}}{{CompatNo}}6 {{property_prefix("webkit")}}
+
+ +

Consultar também

+ + + + diff --git a/files/pt-pt/web/api/web_audio_api/utilizar_api_audio_web/index.html b/files/pt-pt/web/api/web_audio_api/utilizar_api_audio_web/index.html new file mode 100644 index 0000000000..d9a72f2694 --- /dev/null +++ b/files/pt-pt/web/api/web_audio_api/utilizar_api_audio_web/index.html @@ -0,0 +1,259 @@ +--- +title: Utilizar a API de Áudio da Web +slug: Web/API/Web_Audio_API/Utilizar_api_audio_web +tags: + - API + - API de Áudio da Web + - Guía + - Referencia + - Utilização + - básicos +translation_of: Web/API/Web_Audio_API/Using_Web_Audio_API +--- +
{{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_workers_api/functions_and_classes_available_to_workers/index.html b/files/pt-pt/web/api/web_workers_api/functions_and_classes_available_to_workers/index.html new file mode 100644 index 0000000000..ee969bfb75 --- /dev/null +++ b/files/pt-pt/web/api/web_workers_api/functions_and_classes_available_to_workers/index.html @@ -0,0 +1,443 @@ +--- +title: Funções e classes disponíveis para os Workers da Web +slug: Web/API/Web_Workers_API/Functions_and_classes_available_to_workers +tags: + - Referencia + - Web +translation_of: Web/API/Web_Workers_API/Functions_and_classes_available_to_workers +--- +

In addition to the standard JavaScript set of functions (such as {{jsxref("String")}}, {{jsxref("Array")}}, {{jsxref("Object")}}, {{jsxref("JSON")}}, etc), there are a variety of functions available from the DOM to workers. This article provides a list of those.

+ +

Workers run in another global context, {{domxref("DedicatedWorkerGlobalScope")}}, different from the current window. By default, methods and properties of {{domxref("Window")}} are not available to them, but {{domxref("DedicatedWorkerGlobalScope")}}, like Window, implements {{domxref("WindowTimers")}} and {{domxref("WindowBase64")}}.

+ +

Comparação das propriedades e métodos de diferentes tipos de workers

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FunçãoWorkers dedicadosShared workersService workersChrome workers {{Non-standard_inline}}Outside workers
{{domxref("WindowBase64.atob", "atob()")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("Window")}}
{{domxref("WindowBase64.btoa", "btoa()")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("Window")}}
{{domxref("WindowTimers.clearInterval", "clearInterval()")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("Window")}}
{{domxref("WindowTimers.clearTimeout", "clearTimeout()")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("Window")}}
{{domxref("Window.dump()", "dump()")}} {{non-standard_inline}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("Window")}}
{{domxref("WindowTimers.setInterval", "setInterval()")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("Window")}}
{{domxref("WindowTimers.setTimeout", "setTimeout()")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("Window")}}
{{domxref("WorkerGlobalScope.importScripts", "importScripts()")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}no
{{domxref("WorkerGlobalScope.close", "close()")}} {{non-standard_inline}}yes, on {{domxref("WorkerGlobalScope")}}yes, on {{domxref("WorkerGlobalScope")}}yes, but is a no-op.Unknownno
{{domxref("DedicatedWorkerGlobalScope.postMessage", "postMessage()")}}yes, on {{domxref("DedicatedWorkerGlobalScope")}}nonoUnknownno
+ +

APIs disponíveis nos workers

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FunçãoFuncionalidadeSuporte no Gecko (Firefox)Support in IESupport in Blink (Chrome and Opera)Support in WebKit (Safari)
{{domxref("Broadcast_Channel_API","Broadcast Channel API")}}Allows simple communication between {{glossary("browsing context", "browsing contexts")}} (that is windows, tabs, frames, or iframes) with the same {{glossary("origin")}} (usually pages from the same site).{{ CompatGeckoDesktop(38)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
{{domxref("Cache", "Cache")}}Cache API provides the ability to programmatically control cache storage associated with current origin.{{CompatVersionUnknown}}{{CompatNo}}{{ CompatChrome(43) }}{{CompatUnknown}}
{{domxref("Channel_Messaging_API", "Channel Messaging API")}}Allows two separate scripts running in different browsing contexts attached to the same document (e.g., two IFrames, or the main document and an IFrame, two documents via a {{domxref("SharedWorker")}}, or two workers) to communicate directly via two ports.{{ CompatGeckoDesktop(41)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
{{domxref("Console", "Console API")}}Provides access to the browser's debugging console (e.g., the Web Console in Firefox). The specifics of how it works vary from browser to browser, but there is a de facto set of features that are typically provided.{{ CompatGeckoDesktop(38)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
{{domxref("CustomEvent")}}The CustomEvent interface represents events initialized by an application for any purpose.{{ CompatGeckoDesktop(48)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
{{domxref("Data_Store_API", "Data Store")}}A powerful, flexible storage mechanism for multiple Firefox OS applications to use to store and share data between one another quickly, efficiently, and securely.Only in Firefox OS internal (certified) applications, since v1.0.1.{{CompatNo}}{{CompatNo}}{{CompatNo}}
{{domxref("DOMRequest")}} and {{domxref("DOMCursor")}}Respectively, these objects represents an ongoing operation (with listeners for reacting to the operation completely successfully, or failing, for example), and an ongoing operation over a list of results.{{ CompatGeckoDesktop(41)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
{{domxref("Fetch_API", "Fetch")}}The Fetch spec provides an up-to-date definition of, and API for, fetching resources (e.g. across the network.)Mostly in {{ CompatGeckoDesktop(34)}} behind pref, although a few features are later.{{CompatNo}}{{ CompatChrome(42) }}
+ {{ CompatChrome(41) }} behind pref
{{CompatNo}}
{{domxref("FileReader")}}This API allows asynchronous read of {{domxref("Blob")}} and {{domxref("File")}} objects.{{CompatGeckoDesktop(46)}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}
{{domxref("FileReaderSync")}}This API allows synchronous read of {{domxref("Blob")}} and {{domxref("File")}} objects. This is an API that works only in workers.{{CompatGeckoDesktop(8)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
{{domxref("FormData")}}FormData objects provide a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the XMLHttpRequest send() method.{{CompatUnknown}} (should be in {{CompatGeckoDesktop(39)}}){{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
{{domxref("ImageData")}}The underlying pixel data of an area of a {{domxref("canvas")}} element. Manipulating such data can be a complex task better suited to be delegated to a Web Worker.{{CompatGeckoDesktop(25)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
{{domxref("IndexedDB_API", "IndexedDB")}}Database to store records holding simple values and hierarchical objects.{{CompatGeckoDesktop(37)}},  {{CompatGeckoDesktop(42)}} for {{domxref("IDBCursorWithValue")}}.10.0{{CompatVersionUnknown}}{{CompatNo}}
Network Information APIprovides information about the system's connection in terms of general connection type (e.g., 'wifi', 'cellular', etc.).{{CompatGeckoMobile(53)}} only on mobile{{CompatVersionUnknown}} only on mobile{{CompatNo}}{{CompatNo}}
{{domxref("Notifications_API", "Notifications")}}Allows web pages to control the display of system notifications to the end user{{CompatGeckoDesktop(41)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
{{domxref("Performance")}}The Performance interface represents timing-related performance information for the given page.{{ CompatGeckoDesktop("34.0") }}{{CompatUnknown}}{{ CompatChrome("33.0") }}{{CompatUnknown}}
{{jsxref("Promise")}}JavaScript objects that allow you to write asynchronous functions.{{CompatGeckoDesktop(28)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Server-sent eventsAllows a server to push data to a web page at any point, after a connection has been opened to it.{{CompatGeckoDesktop(53)}} (currently only available in dedicated and shared workers; not service workers.){{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
{{domxref("ServiceWorkerRegistration")}}You can register a service worker from inside a standard worker, and use associated functionality.{{CompatGeckoDesktop(40)}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}
{{domxref("TextEncoder")}} and {{domxref("TextDecoder")}}Create and return a new {{domxref("TextEncoder")}}, or respectively {{domxref("TextDecoder")}}, allowing to encode or decode strings into specific encodings.{{CompatGeckoDesktop(20)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
{{ domxref("URL") }}Workers can use the static methods URL.createObjectURL and URL.revokeObjectURL with {{domxref("Blob")}} objects accesible to the worker.
+ Workers can also create a new URL using the {{domxref("URL.URL", "URL()")}} constructor and call any normal method on the returned object.
{{CompatGeckoDesktop(21)}} and {{CompatGeckoDesktop(26)}} for URL() constructor{{CompatNo}}{{CompatNo}}{{CompatNo}}
WebGL with {{domxref("OffscreenCanvas")}}WebGL (Web Graphics Library) is a JavaScript API for rendering interactive 3D and 2D graphics within any compatible web browser without the use of plug-ins.{{CompatGeckoDesktop(44)}} behind a feature preference setting. In about:config, set gfx.offscreencanvas.enabled to true.{{CompatNo}}{{CompatNo}}{{CompatNo}}
{{domxref("WebSocket")}}Creates and returns a new {{domxref("WebSocket")}}  object; this mimics the behavior of the standard WebSocket() constructor.{{CompatGeckoDesktop(37)}}11.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}
{{domxref("Worker")}}Creates a new {{ domxref("Worker") }}. Yes, workers can spawn more workers.{{CompatGeckoDesktop("1.9.1")}}10.0{{CompatNo}} See crbug.com/31666{{CompatNo}}
{{domxref("WorkerGlobalScope")}}The global scope of workers. This objects defines worker-specific functions.{{CompatVersionUnknown}}10.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}
{{domxref("WorkerLocation")}}The subset of the {{domxref("Location")}} interface available to workers.{{CompatGeckoDesktop(1.9.2)}}10.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}
{{domxref("WorkerNavigator")}}The subset of the {{domxref("Navigator")}} interface available to workers.Basic implementation {{CompatVersionUnknown}}
+ {{domxref("NavigatorID.appCodeName", "appCodeName")}}, {{domxref("NavigatorID.product", "product")}}, {{domxref("NavigatorID.taintEnabled", "taintEnabled()")}}: {{CompatGeckoDesktop(28)}}
+ {{domxref("WorkerNavigator.onLine", "onLine")}}: {{CompatGeckoDesktop(29)}}
+ {{domxref("NavigatorLanguage")}}: {{CompatVersionUnknown}}
{{domxref("NavigatorID.appName", "appName")}}, {{domxref("NavigatorID.appVersion", "appVersion")}}, {{domxref("WorkerNavigator.onLine", "onLine")}}, {{domxref("NavigatorID.platform", "platform")}}, {{domxref("NavigatorID.userAgent", "userAgent")}}: 10.0
+ Other: {{CompatNo}}
{{CompatVersionUnknown}}{{CompatVersionUnknown}}
{{domxref("XMLHttpRequest")}}Creates and returns a new {{domxref("XMLHttpRequest")}}  object; this mimics the behavior of the standard XMLHttpRequest() constructor. Note that the responseXML and channel attributes on XMLHttpRequest always return null. +

Basic: {{CompatGeckoDesktop("1.9.1")}}

+ +

{{domxref("XMLHttpRequest.response", "response")}} and {{domxref("XMLHttpRequest.responseType", "responseType")}} are available since {{CompatGeckoDesktop("10")}}

+ +

{{domxref("XMLHttpRequest.timeout", "timeout")}} and {{domxref("XMLHttpRequest.ontimeout", "ontimeout")}} are available since {{CompatGeckoDesktop("13")}}

+
{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+ +

Consulte também

+ + + +
+ + + + + +
diff --git a/files/pt-pt/web/api/web_workers_api/index.html b/files/pt-pt/web/api/web_workers_api/index.html new file mode 100644 index 0000000000..9c1040b06f --- /dev/null +++ b/files/pt-pt/web/api/web_workers_api/index.html @@ -0,0 +1,234 @@ +--- +title: Web Workers API +slug: Web/API/Web_Workers_API +tags: + - API + - NeedsTranslation + - Service Workers + - Shared Workers + - TopicStub + - Web Workers + - Workers +translation_of: Web/API/Web_Workers_API +--- +

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

+ +

Web Workers makes it possible to run a script operation in background thread separate from the main execution thread of a web application. The advantage of this is that laborious processing can be performed in a separate thread, allowing the main (usually the UI) thread to run without being blocked/slowed down.

+ +

Web Workers concepts and usage

+ +

A worker is an object created using a constructor (e.g. {{domxref("Worker.Worker", "Worker()")}}) that runs a named JavaScript file — this file contains the code that will run in the worker thread; workers run in another global context that is different from the current {{domxref("window")}}. This context is represented by a {{domxref("DedicatedWorkerGlobalScope")}} object in the case of dedicated workers (standard workers that are utilized by a single script; shared workers use {{domxref("SharedWorkerGlobalScope")}}).

+ +

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

+ +

In addition to dedicated workers, there are other types of worker:

+ + + +
+

Note: As per the Web workers Spec, worker error events should not bubble (see {{bug(1188141)}}. This has been implemented in Firefox 42.

+
+ +

Web Worker interfaces

+ +
+
{{domxref("AbstractWorker")}}
+
Abstracts properties and methods common to all kind of workers (i.e. {{domxref("Worker")}} or {{domxref("SharedWorker")}}).
+
{{domxref("Worker")}}
+
Represents a running worker thread, allowing you to pass messages to the running worker code.
+
{{domxref("WorkerLocation")}}
+
Defines the absolute location of the script executed by the Worker.
+
+ +
+
{{domxref("SharedWorker")}}
+
Represents a specific kind of worker that can be accessed from several browsing contexts, being several windows, iframes or even workers.
+
{{domxref("WorkerGlobalScope")}}
+
Represents the generic scope of any worker (doing the same job as {{domxref("Window")}} does for normal web content). Different types of worker have scope objects that inherit from this interface and add more specific features.
+
{{domxref("DedicatedWorkerGlobalScope")}}
+
Represents the scope of a dedicated worker, inheriting from {{domxref("WorkerGlobalScope")}} and adding some dedicated features.
+
{{domxref("SharedWorkerGlobalScope")}}
+
Represents the scope of a shared worker, inheriting from {{domxref("WorkerGlobalScope")}} and adding some dedicated features.
+
{{domxref("WorkerNavigator")}}
+
Represents the identity and state of the user agent (the client):
+
+ +

Examples

+ +

We have created a couple of simple demos to show basic usage:

+ + + +

You can find out more information on how these demos work in Using web workers.

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#workers')}}{{Spec2('HTML WHATWG')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support4{{CompatVersionUnknown}}{{CompatGeckoDesktop(1.9.1)}}10.010.64
Shared workers4{{CompatNo}}{{CompatGeckoDesktop(29)}}{{CompatNo}}10.64
Passing data using structured cloning13{{CompatVersionUnknown}}{{CompatGeckoDesktop(8)}}10.011.56
Passing data using  transferable objects17 {{property_prefix("webkit")}}
+ 21
{{CompatNo}}{{CompatGeckoDesktop(18)}}{{CompatNo}}156
Global {{domxref("window.URL", "URL")}}10[1]
+ 23
{{CompatVersionUnknown}}{{CompatGeckoDesktop(21)}}11156[1]
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support4.44{{CompatVersionUnknown}}{{CompatGeckoMobile(1.9.1)}}1.0.110.011.55.1
Shared workers{{CompatNo}}4{{CompatNo}}291.4{{CompatNo}}{{CompatNo}}{{CompatNo}}
Passing data using structured cloning{{CompatNo}}4{{CompatVersionUnknown}}81.0.1{{CompatNo}}{{CompatNo}}{{CompatNo}}
Passing data using  transferable objects{{CompatNo}}{{CompatNo}}{{CompatNo}}181.0.1{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] As webkitURL.

+ +

See also

+ + diff --git a/files/pt-pt/web/api/web_workers_api/utilizacao_de_web_workers/index.html b/files/pt-pt/web/api/web_workers_api/utilizacao_de_web_workers/index.html new file mode 100644 index 0000000000..d9705559e7 --- /dev/null +++ b/files/pt-pt/web/api/web_workers_api/utilizacao_de_web_workers/index.html @@ -0,0 +1,1091 @@ +--- +title: Utilização de Web Workers +slug: Web/API/Web_Workers_API/Utilizacao_de_web_workers +tags: + - Avançado + - Firefox + - Guía + - JavaScript + - Operadores + - Workers +translation_of: Web/API/Web_Workers_API/Using_web_workers +--- +
+

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 new file mode 100644 index 0000000000..8328c7976f --- /dev/null +++ b/files/pt-pt/web/api/webgl_api/constantes/index.html @@ -0,0 +1,4023 @@ +--- +title: Contantes de WebGL +slug: Web/API/WebGL_API/Constantes +tags: + - API + - Referencia + - WebGL + - constantes +translation_of: Web/API/WebGL_API/Constants +--- +
{{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 new file mode 100644 index 0000000000..8257367513 --- /dev/null +++ b/files/pt-pt/web/api/webgl_api/dados/index.html @@ -0,0 +1,133 @@ +--- +title: Dados em WebGL +slug: Web/API/WebGL_API/Dados +tags: + - 3D + - API de WebGL + - Atributos + - Desenho + - Gráficos 3D + - Guía + - Intermediário + - Uniforms + - Varyings + - WebGL + - graficos +translation_of: Web/API/WebGL_API/Data +--- +
{{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/index.html b/files/pt-pt/web/api/webgl_api/index.html new file mode 100644 index 0000000000..69f79c67f6 --- /dev/null +++ b/files/pt-pt/web/api/webgl_api/index.html @@ -0,0 +1,255 @@ +--- +title: 'API de WebGL: Gráficos 2D e 3D para a Web' +slug: Web/API/WebGL_API +tags: + - 3D + - API de WebGL + - Avançado + - Gráficos 3D + - Multimedia + - Referencia + - Resumo + - Sinopse + - WebGL + - graficos +translation_of: Web/API/WebGL_API +--- +
{{WebGLSidebar}}
+ +
+

WebGL (Biblioteca de Gráficos da Web) é uma API de JavaScript para a renderização de gráficos 2D e 3D interativos dentro de qualquer navegador da Web compatível sem a utilização de plug-ins. WebGL fazi isso, ao introduzir uma API que está em conformidade com o OpenGL ES 2.0 que pode ser utilizado em elementos {{HTMLElement("canvas")}} de HTML5.

+
+ +

O suporte para WebGL está presente no Firefox 4+, Google Chrome 9+, Opera 12+, Safari 5.1+ and Internet Explorer 11+, e Microsoft Edge build 10240+; contudo, o dispositivo do utilizador também deve ter hardware que suporte estas funcionalidades.

+ +

O elemento {{HTMLElement("canvas")}} também é utilizado por Canvas 2D para gráficos 2D nas páginas da Web.

+ +

Referência

+ +

Interfaces padrão

+ +
+ +
+ +

Extensões

+ +
+ +
+ +

Eventos

+ + + +

Constantes e tipos

+ + + +

WebGL 2

+ +

WebGL 2 é uma atualização muito importante para WebGL que é fornecida através da inteface de {{domxref("WebGL2RenderingContext")}}. Esta tem como base o OpenGL ES 3.0 e novas funcionalidades includas:

+ + + +

See also the blog post "WebGL 2 lands in Firefox" and webglsamples.org/WebGL2Samples for a few demos.

+ +

Guias e tutoriais

+ +

Below, you'll find an assortment of guides to help you learn WebGL concepts and tutorials that offer step-by-step lessons and examples.

+ +

Guias

+ +
+
Dados em WebGL
+
A guide to variables, buffers, and other types of data used when writing WebGL code.
+
WebGL best practices
+
Tips and suggestions to help you improve the quality, performance, and reliability of your WebGL content.
+
Using extensions
+
A guide to using WebGL extensions.
+
+ +

Tutoriais

+ +
+
WebGL tutorial
+
A beginner's guide to WebGL core concepts. A good place to start if you don't have previous WebGL experience.
+
+ +

Exemplos

+ +
+
A basic 2D WebGL animation example
+
This example demonstrates the simple animation of a one-color shape. Topics examined are adapting to aspect ratio differences, a function to build shader programs from sets of multiple shaders, and the basics of drawing in WebGL.
+
WebGL by example
+
A series of live samples with short explanations that showcase WebGL concepts and capabilities. The examples are sorted according to topic and level of difficulty, covering the WebGL rendering context, shader programming, textures, geometry, user interaction, and more.
+
+ +

Tutoriais avançados

+ +
+
WebGL model view projection
+
A detailed explanation of the three core matrices that are typically used to represent a 3D object view: the model, view and projection matrices.
+
Matrix math for the web
+
A useful guide to how 3D transform matrices work, and can be used on the web — both for WebGL calculations and in CSS3 transforms.
+
+ +

Recursos

+ + + +

Bibliotecas

+ + + +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('WebGL')}}{{Spec2('WebGL')}}Initial definition. Based on OpenGL ES 2.0
{{SpecName('WebGL2')}}{{Spec2('WebGL2')}}Builds on top of WebGL 1. Based on OpenGL ES 3.0.
{{SpecName('OpenGL ES 2.0')}}{{Spec2('OpenGL ES 2.0')}} 
{{SpecName('OpenGL ES 3.0')}}{{Spec2('OpenGL ES 3.0')}} 
+ +

Compatibilidade de navegador

+ +

WebGL 1

+ +
+ + +

{{Compat("api.WebGLRenderingContext", 0)}}

+ +

WebGL 2

+ + + +

{{Compat("api.WebGL2RenderingContext", 0)}}

+
+ +

Notas de compatibilidade

+ +

In addition to the browser, the GPU itself also needs to support the feature. So, for example, S3 Texture Compression (S3TC) is only available on Tegra-based tablets. Most browsers make the WebGL context available through the webgl context name, but older ones need experimental-webgl as well. In addition, the upcoming WebGL 2 is fully backwards-compatible and will have the context name webgl2.

+ +

Notas do Gecko

+ +

Depuração e teste de WebGL

+ +

Starting with Gecko 10.0 {{geckoRelease("10.0")}}, there are two preferences available which let you control the capabilities of WebGL for testing purposes:

+ +
+
webgl.min_capability_mode
+
A Boolean property that, when true, enables a minimum capability mode. When in this mode, WebGL is configured to only support the bare minimum feature set and capabilities required by the WebGL specification. This lets you ensure that your WebGL code will work on any device or browser, regardless of their capabilities. This is false by default.
+
webgl.disable_extensions
+
A Boolean property that, when true, disables all WebGL extensions. This is false by default.
+
+ +

Consultar também

+ + diff --git a/files/pt-pt/web/api/webgl_api/tipos/index.html b/files/pt-pt/web/api/webgl_api/tipos/index.html new file mode 100644 index 0000000000..a1762958ae --- /dev/null +++ b/files/pt-pt/web/api/webgl_api/tipos/index.html @@ -0,0 +1,242 @@ +--- +title: Tipos de WebGL +slug: Web/API/WebGL_API/Tipos +translation_of: Web/API/WebGL_API/Types +--- +
{{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/utilizar_extens\303\265es/index.html" "b/files/pt-pt/web/api/webgl_api/utilizar_extens\303\265es/index.html" new file mode 100644 index 0000000000..a8bbe535d2 --- /dev/null +++ "b/files/pt-pt/web/api/webgl_api/utilizar_extens\303\265es/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/webglrenderingcontext/index.html b/files/pt-pt/web/api/webglrenderingcontext/index.html new file mode 100644 index 0000000000..7d9b4ef24e --- /dev/null +++ b/files/pt-pt/web/api/webglrenderingcontext/index.html @@ -0,0 +1,444 @@ +--- +title: WebGLRenderingContext +slug: Web/API/WebGLRenderingContext +tags: + - WebGL + - WebGLRenderingContext +translation_of: Web/API/WebGLRenderingContext +--- +
{{APIRef("WebGL")}}
+ +

A interface de WebGLRenderingContext fornece o contexto de renderização de OpenGL ES 2.0 para a superfície de desenho de um elemento {{HTMLElement("canvas")}} de HTML.

+ +

Para obter um objeto desta interface, call {{domxref("HTMLCanvasElement.getContext()", "getContext()")}} num elemento de <canvas>, fornecendo "webgl" como um argumento:

+ +
var canvas = document.getElementById('myCanvas');
+var gl = canvas.getContext('webgl');
+
+ +

Once you have the WebGL rendering context for a canvas, you can render within it.

+ +

The WebGL tutorial has more information, examples, and resources on how to get started with WebGL.

+ +

Constantes

+ +

See the WebGL constants page.

+ +

O contexto de WebGL

+ +

The following properties and methods provide general information and functionality to deal with the WebGL context:

+ +
+
{{domxref("WebGLRenderingContext.canvas")}}
+
A read-only back-reference to the {{domxref("HTMLCanvasElement")}}. Might be {{jsxref("null")}} if it is not associated with a {{HTMLElement("canvas")}} element.
+
{{domxref("WebGLRenderingContext.commit()")}} {{experimental_inline}}
+
+

Pushes frames back to the original {{domxref("HTMLCanvasElement")}}, if the context is not directly fixed to a specific canvas.

+
+
{{domxref("WebGLRenderingContext.drawingBufferWidth")}}
+
The read-only width of the current drawing buffer. Should match the width of the canvas element associated with this context.
+
{{domxref("WebGLRenderingContext.drawingBufferHeight")}}
+
The read-only height of the current drawing buffer. Should match the height of the canvas element associated with this context.
+
{{domxref("WebGLRenderingContext.getContextAttributes()")}}
+
Returns a WebGLContextAttributes object that contains the actual context parameters. Might return {{jsxref("null")}}, if the context is lost.
+
{{domxref("WebGLRenderingContext.isContextLost()")}}
+
Returns true if the context is lost, otherwise returns false.
+
+ +

Visualização e  recorte

+ +
+
{{domxref("WebGLRenderingContext.scissor()")}}
+
Defines the scissor box.
+
{{domxref("WebGLRenderingContext.viewport()")}}
+
Sets the viewport.
+
+ +

Informação de estado

+ +
+
{{domxref("WebGLRenderingContext.activeTexture()")}}
+
Selects the active texture unit.
+
{{domxref("WebGLRenderingContext.blendColor()")}}
+
Sets the source and destination blending factors.
+
{{domxref("WebGLRenderingContext.blendEquation()")}}
+
Sets both the RGB blend equation and alpha blend equation to a single equation.
+
{{domxref("WebGLRenderingContext.blendEquationSeparate()")}}
+
Sets the RGB blend equation and alpha blend equation separately.
+
{{domxref("WebGLRenderingContext.blendFunc()")}}
+
Defines which function is used for blending pixel arithmetic.
+
{{domxref("WebGLRenderingContext.blendFuncSeparate()")}}
+
Defines which function is used for blending pixel arithmetic for RGB and alpha components separately.
+
{{domxref("WebGLRenderingContext.clearColor()")}}
+
Specifies the color values used when clearing color buffers.
+
{{domxref("WebGLRenderingContext.clearDepth()")}}
+
Specifies the depth value used when clearing the depth buffer.
+
{{domxref("WebGLRenderingContext.clearStencil()")}}
+
Specifies the stencil value used when clearing the stencil buffer.
+
{{domxref("WebGLRenderingContext.colorMask()")}}
+
Sets which color components to enable or to disable when drawing or rendering to a {{domxref("WebGLFramebuffer")}}.
+
{{domxref("WebGLRenderingContext.cullFace()")}}
+
Specifies whether or not front- and/or back-facing polygons can be culled.
+
{{domxref("WebGLRenderingContext.depthFunc()")}}
+
Specifies a function that compares incoming pixel depth to the current depth buffer value.
+
{{domxref("WebGLRenderingContext.depthMask()")}}
+
Sets whether writing into the depth buffer is enabled or disabled.
+
{{domxref("WebGLRenderingContext.depthRange()")}}
+
Specifies the depth range mapping from normalized device coordinates to window or viewport coordinates.
+
{{domxref("WebGLRenderingContext.disable()")}}
+
Disables specific WebGL capabilities for this context.
+
{{domxref("WebGLRenderingContext.enable()")}}
+
Enables specific WebGL capabilities for this context.
+
{{domxref("WebGLRenderingContext.frontFace()")}}
+
Specifies whether polygons are front- or back-facing by setting a winding orientation.
+
{{domxref("WebGLRenderingContext.getParameter()")}}
+
Returns a value for the passed parameter name.
+
{{domxref("WebGLRenderingContext.getError()")}}
+
Returns error information.
+
{{domxref("WebGLRenderingContext.hint()")}}
+
Specifies hints for certain behaviors. The interpretation of these hints depend on the implementation.
+
{{domxref("WebGLRenderingContext.isEnabled()")}}
+
Tests whether a specific WebGL capability is enabled or not for this context.
+
{{domxref("WebGLRenderingContext.lineWidth()")}}
+
Sets the line width of rasterized lines.
+
{{domxref("WebGLRenderingContext.pixelStorei()")}}
+
Specifies the pixel storage modes
+
{{domxref("WebGLRenderingContext.polygonOffset()")}}
+
Specifies the scale factors and units to calculate depth values.
+
{{domxref("WebGLRenderingContext.sampleCoverage()")}}
+
Specifies multi-sample coverage parameters for anti-aliasing effects.
+
{{domxref("WebGLRenderingContext.stencilFunc()")}}
+
Sets the both front and back function and reference value for stencil testing.
+
{{domxref("WebGLRenderingContext.stencilFuncSeparate()")}}
+
Sets the front and/or back function and reference value for stencil testing.
+
{{domxref("WebGLRenderingContext.stencilMask()")}}
+
Controls enabling and disabling of both the front and back writing of individual bits in the stencil planes.
+
{{domxref("WebGLRenderingContext.stencilMaskSeparate()")}}
+
Controls enabling and disabling of front and/or back writing of individual bits in the stencil planes.
+
{{domxref("WebGLRenderingContext.stencilOp()")}}
+
Sets both the front and back-facing stencil test actions.
+
{{domxref("WebGLRenderingContext.stencilOpSeparate()")}}
+
Sets the front and/or back-facing stencil test actions.
+
+ +

Buffers

+ +
+
{{domxref("WebGLRenderingContext.bindBuffer()")}}
+
Binds a WebGLBuffer object to a given target.
+
{{domxref("WebGLRenderingContext.bufferData()")}}
+
Updates buffer data.
+
{{domxref("WebGLRenderingContext.bufferSubData()")}}
+
Updates buffer data starting at a passed offset.
+
{{domxref("WebGLRenderingContext.createBuffer()")}}
+
Creates a WebGLBuffer object.
+
{{domxref("WebGLRenderingContext.deleteBuffer()")}}
+
Deletes a WebGLBuffer object.
+
{{domxref("WebGLRenderingContext.getBufferParameter()")}}
+
Returns information about the buffer.
+
{{domxref("WebGLRenderingContext.isBuffer()")}}
+
Returns a Boolean indicating if the passed buffer is valid.
+
+ +

Framebuffers

+ +
+
{{domxref("WebGLRenderingContext.bindFramebuffer()")}}
+
Binds a WebGLFrameBuffer object to a given target.
+
{{domxref("WebGLRenderingContext.checkFramebufferStatus()")}}
+
Returns the status of the framebuffer.
+
{{domxref("WebGLRenderingContext.createFramebuffer()")}}
+
Creates a WebGLFrameBuffer object.
+
{{domxref("WebGLRenderingContext.deleteFramebuffer()")}}
+
Deletes a WebGLFrameBuffer object.
+
{{domxref("WebGLRenderingContext.framebufferRenderbuffer()")}}
+
Attaches a WebGLRenderingBuffer object to a WebGLFrameBuffer object.
+
{{domxref("WebGLRenderingContext.framebufferTexture2D()")}}
+
Attaches a textures image to a WebGLFrameBuffer object.
+
{{domxref("WebGLRenderingContext.getFramebufferAttachmentParameter()")}}
+
Returns information about the framebuffer.
+
{{domxref("WebGLRenderingContext.isFramebuffer()")}}
+
Returns a Boolean indicating if the passed WebGLFrameBuffer object is valid.
+
{{domxref("WebGLRenderingContext.readPixels()")}}
+
Reads a block of pixels from the WebGLFrameBuffer.
+
+ +

Renderbuffers

+ +
+
{{domxref("WebGLRenderingContext.bindRenderbuffer()")}}
+
Binds a WebGLRenderBuffer object to a given target.
+
{{domxref("WebGLRenderingContext.createRenderbuffer()")}}
+
Creates a WebGLRenderBuffer object.
+
{{domxref("WebGLRenderingContext.deleteRenderbuffer()")}}
+
Deletes a WebGLRenderBuffer object.
+
{{domxref("WebGLRenderingContext.getRenderbufferParameter()")}}
+
Returns information about the renderbuffer.
+
{{domxref("WebGLRenderingContext.isRenderbuffer()")}}
+
Returns a Boolean indicating if the passed WebGLRenderingBuffer is valid.
+
{{domxref("WebGLRenderingContext.renderbufferStorage()")}}
+
Creates a renderbuffer data store.
+
+ +

Texturas

+ +
+
{{domxref("WebGLRenderingContext.bindTexture()")}}
+
Binds a WebGLTexture object to a given target.
+
{{domxref("WebGLRenderingContext.compressedTexImage2D()")}}
+
Specifies a 2D texture image in a compressed format.
+
{{domxref("WebGLRenderingContext.compressedTexSubImage2D()")}}
+
Specifies a 2D texture sub-image in a compressed format.
+
{{domxref("WebGLRenderingContext.copyTexImage2D()")}}
+
Copies a 2D texture image.
+
{{domxref("WebGLRenderingContext.copyTexSubImage2D()")}}
+
Copies a 2D texture sub-image.
+
{{domxref("WebGLRenderingContext.createTexture()")}}
+
Creates a WebGLTexture object.
+
{{domxref("WebGLRenderingContext.deleteTexture()")}}
+
Deletes a WebGLTexture object.
+
{{domxref("WebGLRenderingContext.generateMipmap()")}}
+
Generates a set of mipmaps for a WebGLTexture object.
+
{{domxref("WebGLRenderingContext.getTexParameter()")}}
+
Returns information about the texture.
+
{{domxref("WebGLRenderingContext.isTexture()")}}
+
Returns a Boolean indicating if the passed WebGLTexture is valid.
+
{{domxref("WebGLRenderingContext.texImage2D()")}}
+
Specifies a 2D texture image.
+
{{domxref("WebGLRenderingContext.texSubImage2D()")}}
+
Updates a sub-rectangle of the current WebGLTexture.
+
{{domxref("WebGLRenderingContext.texParameter", "WebGLRenderingContext.texParameterf()")}}
+
Sets texture parameters.
+
{{domxref("WebGLRenderingContext.texParameter", "WebGLRenderingContext.texParameteri()")}}
+
Sets texture parameters.
+
+ +

Programas e shaders

+ +
+
{{domxref("WebGLRenderingContext.attachShader()")}}
+
Attaches a WebGLShader to a WebGLProgram.
+
{{domxref("WebGLRenderingContext.bindAttribLocation()")}}
+
Binds a generic vertex index to a named attribute variable.
+
{{domxref("WebGLRenderingContext.compileShader()")}}
+
Compiles a WebGLShader.
+
{{domxref("WebGLRenderingContext.createProgram()")}}
+
Creates a WebGLProgram.
+
{{domxref("WebGLRenderingContext.createShader()")}}
+
Creates a WebGLShader.
+
{{domxref("WebGLRenderingContext.deleteProgram()")}}
+
Deletes a WebGLProgram.
+
{{domxref("WebGLRenderingContext.deleteShader()")}}
+
Deletes a WebGLShader.
+
{{domxref("WebGLRenderingContext.detachShader()")}}
+
Detaches a WebGLShader.
+
{{domxref("WebGLRenderingContext.getAttachedShaders()")}}
+
Returns a list of WebGLShader objects attached to a WebGLProgram.
+
{{domxref("WebGLRenderingContext.getProgramParameter()")}}
+
Returns information about the program.
+
{{domxref("WebGLRenderingContext.getProgramInfoLog()")}}
+
Returns the information log for a WebGLProgram object.
+
{{domxref("WebGLRenderingContext.getShaderParameter()")}}
+
Returns information about the shader.
+
{{domxref("WebGLRenderingContext.getShaderPrecisionFormat()")}}
+
Returns a WebGLShaderPrecisionFormat object describing the precision for the numeric format of the shader.
+
{{domxref("WebGLRenderingContext.getShaderInfoLog()")}}
+
Returns the information log for a WebGLShader object.
+
{{domxref("WebGLRenderingContext.getShaderSource()")}}
+
Returns the source code of a WebGLShader as a string.
+
{{domxref("WebGLRenderingContext.isProgram()")}}
+
Returns a Boolean indicating if the passed WebGLProgram is valid.
+
{{domxref("WebGLRenderingContext.isShader()")}}
+
Returns a Boolean indicating if the passed WebGLShader is valid.
+
{{domxref("WebGLRenderingContext.linkProgram()")}}
+
Links the passed WebGLProgram object.
+
{{domxref("WebGLRenderingContext.shaderSource()")}}
+
Sets the source code in a WebGLShader.
+
{{domxref("WebGLRenderingContext.useProgram()")}}
+
Uses the specified WebGLProgram as part the current rendering state.
+
{{domxref("WebGLRenderingContext.validateProgram()")}}
+
Validates a WebGLProgram.
+
+ +

Uniforms e atributos

+ +
+
{{domxref("WebGLRenderingContext.disableVertexAttribArray()")}}
+
Disables a vertex attribute array at a given position.
+
{{domxref("WebGLRenderingContext.enableVertexAttribArray()")}}
+
Enables a vertex attribute array at a given position.
+
{{domxref("WebGLRenderingContext.getActiveAttrib()")}}
+
Returns information about an active attribute variable.
+
{{domxref("WebGLRenderingContext.getActiveUniform()")}}
+
Returns information about an active uniform variable.
+
{{domxref("WebGLRenderingContext.getAttribLocation()")}}
+
Returns the location of an attribute variable.
+
{{domxref("WebGLRenderingContext.getUniform()")}}
+
Returns the value of a uniform variable at a given location.
+
{{domxref("WebGLRenderingContext.getUniformLocation()")}}
+
Returns the location of a uniform variable.
+
{{domxref("WebGLRenderingContext.getVertexAttrib()")}}
+
Returns information about a vertex attribute at a given position.
+
{{domxref("WebGLRenderingContext.getVertexAttribOffset()")}}
+
Returns the address of a given vertex attribute.
+
{{domxref("WebGLRenderingContext.uniform()", "WebGLRenderingContext.uniform[1234][fi][v]()")}}
+
Specifies a value for a uniform variable.
+
{{domxref("WebGLRenderingContext.uniformMatrix()", "WebGLRenderingContext.uniformMatrix[234]fv()")}}
+
Specifies a matrix value for a uniform variable.
+
{{domxref("WebGLRenderingContext.vertexAttrib()", "WebGLRenderingContext.vertexAttrib[1234]f[v]()")}}
+
Specifies a value for a generic vertex attribute.
+
{{domxref("WebGLRenderingContext.vertexAttribPointer()")}}
+
Specifies the data formats and locations of vertex attributes in a vertex attributes array.
+
+ +

Drawing buffers

+ +
+
{{domxref("WebGLRenderingContext.clear()")}}
+
Clears specified buffers to preset values.
+
{{domxref("WebGLRenderingContext.drawArrays()")}}
+
Renders primitives from array data.
+
{{domxref("WebGLRenderingContext.drawElements()")}}
+
Renders primitives from element array data.
+
{{domxref("WebGLRenderingContext.finish()")}}
+
Blocks execution until all previously called commands are finished.
+
{{domxref("WebGLRenderingContext.flush()")}}
+
Empties different buffer commands, causing all commands to be executed as quickly as possible.
+
+ +

Trabalhar com extensões

+ +

These methods manage WebGL extensions:

+ +
+
{{domxref("WebGLRenderingContext.getSupportedExtensions()")}}
+
Returns an {{jsxref("Array")}} of {{domxref("DOMString")}} elements with all the supported WebGL extensions.
+
{{domxref("WebGLRenderingContext.getExtension()")}}
+
Returns an extension object.
+
+ +

Exemplos

+ +

WebGL context feature detection

+ +

{{page("/en-US/Learn/WebGL/By_example/Detect_WebGL", "summary")}}

+ +

{{page("/en-US/Learn/WebGL/By_example/Detect_WebGL", "detect-webgl-source")}}

+ +

{{EmbedLiveSample("detect-webgl-source", 660,150 ,"" , "Learn/WebGL/By_example/Detect_WebGL")}}

+ +

Effect of canvas size on rendering with WebGL

+ +

{{page("/en-US/Learn/WebGL/By_example/Canvas_size_and_WebGL", "canvas-size-and-webgl-intro")}}

+ +

{{page("/en-US/Learn/WebGL/By_example/Canvas_size_and_WebGL", "canvas-size-and-webgl-source")}}

+ +

{{EmbedLiveSample("canvas-size-and-webgl-source", 660,180 ,"" , "Learn/WebGL/By_example/Canvas_size_and_WebGL")}}

+ +

Especificações

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebGL', "#5.14", "WebGLRenderingContext")}}{{Spec2('WebGL')}}Initial definition
+ +

Compatibilidade de navegador

+ + + +

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

+ +

Consulte também

+ + + +
+ + + + + +
diff --git a/files/pt-pt/web/api/websocket/index.html b/files/pt-pt/web/api/websocket/index.html new file mode 100644 index 0000000000..9820afc0b5 --- /dev/null +++ b/files/pt-pt/web/api/websocket/index.html @@ -0,0 +1,148 @@ +--- +title: WebSocket +slug: Web/API/WebSocket +tags: + - API + - Interface + - WebSocket + - WebSockets +translation_of: Web/API/WebSocket +--- +
{{APIRef("Web Sockets API")}}
+ +

O objeto WebSocket fornece a API para criar e gerir uma ligação WebSocket a um servidor, bem como para enviar e receber dados sobre a ligação.

+ +

Para criar uma WebSocket, use o construtor WebSocket().

+ +

Constructor

+ +
+
{{domxref("WebSocket.WebSocket", "WebSocket(url[, protocols])")}}
+
Devolve um objeto WebSocket acabado de criar.
+
+ +

Constantes

+ + + + + + + + + + + + + + + + + + + + + + + + +
ConstanteValor
WebSocket.CONNECTING0
WebSocket.OPEN1
WebSocket.CLOSING2
WebSocket.CLOSED3
+ +

Propriedades

+ +
+
{{domxref("WebSocket.binaryType")}}
+
O tipo de dados binarios usado pela conexão.
+
{{domxref("WebSocket.bufferedAmount")}} {{readonlyinline}}
+
O numero de bytes de dados em fila.
+
{{domxref("WebSocket.extensions")}} {{readonlyinline}}
+
As extensões selecionadas pelo servidor.
+
{{domxref("WebSocket.onclose")}}
+
Um event listener para ser chamado quando a ligação terminar.
+
{{domxref("WebSocket.onerror")}}
+
Um event listener para ser chamado quando um erro ocorre.
+
{{domxref("WebSocket.onmessage")}}
+
Um event listener para ser chamado quando uma mensagem é recebida do servidor.
+
{{domxref("WebSocket.onopen")}}
+
Um event listener para ser chamado quando a ligação é iniciada.
+
{{domxref("WebSocket.protocol")}} {{readonlyinline}}
+
O sub-protocolo selecionado pelo servidor.
+
{{domxref("WebSocket.readyState")}} {{readonlyinline}}
+
O estado atual da conexão.
+
{{domxref("WebSocket.url")}} {{readonlyinline}}
+
O URL absoluto da WebSocket.
+
+ +

Métodos

+ +
+
{{domxref("WebSocket.close", "WebSocket.close([code[, reason]])")}}
+
Termina a conexão.
+
{{domxref("WebSocket.send", "WebSocket.send(data)")}}
+
Adiciona dados à fila para ser transmitida.
+
+ +

Eventos

+ +

Observe estes eventos usando addEventListener() ou atribuindo um agente de escuta de eventos à propriedade oneventname desta interface.

+ +
+
{{domxref("WebSocket/close_event", "close")}}
+
Lançado quando uma ligação com um WebSocket é fechada.
+ Também disponível através da propriedade {{domxref("WebSocket/onclose", "onclose")}}.
+
{{domxref("WebSocket/error_event", "error")}}
+
Lançado quando uma ligação com um WebSocket foi fechada devido a um erro, como quando alguns dados não puderam ser enviados.
+ Também disponível através da propriedade {{domxref("WebSocket/onerror", "onerror")}}.
+
{{domxref("WebSocket/message_event", "message")}}
+
Lançado quando os dados são recebidos através de um WebSocket.
+ Também disponível através da propriedade {{domxref("WebSocket/onmessage", "onmessage")}}.
+
{{domxref("WebSocket/open_event", "open")}}
+
Lançado quando uma ligação com um WebSocket é aberta.
+ Também disponível através da propriedade {{domxref("WebSocket/onopen", "onopen")}}.
+
+ +

Exemplos

+ +
// Criar ligação WebSocket.
+const socket = new WebSocket('ws://localhost:8080');
+
+// Ligação conectada
+socket.addEventListener('open', function (event) {
+    socket.send('Hello Server!');
+});
+
+// Ficar a ouvir por mensagens
+socket.addEventListener('message', function (event) {
+    console.log('Message from server ', event.data);
+});
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoEstado
{{SpecName("HTML WHATWG", "#network", "WebSocket")}}{{Spec2("HTML WHATWG")}}
+ +

Compatibilidade

+ +
+ + +

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

+
+ +

Ver também

+ + diff --git a/files/pt-pt/web/api/websocket/websocket/index.html b/files/pt-pt/web/api/websocket/websocket/index.html new file mode 100644 index 0000000000..6c7a39f7ac --- /dev/null +++ b/files/pt-pt/web/api/websocket/websocket/index.html @@ -0,0 +1,59 @@ +--- +title: WebSocket() +slug: Web/API/WebSocket/WebSocket +tags: + - API + - Construtor + - Referencia + - Web API + - WebSocket +translation_of: Web/API/WebSocket/WebSocket +--- +

{{APIRef("Web Sockets API")}}

+ +

O construtor WebSocket() devolve um novo objeto de {{domxref("WebSocket")}}.

+ +

Sintaxe

+ +
var aWebSocket = new WebSocket(url [, protocols]);
+ +

Parâmetros

+ +
+
url
+
O URL a qual se conectar; este deve ser o URL a qual o servidor WebSocket responderá.
+
protocols {{optional_inline}}
+
Uma string ou uma matriz de strings que representam protocolos. Estas strings representam sub-protocolos, para que um servidor possa implementar vários sub-protocolos WebSocket (por exemplo, pode querer que um servidor seja capaz de lidar com diferentes tipos de interações dependendo do protocol indicado). Se não é dado um valor ao parâmetro, fica pré-definido como uma string vazia.
+
+ +

Exceções lançadas

+ +
+
SECURITY_ERR
+
A porta a qual a que se está a tentar ligar está bloqueada.
+
SyntaxError
+
O URL é invalido.
+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('HTML WHATWG', '#dom-websocket', 'the WebSocket constructor')}}{{Spec2('HTML WHATWG')}}
+ +

Compatibilidade

+ + + +

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

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" new file mode 100644 index 0000000000..c66e10ceaf --- /dev/null +++ "b/files/pt-pt/web/api/websockets_api/escrever_aplica\303\247\303\243o_cliente_de_websocket/index.html" @@ -0,0 +1,180 @@ +--- +title: Escrever aplicação cliente de WebSocket +slug: Web/API/WebSockets_API/Escrever_aplicação_cliente_de_WebSocket +tags: + - Client + - Exemplo + - Guía + - Networking + - Web Sockets API + - WebSocket + - WebSocket API + - WebSockets +translation_of: Web/API/WebSockets_API/Writing_WebSocket_client_applications +--- +
{{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 new file mode 100644 index 0000000000..7f3b996573 --- /dev/null +++ b/files/pt-pt/web/api/websockets_api/escrever_servidores_de_websocket/index.html @@ -0,0 +1,257 @@ +--- +title: Escrever servidores de WebSocket +slug: Web/API/WebSockets_API/Escrever_servidores_de_WebSocket +tags: + - Guía + - HTML5 + - Tutorial + - WebSocket + - WebSocket API + - WebSockets +translation_of: Web/API/WebSockets_API/Writing_WebSocket_servers +--- +
{{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 new file mode 100644 index 0000000000..a76f81d660 --- /dev/null +++ b/files/pt-pt/web/api/websockets_api/escrever_um_servidor_websocket_em_c/index.html @@ -0,0 +1,441 @@ +--- +title: Escrever um servidor WebSocket em C# +slug: Web/API/WebSockets_API/Escrever_um_servidor_WebSocket_em_C +tags: + - HTML5 + - Tutorial + - WebSockets +translation_of: Web/API/WebSockets_API/Writing_WebSocket_server +--- +

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 new file mode 100644 index 0000000000..4181a1cd37 --- /dev/null +++ b/files/pt-pt/web/api/websockets_api/escrever_um_servidor_websocket_em_java/index.html @@ -0,0 +1,220 @@ +--- +title: Escrever um servidor WebSocket em Java +slug: Web/API/WebSockets_API/Escrever_um_servidor_WebSocket_em_Java +tags: + - HTML5 + - Handshaking + - Tutorial + - WebSockets +translation_of: Web/API/WebSockets_API/Writing_a_WebSocket_server_in_Java +--- +

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/index.html b/files/pt-pt/web/api/websockets_api/index.html new file mode 100644 index 0000000000..5fa4e252e2 --- /dev/null +++ b/files/pt-pt/web/api/websockets_api/index.html @@ -0,0 +1,113 @@ +--- +title: WebSocket API (WebSockets) +slug: Web/API/WebSockets_API +tags: + - API + - Client + - Comunicação + - Servidor + - Sumario + - Two-Way + - WebSocket + - WebSocket API + - WebSockets + - dados + - interativo +translation_of: Web/API/WebSockets_API +--- +

{{DefaultAPISidebar("Websockets API")}}

+ +

A WebSocket API é uma tecnologia que permite abrir uma sessão de comunicação interativa bidirecional entre o navegador do utilizador e um servidor. Com esta API, é possível enviar mensagens para um servidor e receber respostas orientadas por eventos sem ter de sondar o servidor para obter uma resposta.

+ +
+

Nota: Enquanto a conexão WebSocket é funcionalmente semelhante aos sockets de estilo Unix, não são relacionados.

+
+ +

Interfaces

+ +
+
WebSocket
+
A interface principal para fazer conexão a um servidor de WebSocket e depois enviar e receber dados na mesma conexão.
+
CloseEvent
+
O evento enviado pelo objeto WebSocket quando a conexão termina.
+
MessageEvent
+
O evento enviado pelo objeto WebSocket quando uma mensagem é recebida do servidor.
+
+ +

Guias

+ + + +

Ferramentas

+ + + + + + + +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName("HTML WHATWG", "web-sockets.html", "WebSocket API")}}{{Spec2("HTML WHATWG")}}
WebSocketsCandidate Recommendation
{{RFC(6455, "The WebSocket Protocol")}}IETF RFC
+ +

Compatibilidade

+ + + +

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

+ +

Ver também

+ + diff --git a/files/pt-pt/web/api/window/barra_lateral/index.html b/files/pt-pt/web/api/window/barra_lateral/index.html new file mode 100644 index 0000000000..d35750364d --- /dev/null +++ b/files/pt-pt/web/api/window/barra_lateral/index.html @@ -0,0 +1,60 @@ +--- +title: Window.sidebar +slug: Web/API/Window/barra_lateral +tags: + - DOM + - Janela + - Não Padrão + - Propriedade + - Referencia +translation_of: Web/API/Window/sidebar +--- +
{{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/console/index.html b/files/pt-pt/web/api/window/console/index.html new file mode 100644 index 0000000000..80abc2170c --- /dev/null +++ b/files/pt-pt/web/api/window/console/index.html @@ -0,0 +1,56 @@ +--- +title: Window.console +slug: Web/API/Window/console +tags: + - API + - Consola + - Referencia + - Só-de-leitura + - Window + - console +translation_of: Web/API/Window/console +--- +

{{ APIRef }}

+ +

A propriedade só-de-leitura Window.console devolve uma referência para o objeto {{domxref("Console")}}, que fornece métodos para registar informação na console do navegador. Estes métodos são destinados apenas para fins de depuração e não deverão ser invocados para apresentar informação aos utilizadores finais.

+ +

Sintaxe

+ +
var consoleObj = window.console;
+
+ +

Exemplos

+ +

Registar para console

+ +

The first example logs text to the console.

+ +
console.log("An error occurred while loading the content");
+
+ +

The next example logs an object to the console, with the object's fields expandable using disclosure widgets:

+ +
console.dir(someObject);
+ +

See {{SectionOnPage("/en-US/docs/Web/API/Console", "Usage")}} for more thorough examples.

+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('Console API')}}{{Spec2('Console API')}}Initial definition.
+ +
+

Currently there are many implementation differences among browsers, but work is being done to bring them together and make them more consistent with one another.

+
diff --git a/files/pt-pt/web/api/window/index.html b/files/pt-pt/web/api/window/index.html new file mode 100644 index 0000000000..338f4980f1 --- /dev/null +++ b/files/pt-pt/web/api/window/index.html @@ -0,0 +1,479 @@ +--- +title: Window +slug: Web/API/Window +tags: + - API + - DOM + - Interface + - JavaScript + - NeedsTranslation + - Reference + - TopicStub + - Window +translation_of: Web/API/Window +--- +

{{APIRef}}

+ +

O objeto window representa uma janela contendo um documento DOM; a propriedade document aponta para o documento DOM carregado nessa janela. Uma janela para um determinado documento pode ser obtida utilizando a propriedade {{Domxref("document.defaultView")}}.

+ +

This section provides a brief reference for all of the methods, properties, and events available through the DOM window object. The window object implements the Window interface, which in turn inherits from the AbstractView interface. Some additional global functions, namespaces, objects, interfaces, and constructors, not typically associated with the window, but available on it, are listed in the JavaScript Reference and DOM Reference.

+ +

In a tabbed browser, such as Firefox, each tab contains its own window object (and if you're writing an extension, the browser window itself is a separate window too - see Working with windows in chrome code for more information). That is, the window object is not shared between tabs in the same window. Some methods, namely {{Domxref("window.resizeTo")}} and {{Domxref("window.resizeBy")}} apply to the whole window and not to the specific tab the window object belongs to. Generally, anything that can't reasonably pertain to a tab pertains to the window instead.

+ +

{{InheritanceDiagram}}

+ +

Propriedades

+ +

This interface inherits properties from the {{domxref("EventTarget")}} interface and implements properties from the {{domxref("WindowOrWorkerGlobalScope")}} and {{domxref("WindowEventHandlers")}} mixins.

+ +

Note that properties which are objects (e.g.,. for overriding the prototype of built-in elements) are listed in a separate section below.

+ +
+
{{domxref("Window.closed")}} {{Non-standard_inline}}{{readOnlyInline}}
+
This property indicates whether the current window is closed or not.
+
{{domxref("Window.console")}} {{ReadOnlyInline}}
+
Returns a reference to the console object which provides access to the browser's debugging console.
+
{{domxref("Window.content")}} and Window._content {{Non-standard_inline}} {{obsolete_inline}}{{ReadOnlyInline}}
+
Returns a reference to the content element in the current window. Since Firefox 57 (initially Nightly-only), both versions are only available from chrome (privileged) code, and not available to the web anymore.
+
{{domxref("Window.controllers")}}{{non-standard_inline}}{{ReadOnlyInline}}
+
Returns the XUL controller objects for the current chrome window.
+
{{domxref("Window.crypto")}} {{readOnlyInline}}
+
Returns the browser crypto object.
+
{{domxref("Window.defaultStatus")}} {{Obsolete_inline("gecko23")}}
+
Gets/sets the status bar text for the given window.
+
{{domxref("Window.devicePixelRatio")}} {{non-standard_inline}}{{ReadOnlyInline}}
+
Returns the ratio between physical pixels and device independent pixels in the current display.
+
{{domxref("Window.dialogArguments")}} {{Fx_minversion_inline(3)}} {{ReadOnlyInline}}
+
Gets the arguments passed to the window (if it's a dialog box) at the time {{domxref("window.showModalDialog()")}} was called. This is an {{Interface("nsIArray")}}.
+
{{domxref("Window.directories")}} {{obsolete_inline}}
+
Synonym of {{domxref("window.personalbar")}}
+
{{domxref("Window.document")}} {{ReadOnlyInline}}
+
Returns a reference to the document that the window contains.
+
{{domxref("Window.frameElement")}} {{readOnlyInline}}
+
Returns the element in which the window is embedded, or null if the window is not embedded.
+
{{domxref("Window.frames")}} {{readOnlyInline}}
+
Returns an array of the subframes in the current window.
+
{{domxref("Window.fullScreen")}} {{gecko_minversion_inline("1.9")}}
+
This property indicates whether the window is displayed in full screen or not.
+
{{domxref("Window.globalStorage")}} {{gecko_minversion_inline("1.8.1")}} {{Non-standard_inline}} {{Obsolete_inline("gecko13")}}
+
Unsupported since Gecko 13 (Firefox 13). Use {{domxref("Window.localStorage")}} instead.
+ Was: Multiple storage objects that are used for storing data across multiple pages.
+
{{domxref("Window.history")}} {{ReadOnlyInline}}
+
Returns a reference to the history object.
+
{{domxref("Window.innerHeight")}} {{readOnlyInline}}
+
Gets the height of the content area of the browser window including, if rendered, the horizontal scrollbar.
+
{{domxref("Window.innerWidth")}} {{readOnlyInline}}
+
Gets the width of the content area of the browser window including, if rendered, the vertical scrollbar.
+
{{domxref("Window.isSecureContext")}} {{readOnlyInline}}
+
Indicates whether a context is capable of using features that require secure contexts.
+
{{domxref("Window.length")}} {{readOnlyInline}}
+
Returns the number of frames in the window. See also {{domxref("window.frames")}}.
+
{{domxref("Window.location")}}
+
Gets/sets the location, or current URL, of the window object.
+
{{domxref("Window.locationbar")}} {{ReadOnlyInline}}
+
Returns the locationbar object, whose visibility can be toggled in the window.
+
{{domxref("Window.localStorage")}} {{readOnlyInline}}{{gecko_minversion_inline("1.9.1")}}
+
Returns a reference to the local storage object used to store data that may only be accessed by the origin that created it.
+
{{domxref("Window.menubar")}} {{ReadOnlyInline}}
+
Returns the menubar object, whose visibility can be toggled in the window.
+
{{domxref("Window.messageManager")}} {{gecko_minversion_inline("2.0")}}
+
Returns the message manager object for this window.
+
{{domxref("Window.mozAnimationStartTime")}} {{ReadOnlyInline}}{{gecko_minversion_inline("2.0")}} {{Deprecated_inline}}
+
The time in milliseconds since epoch at which the current animation cycle began.
+
{{domxref("Window.mozInnerScreenX")}} {{ReadOnlyInline}}{{non-standard_inline}}{{gecko_minversion_inline("1.9.2")}}
+
Returns the horizontal (X) coordinate of the top-left corner of the window's viewport, in screen coordinates. This value is reported in CSS pixels. See mozScreenPixelsPerCSSPixel in {{interface("nsIDOMWindowUtils")}} for a conversion factor to adapt to screen pixels if needed.
+
{{domxref("Window.mozInnerScreenY")}} {{ReadOnlyInline}} {{non-standard_inline}}{{gecko_minversion_inline("1.9.2")}}
+
Returns the vertical (Y) coordinate of the top-left corner of the window's viewport, in screen coordinates. This value is reported in CSS pixels. See mozScreenPixelsPerCSSPixel for a conversion factor to adapt to screen pixels if needed.
+
{{domxref("Window.mozPaintCount")}} {{non-standard_inline}}{{ReadOnlyInline}} {{gecko_minversion_inline("2.0")}}
+
Returns the number of times the current document has been rendered to the screen in this window. This can be used to compute rendering performance.
+
{{domxref("Window.name")}}
+
Gets/sets the name of the window.
+
{{domxref("Window.navigator")}} {{readOnlyInline}}
+
Returns a reference to the navigator object.
+
{{domxref("Window.opener")}}
+
Returns a reference to the window that opened this current window.
+
{{domxref("Window.orientation")}}{{non-standard_inline}}{{deprecated_inline}}{{readOnlyInline}}
+
Returns the orientation in degrees (in 90 degree increments) of the viewport relative to the device's natural orientation.
+
{{domxref("Window.outerHeight")}} {{readOnlyInline}}
+
Gets the height of the outside of the browser window.
+
{{domxref("Window.outerWidth")}} {{readOnlyInline}}
+
Gets the width of the outside of the browser window.
+
{{domxref("Window.scrollX","Window.pageXOffset")}} {{readOnlyInline}}
+
An alias for {{domxref("window.scrollX")}}.
+
{{domxref("Window.scrollY","Window.pageYOffset")}}{{readOnlyInline}}
+
An alias for {{domxref("window.scrollY")}}
+
{{domxref("Window.sessionStorage")}} {{readOnlyInline}}
+
Returns a reference to the session storage object used to store data that may only be accessed by the origin that created it.
+
{{domxref("Window.StaticRange")}} {{experimental_inline}} {{readonlyinline}}
+
Returns a {{domxref('StaticRange.StaticRange','StaticRange()')}} constructor which creates a {{domxref('StaticRange')}} object.
+
{{domxref("Window.parent")}} {{readOnlyInline}}
+
Returns a reference to the parent of the current window or subframe.
+
{{domxref("Window.performance")}} {{readOnlyInline}}
+
Returns a {{domxref("Performance")}} object, which includes the {{domxref("Performance.timing", "timing")}} and {{domxref("Performance.navigation", "navigation")}} attributes, each of which is an object providing performance-related data. See also Using Navigation Timing for additional information and examples.
+
{{domxref("Window.personalbar")}} {{readOnlyInline}}
+
Returns the personalbar object, whose visibility can be toggled in the window.
+
{{domxref("Window.pkcs11")}} {{obsolete_inline(29)}}
+
Formerly provided access to install and remove PKCS11 modules.
+
{{domxref("Window.returnValue")}} {{Fx_minversion_inline(3)}}
+
The return value to be returned to the function that called {{domxref("window.showModalDialog()")}} to display the window as a modal dialog.
+
{{domxref("Window.screen")}} {{readOnlyInline}}
+
Returns a reference to the screen object associated with the window.
+ +
{{domxref("Window.screenX")}} {{readOnlyInline}}
+
Returns the horizontal distance of the left border of the user's browser from the left side of the screen.
+
{{domxref("Window.screenY")}} {{readOnlyInline}}
+
Returns the vertical distance of the top border of the user's browser from the top side of the screen.
+
{{domxref("Window.scrollbars")}} {{readOnlyInline}}
+
Returns the scrollbars object, whose visibility can be toggled in the window.
+
{{domxref("Window.scrollMaxX")}}{{non-standard_inline}}{{ReadOnlyInline}}
+
The maximum offset that the window can be scrolled to horizontally, that is the document width minus the viewport width.
+
{{domxref("Window.scrollMaxY")}}{{non-standard_inline}}{{ReadOnlyInline}}
+
The maximum offset that the window can be scrolled to vertically (i.e., the document height minus the viewport height).
+
{{domxref("Window.scrollX")}} {{readOnlyInline}}
+
Returns the number of pixels that the document has already been scrolled horizontally.
+
{{domxref("Window.scrollY")}} {{readOnlyInline}}
+
Returns the number of pixels that the document has already been scrolled vertically.
+
{{domxref("Window.self")}} {{ReadOnlyInline}}
+
Returns an object reference to the window object itself.
+
{{domxref("Window.sessionStorage")}} {{Fx_minversion_inline("2.0")}}
+
Returns a storage object for storing data within a single page session.
+
{{domxref("Window.sidebar")}} {{non-standard_inline}}{{ReadOnlyInline}}
+
Returns a reference to the window object of the sidebar.
+
{{domxref("Window.speechSynthesis")}} {{ReadOnlyInline}}
+
Returns a {{domxref("SpeechSynthesis")}} object, which is the entry point into using Web Speech API speech synthesis functionality.
+
{{domxref("Window.status")}}
+
Gets/sets the text in the statusbar at the bottom of the browser.
+
{{domxref("Window.statusbar")}} {{readOnlyInline}}
+
Returns the statusbar object, whose visibility can be toggled in the window.
+
{{domxref("Window.toolbar")}} {{readOnlyInline}}
+
Returns the toolbar object, whose visibility can be toggled in the window.
+
{{domxref("Window.top")}} {{readOnlyInline}}
+
Returns a reference to the topmost window in the window hierarchy. This property is read only.
+
{{domxref("Window.visualViewport")}} {{readOnlyInline}}
+
Returns a {{domxref("VisualViewport")}} object which represents the visual viewport for a given window.
+
{{domxref("Window.window")}} {{ReadOnlyInline}}
+
Returns a reference to the current window.
+
window[0], window[1], etc.
+
Returns a reference to the window object in the frames. See {{domxref("Window.frames")}} for more details.
+
+ +

Properties implemented from elsewhere

+ +
+
{{domxref("WindowOrWorkerGlobalScope.caches")}} {{readOnlyinline}}
+
Returns the {{domxref("CacheStorage")}} object associated with the current context. This object enables functionality such as storing assets for offline use, and generating custom responses to requests.
+
{{domxref("WindowOrWorkerGlobalScope.indexedDB")}} {{readonlyInline}}
+
Provides a mechanism for applications to asynchronously access capabilities of indexed databases; returns an {{domxref("IDBFactory")}} object.
+
{{domxref("WindowOrWorkerGlobalScope.isSecureContext")}} {{readOnlyinline}}
+
Returns a boolean indicating whether the current context is secure (true) or not (false).
+
{{domxref("WindowOrWorkerGlobalScope.origin")}} {{readOnlyinline}}
+
Returns the global object's origin, serialized as a string. (This does not yet appear to be implemented in any browser.)
+
+ +

Métodos

+ +

This interface inherits methods from the {{domxref("EventTarget")}} interface and implements methods from {{domxref("WindowOrWorkerGlobalScope")}} and {{domxref("EventTarget")}}.

+ +
+
{{domxref("Window.alert()")}}
+
Displays an alert dialog.
+ +
{{domxref("Window.back()")}} {{Non-standard_inline}} {{obsolete_inline}}
+
Moves back one in the window history.
+
{{domxref("Window.blur()")}}
+
Sets focus away from the window.
+
{{domxref("Window.cancelAnimationFrame()")}} {{experimental_inline}}
+
Enables you to cancel a callback previously scheduled with {{domxref("Window.requestAnimationFrame")}}.
+
{{domxref("Window.cancelIdleCallback()")}} {{experimental_inline}}
+
Enables you to cancel a callback previously scheduled with {{domxref("Window.requestIdleCallback")}}.
+
{{domxref("Window.captureEvents()")}} {{Deprecated_inline}}
+
Registers the window to capture all events of the specified type.
+
{{domxref("Window.clearImmediate()")}}
+
Cancels the repeated execution set using setImmediate.
+
{{domxref("Window.close()")}}
+
Closes the current window.
+
{{domxref("Window.confirm()")}}
+
Displays a dialog with a message that the user needs to respond to.
+
{{domxref("Window.disableExternalCapture()")}} {{obsolete_inline(24)}}
+
{{todo("NeedsContents")}}
+
{{domxref("Window.dispatchEvent()")}}
+
Used to trigger an event.
+
{{domxref("Window.dump()")}} {{Non-standard_inline}}
+
Writes a message to the console.
+
{{domxref("Window.enableExternalCapture()")}} {{obsolete_inline(24)}}
+
{{todo("NeedsContents")}}
+
{{domxref("Window.find()")}}
+
Searches for a given string in a window.
+
{{domxref("Window.focus()")}}
+
Sets focus on the current window.
+
{{domxref("Window.forward()")}} {{Non-standard_inline}} {{obsolete_inline}}
+
Moves the window one document forward in the history.
+
{{domxref("Window.getAttention()")}} {{Non-standard_inline}} {{obsolete_inline}}
+
Flashes the application icon.
+
{{domxref("Window.getAttentionWithCycleCount()")}}
+
{{todo("NeedsContents")}}
+
{{domxref("Window.getComputedStyle()")}}
+
Gets computed style for the specified element. Computed style indicates the computed values of all CSS properties of the element.
+
{{domxref("Window.getDefaultComputedStyle()")}} {{Non-standard_inline}}
+
Gets default computed style for the specified element, ignoring author stylesheets.
+
{{domxref("Window.getSelection()")}}
+
Returns the selection object representing the selected item(s).
+
{{domxref("Window.home()")}} {{Non-standard_inline}} {{obsolete_inline}}
+
Returns the browser to the home page.
+
{{domxref("Window.matchMedia()")}} {{gecko_minversion_inline("6.0")}}
+
Returns a {{domxref("MediaQueryList")}} object representing the specified media query string.
+
{{domxref("Window.maximize()")}}
+
{{todo("NeedsContents")}}
+
{{domxref("Window.minimize()")}} (top-level XUL windows only)
+
Minimizes the window.
+
{{domxref("Window.moveBy()")}}
+
Moves the current window by a specified amount.
+
{{domxref("Window.moveTo()")}}
+
Moves the window to the specified coordinates.
+
{{domxref("Window.open()")}}
+
Opens a new window.
+
{{domxref("Window.openDialog()")}} {{Non-standard_inline}} {{obsolete_inline}}
+
Opens a new dialog window.
+
{{domxref("Window.postMessage()")}} {{Fx_minversion_inline(3)}}
+
Provides a secure means for one window to send a string of data to another window, which need not be within the same domain as the first.
+
{{domxref("Window.print()")}}
+
Opens the Print Dialog to print the current document.
+
{{domxref("Window.prompt()")}}
+
Returns the text entered by the user in a prompt dialog.
+
{{domxref("Window.releaseEvents()")}} {{Non-standard_inline}} {{Deprecated_inline}}
+
Releases the window from trapping events of a specific type.
+
{{domxref("Window.requestAnimationFrame()")}} {{gecko_minversion_inline("2.0")}}
+
Tells the browser that an animation is in progress, requesting that the browser schedule a repaint of the window for the next animation frame.
+
{{domxref("Window.requestIdleCallback()")}}  {{experimental_inline}}
+
Enables the scheduling of tasks during a browser's idle periods.
+
{{domxref("Window.resizeBy()")}}
+
Resizes the current window by a certain amount.
+
{{domxref("Window.resizeTo()")}}
+
Dynamically resizes window.
+
{{domxref("Window.restore()")}} {{Non-standard_inline}} {{obsolete_inline}}
+
{{todo("NeedsContents")}}
+
{{domxref("Window.routeEvent()")}} {{obsolete_inline(24)}}
+
{{todo("NeedsContents")}}
+
{{domxref("Window.scroll()")}}
+
Scrolls the window to a particular place in the document.
+
{{domxref("Window.scrollBy()")}}
+
Scrolls the document in the window by the given amount.
+
{{domxref("Window.scrollByLines()")}} {{Non-standard_inline}}
+
Scrolls the document by the given number of lines.
+
{{domxref("Window.scrollByPages()")}} {{Non-standard_inline}}
+
Scrolls the current document by the specified number of pages.
+
{{domxref("Window.scrollTo()")}}
+
Scrolls to a particular set of coordinates in the document.
+
{{domxref("Window.setCursor()")}} {{Non-standard_inline}} (top-level XUL windows only)
+
Changes the cursor for the current window
+
{{domxref("Window.setImmediate()")}}
+
Executes a function after the browser has finished other heavy tasks
+
{{domxref("Window.setResizable()")}} {{Non-standard_inline}}
+
Toggles a user's ability to resize a window.
+
{{domxref("Window.sizeToContent()")}} {{Non-standard_inline}}
+
Sizes the window according to its content.
+
{{domxref("Window.stop()")}}
+
This method stops window loading.
+
{{domxref("Window.updateCommands()")}} {{Non-standard_inline}}
+
Updates the state of commands of the current chrome window (UI).
+
+ +

Methods implemented from elsewhere

+ +
+
{{domxref("EventTarget.addEventListener()")}}
+
Register an event handler to a specific event type on the window.
+
{{domxref("WindowOrWorkerGlobalScope.atob()")}}
+
Decodes a string of data which has been encoded using base-64 encoding.
+
{{domxref("WindowOrWorkerGlobalScope.btoa()")}}
+
Creates a base-64 encoded ASCII string from a string of binary data.
+
{{domxref("WindowOrWorkerGlobalScope.clearInterval()")}}
+
Cancels the repeated execution set using {{domxref("WindowOrWorkerGlobalScope.setInterval()")}}.
+
{{domxref("WindowOrWorkerGlobalScope.clearTimeout()")}}
+
Cancels the delayed execution set using {{domxref("WindowOrWorkerGlobalScope.setTimeout()")}}.
+
{{domxref("WindowOrWorkerGlobalScope.createImageBitmap()")}}
+
Accepts a variety of different image sources, and returns a {{domxref("Promise")}} which resolves to an {{domxref("ImageBitmap")}}. Optionally the source is cropped to the rectangle of pixels originating at (sx, sy) with width sw, and height sh.
+
{{domxref("WindowOrWorkerGlobalScope.fetch()")}}
+
Starts the process of fetching a resource from the network.
+
{{domxref("EventTarget.removeEventListener")}}
+
Removes an event listener from the window.
+
{{domxref("WindowOrWorkerGlobalScope.setInterval()")}}
+
Schedules a function to execute every time a given number of milliseconds elapses.
+
{{domxref("WindowOrWorkerGlobalScope.setTimeout()")}}
+
Schedules a function to execute in a given amount of time.
+
+ +

Métodos obsoletos

+ +
+
{{domxref("Window.showModalDialog()")}} {{obsolete_inline}}
+
Displays a modal dialog. This method was removed completely in Chrome 43, and Firefox 55.
+
+ +

Manipuladores de evento

+ +

These are properties of the window object that can be set to establish event handlers for the various things that can happen in the window that might be of interest.

+ +

This interface inherits event handlers from the {{domxref("EventTarget")}} interface and implements event handlers from {{domxref("WindowEventHandlers")}}.

+ +
+

Nota: Starting in {{Gecko("9.0")}}, you can now use the syntax if ("onabort" in window) to determine whether or not a given event handler property exists. This is because event handler interfaces have been updated to be proper web IDL interfaces. See DOM event handlers for details.

+
+ +
+
{{domxref("GlobalEventHandlers.onabort")}}
+
Called when the loading of a resource has been aborted, such as by a user canceling the load while it is still in progress
+
{{domxref("WindowEventHandlers.onafterprint")}}
+
Called when the print dialog box is closed. See {{event("afterprint")}} event.
+
{{domxref("WindowEventHandlers.onbeforeprint")}}
+
Called when the print dialog box is opened. See {{event("beforeprint")}} event.
+
{{domxref("Window.onbeforeinstallprompt")}}
+
An event handler property dispatched before a user is prompted to save a web site to a home screen on mobile.
+
{{domxref("WindowEventHandlers.onbeforeunload")}}
+
An event handler property for before-unload events on the window.
+
{{domxref("GlobalEventHandlers.onblur")}}
+
Called after the window loses focus, such as due to a popup.
+
{{domxref("GlobalEventHandlers.onchange")}}
+
An event handler property for change events on the window.
+
{{domxref("GlobalEventHandlers.onclick")}}
+
Called after the ANY mouse button is pressed & released
+
{{domxref("GlobalEventHandlers.ondblclick")}}
+
Called when a double click is made with ANY mouse button.
+
{{domxref("GlobalEventHandlers.onclose")}}
+
Called after the window is closed
+
{{domxref("GlobalEventHandlers.oncontextmenu")}}
+
Called when the RIGHT mouse button is pressed
+
{{domxref("Window.ondevicelight")}}
+
An event handler property for any ambient light levels changes
+
{{domxref("Window.ondevicemotion")}} {{gecko_minversion_inline("6.0")}}
+
Called if accelerometer detects a change (For mobile devices)
+
{{domxref("Window.ondeviceorientation")}} {{gecko_minversion_inline("6.0")}}
+
Called when the orientation is changed (For mobile devices)
+
{{domxref("Window.ondeviceorientationabsolute")}} {{non-standard_inline}} Chrome only
+
An event handler property for any device orientation changes.
+
{{domxref("Window.ondeviceproximity")}}
+
An event handler property for device proximity event
+
{{domxref("GlobalEventHandlers.onerror")}}
+
Called when a resource fails to load OR when an error occurs at runtime. See {{event("error")}} event.
+
{{domxref("GlobalEventHandlers.onfocus")}}
+
Called after the window receives or regains focus. See {{event("focus")}} events.
+
{{domxref("WindowEventHandlers.onhashchange")}} {{gecko_minversion_inline("1.9.2")}}
+
An event handler property for {{event('hashchange')}} events on the window; called when the part of the URL after the hash mark ("#") changes.
+
{{domxref("Window.onappinstalled")}}
+
Called when the page is installed as a webapp. See {{event('appinstalled')}} event.
+
{{domxref("Window.ongamepadconnected")}}
+
Represents an event handler that will run when a gamepad is connected (when the {{event('gamepadconnected')}} event fires).
+
{{domxref("Window.ongamepaddisconnected")}}
+
Represents an event handler that will run when a gamepad is disconnected (when the {{event('gamepaddisconnected')}} event fires).
+
{{domxref("Window.oninput")}}
+
Called when the value of an <input> element changes
+
{{domxref("GlobalEventHandlers.onkeydown")}}
+
Called when you begin pressing ANY key. See {{event("keydown")}} event.
+
{{domxref("GlobalEventHandlers.onkeypress")}}
+
Called when a key (except Shift, Fn, and CapsLock) is in pressed position. See {{event("keypress")}} event.
+
{{domxref("GlobalEventHandlers.onkeyup")}}
+
Called when you finish releasing ANY key. See {{event("keyup")}} event.
+
{{domxref("WindowEventHandlers.onlanguagechange")}}
+
An event handler property for {{event("languagechange")}} events on the window.
+
{{domxref("GlobalEventHandlers.onload")}}
+
Called after all resources and the DOM are fully loaded. WILL NOT get called when the page is loaded from cache, such as with back button.
+
{{domxref("WindowEventHandlers.onmessage")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("message")}} event is raised.
+
{{domxref("GlobalEventHandlers.onmousedown")}}
+
Called when ANY mouse button is pressed.
+
{{domxref("GlobalEventHandlers.onmousemove")}}
+
Called continously when the mouse is moved inside the window.
+
{{domxref("GlobalEventHandlers.onmouseout")}}
+
Called when the pointer leaves the window.
+
{{domxref("GlobalEventHandlers.onmouseover")}}
+
Called when the pointer enters the window
+
{{domxref("GlobalEventHandlers.onmouseup")}}
+
Called when ANY mouse button is released
+
{{domxref("Window.onmozbeforepaint")}} {{gecko_minversion_inline("2.0")}}
+
An event handler property for the MozBeforePaint event, which is sent before repainting the window if the event has been requested by a call to the {{domxref("Window.mozRequestAnimationFrame()")}} method.
+
{{domxref("WindowEventHandlers.onoffline")}}
+
Called when network connection is lost. See {{event("offline")}} event.
+
{{domxref("WindowEventHandlers.ononline")}}
+
Called when network connection is established. See {{event("online")}} event.
+
{{domxref("WindowEventHandlers.onpagehide")}}
+
Called when the user navigates away from the page, before the onunload event. See {{event("pagehide")}} event.
+
{{domxref("WindowEventHandlers.onpageshow")}}
+
Called after all resources and the DOM are fully loaded. See {{event("pageshow")}} event.
+
{{domxref("Window.onpaint")}}
+
An event handler property for paint events on the window.
+
{{domxref("WindowEventHandlers.onpopstate")}} {{gecko_minversion_inline("2.0")}}
+
Called when a back button is pressed.
+
{{domxref("Window.onrejectionhandled")}} {{experimental_inline}}
+
An event handler for handled {{jsxref("Promise")}} rejection events.
+
{{domxref("GlobalEventHandlers.onreset")}}
+
Called when a form is reset
+
{{domxref("GlobalEventHandlers.onresize")}}
+
Called continuously as you are resizing the window.
+
{{domxref("GlobalEventHandlers.onscroll")}}
+
Called when the scroll bar is moved via ANY means. If the resource fully fits in the window, then this event cannot be invoked
+
{{domxref("GlobalEventHandlers.onwheel")}}
+
Called when the mouse wheel is rotated around any axis
+
{{domxref("GlobalEventHandlers.onselect")}}
+
Called after text in an input field is selected
+
{{domxref("GlobalEventHandlers.onselectionchange")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("selectionchange")}} event is raised.
+
{{domxref("WindowEventHandlers.onstorage")}}
+
Called when there is a change in session storage or local storage. See {{event("storage")}} event
+
{{domxref("GlobalEventHandlers.onsubmit")}}
+
Called when a form is submitted
+
{{domxref("WindowEventHandlers.onunhandledrejection")}} {{experimental_inline}}
+
An event handler for unhandled {{jsxref("Promise")}} rejection events.
+
{{domxref("WindowEventHandlers.onunload")}}
+
Called when the user navigates away from the page.
+
{{domxref("Window.onuserproximity")}}
+
An event handler property for user proximity events.
+
{{domxref("Window.onvrdisplayconnect")}}
+
Represents an event handler that will run when a compatible VR device has been connected to the computer (when the {{event("vrdisplayconnected")}} event fires).
+
{{domxref("Window.onvrdisplaydisconnect")}}
+
Represents an event handler that will run when a compatible VR device has been disconnected from the computer (when the {{event("vrdisplaydisconnected")}} event fires).
+
{{domxref("Window.onvrdisplayactivate")}}
+
Represents an event handler that will run when a display is able to be presented to (when the {{event("vrdisplayactivate")}} event fires), for example if an HMD has been moved to bring it out of standby, or woken up by being put on.
+
{{domxref("Window.onvrdisplaydeactivate")}}
+
Represents an event handler that will run when a display can no longer be presented to (when the {{event("vrdisplaydeactivate")}} event fires), for example if an HMD has gone into standby or sleep mode due to a period of inactivity.
+
{{domxref("Window.onvrdisplayblur")}}
+
Represents an event handler that will run when presentation to a display has been paused for some reason by the browser, OS, or VR hardware (when the {{event("vrdisplayblur")}} event fires) — for example, while the user is interacting with a system menu or browser, to prevent tracking or loss of experience.
+
{{domxref("Window.onvrdisplayfocus")}}
+
Represents an event handler that will run when presentation to a display has resumed after being blurred (when the {{event("vrdisplayfocus")}} event fires).
+
{{domxref("Window.onvrdisplaypresentchange")}}
+
represents an event handler that will run when the presenting state of a VR device changes — i.e. goes from presenting to not presenting, or vice versa (when the {{event("vrdisplaypresentchange")}} event fires).
+
+ +

Construtores

+ +

Consulte também as Interfaces de DOM.

+ +
+
{{domxref("DOMParser")}}
+
DOMParser can parse XML or HTML source stored in a string into a DOM DocumentDOMParser is specified in DOM Parsing and Serialization.
+
{{domxref("Window.GeckoActiveXObject")}}
+
{{todo("NeedsContents")}}
+
{{domxref("Image")}}
+
Used for creating an {{domxref("HTMLImageElement")}}.
+
{{domxref("Option")}}
+
Used for creating an {{domxref("HTMLOptionElement")}}
+
{{domxref("Window.QueryInterface")}}
+
{{todo("NeedsContents")}}
+
{{domxref("Window.XMLSerializer")}}
+
{{todo("NeedsContents")}}
+
{{domxref("Worker")}}
+
Used for creating a Web worker
+
{{domxref("Window.XPCNativeWrapper")}}
+
{{todo("NeedsContents")}}
+
{{domxref("Window.XPCSafeJSObjectWrapper")}}
+
{{todo("NeedsContents")}}
+
+ +

Interfaces

+ +

Consulte Referência de DOM

+ +

Consulte também

+ + diff --git a/files/pt-pt/web/api/window/open/index.html b/files/pt-pt/web/api/window/open/index.html new file mode 100644 index 0000000000..bb64902182 --- /dev/null +++ b/files/pt-pt/web/api/window/open/index.html @@ -0,0 +1,748 @@ +--- +title: Window.open() +slug: Web/API/Window/open +tags: + - API + - DOM + - Janela + - Referencia + - abrir + - metodo +translation_of: Web/API/Window/open +--- +
{{APIRef}}
+ +

The {{domxref("Window")}} interface's open() method loads the specified resource into the browsing context (window, {{HTMLElement("iframe")}} or tab) with the specified name. If the name doesn't exist, then a new window is opened and the specified resource is loaded into its browsing context.

+ +

Sintaxe

+ +
var window = window.open(url, windowName, [windowFeatures]);
+ +

Parâmetros

+ +
+
url
+
A {{domxref("DOMString")}} indicating the URL of the resource to be loaded. This can be a path or URL to an HTML page, image file, or any other resource which is supported by the browser. If the empty string ("") is specified as url, a blank page is opened into the targeted browsing context.
+
windowName
+
A {{domxref("DOMString")}} specifying the name of the browsing context (window, {{HTMLElement("iframe")}} or tab) into which to load the specified resource; if the name doesn't indicate an existing context, a new window is created and is given the name specified by windowName. This name can then be used as the target of links and forms by specifying it as the target attribute of {{HTMLElement("a")}} or {{HTMLElement("form")}} elements. The name should not contain whitespace. Keep in mind that this will not be used as the window's displayed title.
+
windowFeatures {{optional_inline}}
+
A {{domxref("DOMString")}} containing a comma-separated list of window features given with their corresponding values in the form "name=value". These features include options such as the window's default size and position, whether or not to include scroll bars, and so forth. There must be no whitespace in the string. See {{anch("Window features")}} below for documentation of each of the features that can be specified.
+
+ +

Valor de retorno

+ +

A {{domxref("Window")}} object representing to the newly created window. If the window couldn't be opened, the returned value is instead null. The returned Window reference can be used to access properties and methods of the new window as long as it complies with Same-origin policy security requirements.

+ +

Descrição

+ +

The open() method creates a new secondary browser window, similar to choosing New Window from the File menu. The strUrl parameter specifies the URL to be fetched and loaded in the new window. If strUrl is an empty string, then a new blank, empty window (URL about:blank) is created with the default toolbars of the main window.

+ +

Note that remote URLs won't load immediately. When window.open() returns, the window always contains about:blank. The actual fetching of the URL is deferred and starts after the current script block finishes executing. The window creation and the loading of the referenced resource are done asynchronously.

+ +

Exemplos

+ +
var windowObjectReference;
+var strWindowFeatures = "menubar=yes,location=yes,resizable=yes,scrollbars=yes,status=yes";
+
+function openRequestedPopup() {
+  windowObjectReference = window.open("http://www.cnn.com/", "CNN_WindowName", strWindowFeatures);
+}
+ +
var windowObjectReference;
+
+function openRequestedPopup() {
+  windowObjectReference = window.open(
+    "http://www.domainname.ext/path/ImageFile.png",
+    "DescriptiveWindowName",
+    "resizable,scrollbars,status"
+  );
+}
+ +

If a window with the name already exists, then strUrl is loaded into the existing window. In this case the return value of the method is the existing window and strWindowFeatures is ignored. Providing an empty string for strUrl is a way to get a reference to an open window by its name without changing the window's location. To open a new window on every call of window.open(), use the special value _blank for strWindowName.

+ +
+

Note on the use of window.open to reopen an existing window with name strWindowName : This functionality is not valid for all browsers and more with variable conditions. Firefox (50.0.1) functions as described: from the same domain+port reopen with same name will access the previously created window. Google Chrome (55.0.2883.87 m ) on the other hand will do it only from the same parent (as if the window was created dependent, which is the "opener"). This is a wide limitation and generates unbelievable complexity of development. Firefox (51.) gets the handle but cannot run any Element.focus() while Chrome can run focus() from opener to child but not between siblings nor, reverse, from child to opener. This function is the lonely key to get back the handle on a window if the developer has access only to its name (the name can be saved with cookies or local storage but not the window object handle). For now 10/01/2017 the differencies of behavior found recently have not still been tested for others Browsers.  

+
+ +

Funcionalidades de janela

+ +

strWindowFeatures is an optional string containing a comma-separated list of requested features of the new window. After a window is opened, JavaScript can't be used to change the features. If strWindowName does not specify an existing window and the strWindowFeatures parameter is not provided (or if the strWindowFeatures parameter is an empty string), then the new secondary window will render the default toolbars of the main window.

+ +

If the strWindowFeatures parameter is used and no size features are defined, then the new window dimensions will be the same as the dimensions of the most recently rendered window.

+ +

If the strWindowFeatures parameter is used and if no position features are defined, then the left and top coordinates of the new window dimension will be 22 pixels from where the most recently rendered window was. An offset is universally implemented by browser manufacturers (it is 29 pixels in IE6 SP2 with the default theme) and its purpose is to help users to notice new windows opening. If the most recently used window was maximized, then there is no offset: the new window will be maximized as well.

+ +

If the strWindowFeatures parameter is used, the features that are not listed will be disabled or removed (except titlebar and close, which are by default yes).

+ +
+

Tip: If using the strWindowFeatures parameter, only list the features to be enabled or rendered; the others (except titlebar and close) will be disabled or removed. Note that in some browsers, users can override the strWindowFeatures settings and enable (or prevent the disabling of) features.

+
+ +

Firefox Toolbars Illustration

+ +

Funcionalidades de posição e tamanho

+ +
{{gecko_minversion_note("1.9.2", "Starting in Gecko 1.9.2 (Firefox 3.6), overriding the position of a window using window features will not change the persisted values saved by the session store feature. That means the next time the window is opened, it will still open in the saved location.")}}
+ +

Note on position and dimension error correction

+ +
{{bug(176320)}}
+ +

Note on precedence

+ +
+
left
+
Specifies the distance the new window is placed from the left side of the work area for applications of the user's operating system to the leftmost border (resizing handle) of the browser window. The new window can not be initially positioned offscreen.
+
Supported in: Internet Explorer 5+, Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x, Opera 6+
+
top
+
Specifies the distance the new window is placed from the top side of the work area for applications of the user's operating system to the topmost border (resizing handle) of the browser window. The new window can not be initially positioned offscreen.
+
Supported in: Internet Explorer 5+, Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x, Opera 6+
+
height
+
Specifies the height of the content area, viewing area of the new secondary window in pixels. The height value includes the height of the horizontal scrollbar if present. The minimum required value is 100.
+
Note on outerHeight versus height (or innerHeight)
+
Supported in: Internet Explorer 5+, Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x, Opera 6+
+
width
+
Specifies the width of the content area, viewing area of the new secondary window in pixels. The width value includes the width of the vertical scrollbar if present. The width value does not include the sidebar if it is expanded. The minimum required value is 100.
+
Supported in: Internet Explorer 5+, Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x, Opera 6+
+
screenX
+
Deprecated. Same as left but only supported by Netscape and Mozilla-based browsers.
+
Supported in: Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
+
screenY
+
Deprecated. Same as top but only supported by Netscape and Mozilla-based browsers.
+
Supported in: Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
+
centerscreen
+
Centers the window in relation to its parent's size and position. Requires chrome=yes.
+
outerHeight
+
Specifies the height of the whole browser window in pixels. This outerHeight value includes any/all present toolbar, window horizontal scrollbar (if present) and top and bottom window resizing borders. Minimal required value is 100.
+
Note: since titlebar is always rendered, then requesting outerHeight=100 will make the innerHeight of the browser window under the minimal 100 pixels.
+
Note on outerHeight versus height (or innerHeight)
+
Supported in: Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
+
outerWidth
+
Specifies the width of the whole browser window in pixels. This outerWidth value includes the window vertical scrollbar (if present) and left and right window resizing borders.
+
Supported in: Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
+
innerHeight
+
Same as height but only supported by Netscape and Mozilla-based browsers. Specifies the height of the content area, viewing area of the new secondary window in pixels. The innerHeight value includes the height of the horizontal scrollbar if present. Minimal required value is 100.
+
Note on outerHeight versus height (or innerHeight)
+
Supported in: Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
+
innerWidth
+
Same as width but only supported by Netscape and Mozilla-based browsers. Specifies the width of the content area, viewing area of the new secondary window in pixels. The innerWidth value includes the width of the vertical scrollbar if present. The innerWidth value does not include the sidebar if it is expanded. Minimal required value is 100.
+
Supported in: Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
+
+ +

Funcionalidades da barra de ferramentas e chrome

+ +
+
NOTE: All features can be set to yes or 1, or just be present to be "on". Set them to no or 0, or in most cases just omit them, to be "off".
+
Example: "status=yes", "status=1", and "status" have identical results.
+
menubar
+
If this feature is on, then the new secondary window renders the menubar.
+
Mozilla and Firefox users can force new windows to always render the menubar by setting dom.disable_window_open_feature.menubar to true in about:config or in their user.js file.
+
Supported in: Internet Explorer 5+, Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
+
toolbar
+
If this feature is on, then the new secondary window renders the Navigation Toolbar (Back, Forward, Reload, Stop buttons). In addition to the Navigation Toolbar, Mozilla-based browsers will render the Tab Bar if it is visible, present in the parent window. (If this feature is set to no all toolbars in the window will be invisible, for example extension toolbars).
+
Mozilla and Firefox users can force new windows to always render the Navigation Toolbar by setting dom.disable_window_open_feature.toolbar to true in about:config or in their user.js file.
+
Supported in: Internet Explorer 5+, Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
+
location
+
If this feature is on, then the new secondary window renders the Location bar in Mozilla-based browsers. MSIE 5+ and Opera 7.x renders the Address Bar.
+
Mozilla and Firefox users can force new windows to always render the location bar by setting dom.disable_window_open_feature.location to true in about:config or in their user.js file. {{Fx_minversion_note(3, "In Firefox 3, dom.disable_window_open_feature.location now defaults to true, forcing the presence of the Location Bar much like in IE7. See bug 337344 for more information.")}}
+
Supported in: Internet Explorer 5+, Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x, Opera 6+
+
personalbar
+
If this feature is on, then the new secondary window renders the Personal Toolbar in Netscape 6.x, Netscape 7.x and Mozilla browser. It renders the Bookmarks Toolbar in Firefox. In addition to the Personal Toolbar, Mozilla browser will render the Site Navigation Bar if such toolbar is visible, present in the parent window.
+
Mozilla and Firefox users can force new windows to always render the Personal Toolbar/Bookmarks toolbar by setting dom.disable_window_open_feature.personalbar to true in about:config or in their user.js file.
+
Supported in: Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
+
directories {{obsolete_inline("2")}}
+
Obsolete synonym of personalbar. In IE, it rendered the Links bar. Supported in Gecko up to 1.9.2 and in IE up to 6.
+
status
+
If this feature is on, then the new secondary window has a status bar. Users can force the rendering of status bar in all Mozilla-based browsers, in MSIE 6 SP2 (Note on status bar in XP SP2) and in Opera 6+. The default preference setting in recent Mozilla-based browser releases and in Firefox 1.0 is to force the presence of the status bar.
+
Note on status bar
+
Supported in: Internet Explorer 5+, Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
+
+ +

Funcionalidades da função da janela

+ +
+
attention {{NonStandardBadge}}
+
If this feature is specified, the window is able to open even if another application is already in the foreground. This feature is for Firefox OS applications only, and is currently restricted to certified applications. See {{SectionOnPage("/en-US/Apps/Build/App_permissions", "Certified app permissions")}} for more information.
+
Supported in:
+
dependent
+
If on, the new window is said to be dependent of its parent window. A dependent window closes when its parent window closes. A dependent window is minimized on the Windows task bar only when its parent window is minimized. On Windows platforms, a dependent window does not show on the task bar. A dependent window also stays in front of the parent window.
+
Dependent windows are not implemented on MacOS X, this option will be ignored.
+
The dependent feature is currently under revision to be removed ({{Bug(214867)}})
+
In MSIE 6, the nearest equivalent to this feature is the showModelessDialog() method.
+
Supported in: Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
+
minimizable
+
This setting can only apply to dialog windows; "minimizable" requires dialog=yes. If minimizable is on, the new dialog window will have a minimize system command icon in the titlebar and it will be minimizable. Any non-dialog window is always minimizable and minimizable=no will be ignored.
+
Supported in: Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
+
fullscreen
+
Do not use. Not implemented in Mozilla. There are no plans to implement this feature in Mozilla.
+
This feature no longer works in MSIE 6 SP2 the way it worked in MSIE 5.x. The Windows taskbar, as well as the titlebar and the status bar of the window are not visible, nor accessible when fullscreen is enabled in MSIE 5.x.
+
fullscreen always upsets users with large monitor screen or with dual monitor screen. Forcing fullscreen onto other users is also extremely unpopular and is considered an outright rude attempt to impose web author's viewing preferences onto users.
+
Note on fullscreen
+
Supported in: Internet Explorer 5+
+
fullscreen does not really work in MSIE 6 SP2.
+
noopener
+
If this feature is set, the newly-opened window will open as normal, except that it will not have access back to the originating window (via {{domxref("Window.opener")}} — it returns null). In addition, the window.open() call will also return null, so the originating window will not have access to the new one either.  This is useful for preventing untrusted sites opened via window.open() from tampering with the originating window, and vice versa.
+
Note that when noopener is used, nonempty target names other than _top, _self, and _parent are all treated like _blank in terms of deciding whether to open a new window/tab.
+
+ This is supported in modern browsers including Chrome, and Firefox 52+. See also rel="noopener".
+
resizable
+
If this feature is on, the new secondary window will be resizable.
+
Note: Starting with version 1.4, Mozilla-based browsers have a window resizing grippy at the right end of the status bar, this ensures that users can resize the browser window even if the web author requested this secondary window to be non-resizable. In such case, the maximize/restore icon in the window's titlebar will be disabled and the window's borders won't allow resizing but the window will still be resizable via that grippy in the status bar. +

Starting with Firefox 3, secondary windows are always resizable ({{Bug(177838)}})

+ +
+

Dica: For accessibility reasons, it is strongly recommended to set this feature always on

+
+
+
Mozilla and Firefox users can force new windows to be easily resizable by setting dom.disable_window_open_feature.resizable to true in about:config or in their user.js file.
+
Supported in: Internet Explorer 5+, Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
+
scrollbars
+
If this feature is on, the new secondary window will show horizontal and/or vertical scrollbar(s) if the document doesn't fit into the window's viewport. +
+

Dica: For accessibility reasons, it is strongly encouraged to set this feature always on.

+
+
+
Mozilla and Firefox users can force this option to be always enabled for new windows by setting {{pref("dom.disable_window_open_feature.scrollbars")}} to true in about:config or in their user.js file. Starting in Firefox 49, this feature is on by default, and the {{pref("dom.disable_window_open_feature.scrollbars")}} preference has been removed.
+
Note on scrollbars
+
Supported in: Internet Explorer 5+, Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
+
+ +

Funcionalidades que requerem privilégios

+ +

The following features require the UniversalBrowserWrite privilege, otherwise they will be ignored. Chrome scripts have this privilege automatically, others have to request it from the PrivilegeManager.

+ +
+
chrome
+
Note: Starting with Mozilla 1.7/Firefox 0.9, this feature requires the UniversalBrowserWrite privilege ({{Bug(244965)}}). Without this privilege, it is ignored.
+
If on, the page is loaded as window's only content, without any of the browser's interface elements. There will be no context menu defined by default and none of the standard keyboard shortcuts will work. The page is supposed to provide a user interface of its own, usually this feature is used to open XUL documents (standard dialogs like the JavaScript Console are opened this way).
+
Supported in: Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
+
dialog
+
Note: Starting with Firefox 44, this feature can only be used with chrome privileges. If content attempts to toggle this feature, it will be ignored.
+
MenuSystemCommands.png The dialog feature removes all icons (restore, minimize, maximize) from the window's titlebar, leaving only the close button. Mozilla 1.2+ and Netscape 7.1 will render the other menu system commands (in FF 1.0 and in NS 7.0x, the command system menu is not identified with the Firefox/NS 7.0x icon on the left end of the titlebar: that's probably a bug. You can access the command system menu with a right-click on the titlebar). Dialog windows are windows which have no minimize system command icon and no maximize/restore down system command icon on the titlebar nor in correspondent menu item in the command system menu. They are said to be dialog because their normal, usual purpose is to only notify info and to be dismissed, closed. On Mac systems, dialog windows have a different window border and they may get turned into a sheet.
+
Supported in: Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
+
modal
+
Note: Starting with Mozilla 1.2.1, this feature requires the UniversalBrowserWrite privilege ({{Bug(180048)}}). Without this privilege, it is ignored.
+
If on, the new window is said to be modal. The user cannot return to the main window until the modal window is closed. A typical modal window is created by the alert() function.
+
The exact behavior of modal windows depends on the platform and on the Mozilla release version. +
+

Nota: As of {{Gecko("1.9")}}, the Internet Explorer equivalent to this feature is the {{domxref("window.showModalDialog()")}} method. For compatibility reasons, it's now supported in Firefox. Note also that starting in {{Gecko("2.0")}}, you can use {{domxref("window.showModalDialog()")}} without UniversalBrowserWrite privileges.

+
+
+
Supported in: Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
+
titlebar
+
By default, all new secondary windows have a titlebar. If set to no or 0, this feature removes the titlebar from the new secondary window.
+
Mozilla and Firefox users can force new windows to always render the titlebar by setting
+ dom.disable_window_open_feature.titlebar
+ to true in about:config or in their user.js file.
+
Supported in: Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
+
alwaysRaised
+
If on, the new window will always be displayed on top of other browser windows, regardless of whether it is active or not.
+
Supported in: Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
+
alwaysLowered
+
If on, the new created window floats below, under its own parent when the parent window is not minimized. alwaysLowered windows are often referred as pop-under windows. The alwaysLowered window can not be on top of the parent but the parent window can be minimized. In NS 6.x, the alwaysLowered window has no minimize system command icon and no restore/maximize system command.
+
Supported in: Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
+
z-lock
+
Same as alwaysLowered.
+
close
+
When set to no or 0, this feature removes the system close command icon and system close menu item. It will only work for dialog windows (dialog feature set). close=no will override minimizable=yes.
+
Mozilla and Firefox users can force new windows to always have a close button by setting
+ dom.disable_window_open_feature.close
+ to true in about:config or in their user.js file.
+
Supported in: Netscape 6.x, Netscape 7.x, Mozilla 1.x, Firefox 1.x
+
+ +

The position and size feature elements require a number to be set. The toolbars and window functionalities can be set with a yes or no; you can use 1 instead of yes and 0 instead of no. The toolbar and functionality feature elements also accept the shorthand form: you can turn a feature on by simply listing the feature name in the features string. If you supply the features parameter, then the titlebar and close are still yes by default, but the other features which have a yes/no choice will be no by default and will be turned off.

+ +

Example:

+ +
var windowObjectReference; // global variable
+
+function openRequestedPopup() {
+  windowObjectReference = window.open(
+    "http://www.domainname.ext/path/ImgFile.png",
+    "DescriptiveWindowName",
+    "width=420,height=230,resizable,scrollbars=yes,status=1"
+  );
+}
+ +

In this example, the window will be resizable, it will render scrollbar(s) if needed, if the content overflows requested window dimensions and it will render the status bar. It will not render the menubar nor the location bar. Since the author knew about the size of the image (400 pixels wide and 200 pixels high), he added the margins applied to the root element in MSIE 6 which is 15 pixels for top margin, 15 pixels for the bottom margin, 10 pixels for the left margin and 10 pixels for the right margin.

+ +

As melhores práticas

+ +
<script type="text/javascript">
+var windowObjectReference = null; // global variable
+
+function openFFPromotionPopup() {
+  if(windowObjectReference == null || windowObjectReference.closed)
+  /* if the pointer to the window object in memory does not exist
+     or if such pointer exists but the window was closed */
+
+  {
+    windowObjectReference = window.open("http://www.spreadfirefox.com/",
+   "PromoteFirefoxWindowName", "resizable,scrollbars,status");
+    /* then create it. The new window will be created and
+       will be brought on top of any other window. */
+  }
+  else
+  {
+    windowObjectReference.focus();
+    /* else the window reference must exist and the window
+       is not closed; therefore, we can bring it back on top of any other
+       window with the focus() method. There would be no need to re-create
+       the window or to reload the referenced resource. */
+  };
+}
+</script>
+
+(...)
+
+<p><a
+ href="http://www.spreadfirefox.com/"
+ target="PromoteFirefoxWindowName"
+ onclick="openFFPromotionPopup(); return false;"
+ title="This link will create a new window or will re-use an already opened one"
+>Promote Firefox adoption</a></p>
+
+ +

The above code solves a few usability problems related to links opening secondary window. The purpose of the return false in the code is to cancel default action of the link: if the onclick event handler is executed, then there is no need to execute the default action of the link. But if javascript support is disabled or non-existent on the user's browser, then the onclick event handler is ignored and the browser loads the referenced resource in the target frame or window that has the name "PromoteFirefoxWindowName". If no frame nor window has the name "PromoteFirefoxWindowName", then the browser will create a new window and will name it "PromoteFirefoxWindowName".

+ +

More reading on the use of the target attribute:

+ +

HTML 4.01 Target attribute specifications

+ +

How do I create a link that opens a new window?

+ +

You can also parameterize the function to make it versatile, functional in more situations, therefore re-usable in scripts and webpages:

+ +
<script type="text/javascript">
+var windowObjectReference = null; // global variable
+
+function openRequestedPopup(strUrl, strWindowName) {
+  if(windowObjectReference == null || windowObjectReference.closed) {
+    windowObjectReference = window.open(strUrl, strWindowName,
+           "resizable,scrollbars,status");
+  } else {
+    windowObjectReference.focus();
+  };
+}
+</script>
+
+(...)
+
+<p><a
+ href="http://www.spreadfirefox.com/"
+ target="PromoteFirefoxWindow"
+ onclick="openRequestedPopup(this.href, this.target); return false;"
+ title="This link will create a new window or will re-use an already opened one"
+>Promote Firefox adoption</a></p>
+
+ +

You can also make such function able to open only 1 secondary window and to reuse such single secondary window for other links in this manner:

+ +
<script type="text/javascript">
+var windowObjectReference = null; // global variable
+var PreviousUrl; /* global variable which will store the
+                    url currently in the secondary window */
+
+function openRequestedSinglePopup(strUrl) {
+  if(windowObjectReference == null || windowObjectReference.closed) {
+    windowObjectReference = window.open(strUrl, "SingleSecondaryWindowName",
+         "resizable,scrollbars,status");
+  } else if(PreviousUrl != strUrl) {
+    windowObjectReference = window.open(strUrl, "SingleSecondaryWindowName",
+      "resizable=yes,scrollbars=yes,status=yes");
+    /* if the resource to load is different,
+       then we load it in the already opened secondary window and then
+       we bring such window back on top/in front of its parent window. */
+    windowObjectReference.focus();
+  } else {
+    windowObjectReference.focus();
+  };
+
+  PreviousUrl = strUrl;
+  /* explanation: we store the current url in order to compare url
+     in the event of another call of this function. */
+}
+</script>
+
+(...)
+
+<p><a
+ href="http://www.spreadfirefox.com/"
+ target="SingleSecondaryWindowName"
+ onclick="openRequestedSinglePopup(this.href); return false;"
+ title="This link will create a new window or will re-use an already opened one"
+>Promote Firefox adoption</a></p>
+
+<p><a
+ href="http://www.mozilla.org/support/firefox/faq"
+ target="SingleSecondaryWindowName"
+ onclick="openRequestedSinglePopup(this.href); return false;"
+ title="This link will create a new window or will re-use an already opened one"
+>Firefox FAQ</a></p>
+
+ +

Perguntas Mais Frequentes

+ +
+
How can I prevent the confirmation message asking the user whether he wants to close the window?
+
You can not. New windows not opened by javascript can not as a rule be closed by JavaScript. The JavaScript Console in Mozilla-based browsers will report the warning message: "Scripts may not close windows that were not opened by script." Otherwise the history of URLs visited during the browser session would be lost.
+
More on the window.close() method
+
How can I bring back the window if it is minimized or behind another window?
+
First check for the existence of the window object reference of such window and if it exists and if it has not been closed, then use the focus() method. There is no other reliable way. You can examine an example explaining how to use the focus() method.
+
How do I force a maximized window?
+
You cannot. All browser manufacturers try to make the opening of new secondary windows noticed by users and noticeable by users to avoid confusion, to avoid disorienting users.
+
How do I turn off window resizability or remove toolbars?
+
You cannot force this. Users with Mozilla-based browsers have absolute control over window functionalities like resizability, scrollability and toolbars presence via user preferences in about:config. Since your users are the ones who are supposed to use such windows (and not you, being the web author), the best is to avoid interfering with their habits and preferences. We recommend to always set the resizability and scrollbars presence (if needed) to yes to insure accessibility to content and usability of windows. This is in the best interests of both the web author and the users.
+
How do I resize a window to fit its content?
+
You can not reliably because the users can prevent the window from being resized by unchecking the Edit/Preferences/Advanced/Scripts & Plug-ins/Allow Scripts to/ Move or resize existing windows checkbox in Mozilla or Tools/Options.../Content tab/Enable Javascript/Advanced button/Move or resize existing windows checkbox in Firefox or by setting dom.disable_window_move_resize to true in about:config or by editing accordingly their user.js file.
+
In general, users usually disable moving and resizing of existing windows because allowing authors' scripts to do so has been abused overwhelmingly in the past and the rare scripts that do not abuse such feature are often wrong, inaccurate when resizing the window. 99% of all those scripts disable window resizability and disable scrollbars when in fact they should enable both of these features to allow a cautious and sane fallback mechanism if their calculations are wrong.
+
The window method sizeToContent() is also disabled if the user unchecks the preference Move or resize existing windows checkbox. Moving and resizing a window remotely on the user's screen via script will very often annoy the users, will disorient the user, and will be wrong at best. The web author expects to have full control of (and can decide about) every position and size aspects of the users' browser window ... which is simply not true.
+
How do I open a referenced resource of a link in a new tab? or in a specific tab?
+
To open a resource in a new tab see Tabbed browser. Some Code snippets are available. If you are using the SDK, tabs are handled a bit differently
+
K-meleon 1.1, a Mozilla-based browser, gives complete control and power to the user regarding how links are opened. Only the user can set his advanced preferences to do that. Some advanced extensions also give Mozilla and Firefox a lot of power over how referenced resources are loaded.
+
In a few years, the target property of the CSS3 hyperlink module may be implemented (if CSS3 Hyperlink module as it is right now is approved). And even if and when this happens, you can expect developers of browsers with tab-browsing to give the user entire veto power and full control over how links can open web pages. How to open a link should always be entirely under the control of the user.
+
How do I know whether a window I opened is still open?
+
You can test for the existence of the window object reference which is the returned value in case of success of the window.open() call and then verify that windowObjectReference.closed return value is false.
+
How can I tell when my window was blocked by a popup blocker?
+
With the built-in popup blockers of Mozilla/Firefox and Internet Explorer 6 SP2, you have to check the return value of window.open(): it will be null if the window wasn't allowed to open. However, for most other popup blockers, there is no reliable way.
+
What is the JavaScript relationship between the main window and the secondary window?
+
The window.open() method gives a main window a reference to a secondary window; the opener property gives a secondary window a reference to its main window.
+
I can not access the properties of the new secondary window. I always get an error in the javascript console saying "Error: uncaught exception: Permission denied to get property <property_name or method_name>. Why is that?
+
It is because of the cross-domain script security restriction (also referred as the "Same Origin Policy"). A script loaded in a window (or frame) from a distinct origin (domain name) cannot get nor set properties of another window (or frame) or the properties of any of its HTML objects coming from another distinct origin (domain name). Therefore, before executing a script targeting a secondary window, the browser in the main window will verify that the secondary window has the same domain name.
+
More reading on the cross-domain script security restriction: http://www.mozilla.org/projects/secu...me-origin.html
+
+ +

Problemas de usabilidade

+ +

Evitar o recurso a window.open()

+ +

Generally speaking, it is preferable to avoid resorting to window.open() for several reasons:

+ + + +

Oferecer para abrir uma hiperligação numa nova janela, utilizando estas linhas diretrizes

+ +

If you want to offer to open a link in a new window, then follow tested and recommendable usability and accessibility guidelines:

+ + + +

"javascript:" links break accessibility and usability of webpages in every browser.

+ + + +

Further reading:

+ + + +

Never use <a href="#" onclick="window.open(...);">

+ +

Such pseudo-link also breaks accessibility of links. Always use a real URL for the href attribute value so that if javascript support is disabled or inexistent or if the user agent does not support opening of secondary window (like MS-Web TV, text browsers, etc), then such user agents will still be able to load the referenced resource according to its default mode of opening/handling a referenced resource. This form of code also interferes with advanced features in tab-capable browsers: eg. middle-click on links, Ctrl+click on links, Ctrl+Enter on links, "mouse gestures" features.

+ + + +

Identify links that will open new windows in a way that helps navigation for users by coding the title attribute of the link, by adding an icon at the end of the link or by coding the cursor accordingly.

+ +

The purpose is to warn users in advance of context changes to minimize confusion on the user's part: changing the current window or popping up new windows can be very disorienting to users (Back toolbar button is disabled).

+ +
+

"Users often don't notice that a new window has opened, especially if they are using a small monitor where the windows are maximized to fill up the screen. So a user who tries to return to the origin will be confused by a grayed out Back button."
+ quote from The Top Ten New Mistakes of Web Design: 2. Opening New Browser Windows, Jakob Nielsen, May 1999

+
+ +

When extreme changes in context are explicitly identified before they occur, then the users can determine if they wish to proceed or so they can be prepared for the change: not only they will not be confused or feel disoriented, but more experienced users can better decide how to open such links (in a new window or not, in the same window, in a new tab or not, in "background" or not).

+ +

Referências

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Example "New Window" Icons & Cursors
New window icon from yahoo.comNew window icon from microsoft.comNew window icon from webaim.orgNew window icon from sun.com
New window icon from bbc.co.ukNew window icon from Accessible Internet SolutionsNew window icon from accessify.comNew window icon from webstyleguide.com
New window icon from an unknown sourceNew window icon from an unknown sourceNew window icon from an unknown sourceNew window icon from gtalbot.org
New window cursor from draig.deNew window cursor from mithgol.ru
+ +

Utilziar sempre o atributo target

+ +

If javascript support is disabled or non-existent, then the user agent will create a secondary window accordingly or will render the referenced resource according to its handling of the target attribute: e.g. some user agents which can not create new windows, like MS Web TV, will fetch the referenced resource and append it at the end of the current document. The goal and the idea is to try to provide - not impose - to the user a way to open the referenced resource, a mode of opening the link. Your code should not interfere with the features of the browser at the disposal of the user and your code should not interfere with the final decision resting with the user.

+ +

Não utilizar target="_blank"

+ +

Always provide a meaningful name to your target attribute and try to reuse such target attribute in your page so that a click on another link may load the referenced resource in an already created and rendered window (therefore speeding up the process for the user) and therefore justifying the reason (and user system resources, time spent) for creating a secondary window in the first place. Using a single target attribute value and reusing it in links is much more user resources friendly as it only creates one single secondary window which is recycled. On the other hand, using "_blank" as the target attribute value will create several new and unnamed windows on the user's desktop which can not be recycled, reused. In any case, if your code is well done, it should not interfere with the user's final choice but rather merely offer him more choices, more ways to open links and more power to the tool he's using (a browser).

+ +

Glossário

+ +
+
Opener window, parent window, main window, first window
+
Terms often used to describe or to identify the same window. It is the window from which a new window will be created. It is the window on which the user clicked a link which lead to the creation of another, new window.
+
Sub-window, child window, secondary window, second window
+
Terms often used to describe or to identify the same window. It is the new window which was created.
+
Unrequested popup windows
+
Script-initiated windows opening automatically without the user's consent.
+
+ +

Especificação

+ + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('HTML WHATWG', 'browsers.html#dom-open', 'Window.open()')}}{{Spec2('HTML WHATWG')}} 
{{ SpecName('CSSOM View', '#the-features-argument-to-the-open()-method', 'The features argument to the open() method') }}{{ Spec2('CSSOM View') }}Defines the effect of the features argument
+ +

Notas

+ +

Nota na precedência

+ +

In cases where left and screenX (and/or top and screenY) have conflicting values, then left and top have precedence over screenX and screenY respectively. If left and screenX (and/or top and screenY) are defined in the features list, then left (and/or top) will be honored and rendered. In the following example the new window will be positioned at 100 pixels from the left side of the work area for applications of the user's operating system, not at 200 pixels.

+ +
windowObjectReference = window.open(
+  "http://news.bbc.co.uk/",
+  "BBCWorldNewsWindowName",
+  "left=100,screenX=200,resizable,scrollbars,status"
+);
+ +

If left is set but top has no value and screenY has a value, then left and screenY will be the coordinate positioning values of the secondary window.

+ +

outerWidth has precedence over width and width has precedence over innerWidth. outerHeight has precedence over height and height has precedence over innerHeight. In the following example, Mozilla-browsers will create a new window with an outerWidth of 600 pixels wide and will ignore the request of a width of 500 pixels and will also ignore the request of an innerWidth of 400 pixels.

+ +
windowObjectReference = window.open(
+  "http://www.wwf.org/",
+  "WWildlifeOrgWindowName",
+  "outerWidth=600,width=500,innerWidth=400,resizable,scrollbars,status"
+);
+ +

Nota na correção de erro da posição e dimensão

+ +

Requested position and requested dimension values in the features list will not be honored and will be corrected if any of such requested value does not allow the entire browser window to be rendered within the work area for applications of the user's operating system. No part of the new window can be initially positioned offscreen. This is by default in all Mozilla-based browser releases.

+ +

MSIE 6 SP2 has a similar error correction mechanism but it is not activated by default in all security levels: a security setting can disable such error correction mechanism.

+ +

Nota nas scrollbars

+ +

When content overflows window viewport dimensions, then scrollbar(s) (or some scrolling mechanism) are necessary to ensure that content can be accessed by users. Content can overflow window dimensions for several reasons which are outside the control of web authors:

+ + + +

Nota na barra de estado

+ +

You should assume that a large majority of browsers will have the status bar or that a large majority of users will want to force the status bar presence: best is to always set this feature to yes. Also, if you specifically request to remove the status bar, then Firefox users will not be able to view the Site Navigation toolbar if it is installed. In Mozilla and in Firefox, all windows with a status bar have a window resizing grippy at its right-most side. The status bar also provides info on http connection, hypertext resource location, download progress bar, encryption/secure connection info with SSL connection (displaying a yellow padlock icon), internet/security zone icons, privacy policy/cookie icon, etc. Removing the status bar usually removes a lot of functionality, features and information considered useful (and sometimes vital) by the users.

+ +

Nota nos problemas de segurança da presença da barra de estado

+ +

In MSIE 6 for XP SP2: For windows opened using window.open():

+ +
+

"For windows opened using window.open():
+ Expect the status bar to be present, and code for it. The status bar will be on by default and is 20-25 pixels in height. (...)"
+ quote from Fine-Tune Your Web Site for Windows XP Service Pack 2, Browser Window Restrictions in XP SP2

+
+ +
+

"(...) windows that are created using the window.open() method can be called by scripts and used to spoof a user interface or desktop or to hide malicious information or activity by sizing the window so that the status bar is not visible.
+ Internet Explorer windows provide visible security information to the user to help them ascertain the source of the Web page and the security of the communication with that page. When these elements are not in view, the user might think they are on a more trusted page or interacting with a system process when they are actually interacting with a malicious host. (...)
+ Script-initiated windows will be displayed fully, with the Internet Explorer title bar and status bar. (...)
+ Script management of Internet Explorer status bar
+ Detailed description
+ Internet Explorer has been modified to not turn off the status bar for any windows. The status bar is always visible for all Internet Explorer windows. (...) Without this change, windows that are created using the window.open() method can be called by scripts and spoof a user interface or desktop or hide malicious information or activity by hiding important elements of the user interface from the user.
+ The status bar is a security feature of Internet Explorer windows that provides Internet Explorer security zone information to the user. This zone cannot be spoofed (...)"
+ quote from Changes to Functionality in Microsoft Windows XP Service Pack 2, Internet Explorer Window Restrictions

+
+ +

Nota no ecrã completo

+ +

In MSIE 6 for XP SP2:

+ + + +

Referências:

+ + + +

Nota em outerHeight versus height

+ +

innerHeight vs outerHeight illustration

+ +

Nota na atualização (recarregar página) vs. abrir uma nova janela/separador

+ +

If the strWindowName parameter is omitted, a new window or tab is opened. If a window with the same name already exists, the existing window is refreshed.

+ +
//Always opens a new window/tab
+window.open("map.php");
+
+//Refreshes an existing window/tab that was opened with the same name, if one exists
+window.open("map.php", "BiggerMap");
+ +

Tutoriais

+ + + +

Referências

+ + + +
+ + + + + +
diff --git a/files/pt-pt/web/api/window/postmessage/index.html b/files/pt-pt/web/api/window/postmessage/index.html new file mode 100644 index 0000000000..50e5c91a5d --- /dev/null +++ b/files/pt-pt/web/api/window/postmessage/index.html @@ -0,0 +1,337 @@ +--- +title: Window.postMessage() +slug: Web/API/Window/postMessage +tags: + - API + - DOM + - Janela + - Referencia + - metodo +translation_of: Web/API/Window/postMessage +--- +
{{ApiRef("HTML DOM")}}
+ +

O método window.postMessage()  permite a comunicação segura de origem cruzada. Normalmente, é permitido que os scripts em páginas diferentes podem aceder a cada uma delas, se e apenas se as páginas que os executaram estão em localizações com o mesmo protocolo (normalmente ambas https), número da porta (443, por predefinição para https), e anfitrião (módulo {{domxref("Document.domain")}}, sendo definidos por ambas as páginas para o mesmo valor). window.postMessage() fornece um mecanismo para contornar esta restrição de um modo que é seguro quando utilizado corretamente.

+ +

The window.postMessage() method, when called, causes a {{domxref("MessageEvent")}} to be dispatched at the target window when any pending script that must be executed completes (e.g., remaining event handlers if window.postMessage() is called from an event handler, previously-set pending timeouts, etc.) The {{domxref("MessageEvent")}} has the type message, a data property which is set to the value of the first argument provided to window.postMessage(), an origin property corresponding to the origin of the main document in the window calling window.postMessage at the time window.postMessage() was called, and a source property which is the window from which window.postMessage() is called. (Other standard properties of events are present with their expected values.)

+ +

Sintaxe

+ +
otherWindow.postMessage(message, targetOrigin, [transfer]);
+ +
+
otherWindow
+
A reference to another window; such a reference may be obtained, for example, using the contentWindow property of an iframe element, the object returned by window.open, or by named or numeric index on {{domxref("Window.frames")}}, if you're trying to start the communication from iframe to parent window then parent is also a valid reference
+
message
+
Data to be sent to the other window. The data is serialized using the structured clone algorithm. This means you can pass a broad variety of data objects safely to the destination window without having to serialize them yourself. [1]
+
targetOrigin
+
Specifies what the origin of otherWindow must be for the event to be dispatched, either as the literal string "*" (indicating no preference) or as a URI. If at the time the event is scheduled to be dispatched the scheme, hostname, or port of otherWindow's document does not match that provided in targetOrigin, the event will not be dispatched; only if all three match will the event be dispatched. This mechanism provides control over where messages are sent; for example, if postMessage() was used to transmit a password, it would be absolutely critical that this argument be a URI whose origin is the same as the intended receiver of the message containing the password, to prevent interception of the password by a malicious third party. Always provide a specific targetOrigin, not *, if you know where the other window's document should be located. Failing to provide a specific target discloses the data you send to any interested malicious site.
+
transfer {{optional_Inline}}
+
Is a sequence of {{domxref("Transferable")}} objects that are transferred with the message. The ownership of these objects is given to the destination side and they are no longer usable on the sending side.
+
+ +

O evento expedido

+ +

otherWindow can listen for dispatched messages by executing the following JavaScript:

+ +
window.addEventListener("message", receiveMessage, false);
+
+function receiveMessage(event)
+{
+  if (event.origin !== "http://example.org:8080")
+    return;
+
+  // ...
+}
+
+ +

The properties of the dispatched message are:

+ +
+
data
+
The object passed from the other window.
+
origin
+
The origin of the window that sent the message at the time postMessage was called. This string is the concatenation of the protocol and "://", the host name if one exists, and ":" followed by a port number if a port is present and differs from the default port for the given protocol. Examples of typical origins are https://example.org (implying port 443), http://example.net (implying port 80), and http://example.com:8080. Note that this origin is not guaranteed to be the current or future origin of that window, which might have been navigated to a different location since postMessage was called.
+
source
+
A reference to the window object that sent the message; you can use this to establish two-way communication between two windows with different origins.
+
+ +

Preocupações de segurança

+ +

If you do not expect to receive messages from other sites, do not add any event listeners for message events. This is a completely foolproof way to avoid security problems.

+ +

If you do expect to receive messages from other sites, always verify the sender's identity using the origin and possibly source properties. Any window (including, for example, http://evil.example.com) can send a message to any other window, and you have no guarantees that an unknown sender will not send malicious messages. Having verified identity, however, you still should always verify the syntax of the received message. Otherwise, a security hole in the site you trusted to send only trusted messages could then open a cross-site scripting hole in your site.

+ +

Always specify an exact target origin, not *, when you use postMessage to send data to other windows. A malicious site can change the location of the window without your knowledge, and therefore it can intercept the data sent using postMessage.

+ +

Exemplo

+ +
/*
+ * In window A's scripts, with A being on <http://example.com:8080>:
+ */
+
+var popup = window.open(...popup details...);
+
+// When the popup has fully loaded, if not blocked by a popup blocker:
+
+// This does nothing, assuming the window hasn't changed its location.
+popup.postMessage("The user is 'bob' and the password is 'secret'",
+                  "https://secure.example.net");
+
+// This will successfully queue a message to be sent to the popup, assuming
+// the window hasn't changed its location.
+popup.postMessage("hello there!", "http://example.com");
+
+function receiveMessage(event)
+{
+  // Do we trust the sender of this message?  (might be
+  // different from what we originally opened, for example).
+  if (event.origin !== "http://example.com")
+    return;
+
+  // event.source is popup
+  // event.data is "hi there yourself!  the secret response is: rheeeeet!"
+}
+window.addEventListener("message", receiveMessage, false);
+
+ +
/*
+ * In the popup's scripts, running on <http://example.com>:
+ */
+
+// Called sometime after postMessage is called
+function receiveMessage(event)
+{
+  // Do we trust the sender of this message?
+  if (event.origin !== "http://example.com:8080")
+    return;
+
+  // event.source is window.opener
+  // event.data is "hello there!"
+
+  // Assuming you've verified the origin of the received message (which
+  // you must do in any case), a convenient idiom for replying to a
+  // message is to call postMessage on event.source and provide
+  // event.origin as the targetOrigin.
+  event.source.postMessage("hi there yourself!  the secret response " +
+                           "is: rheeeeet!",
+                           event.origin);
+}
+
+window.addEventListener("message", receiveMessage, false);
+
+ +

Notas

+ +

Any window may access this method on any other window, at any time, regardless of the location of the document in the window, to send it a message. Consequently, any event listener used to receive messages must first check the identity of the sender of the message, using the origin and possibly source properties. This cannot be overstated: Failure to check the origin and possibly source properties enables cross-site scripting attacks.

+ +

As with any asynchronously-dispatched script (timeouts, user-generated events), it is not possible for the caller of postMessage to detect when an event handler listening for events sent by postMessage throws an exception.

+ +

The value of the origin property of the dispatched event is not affected by the current value of document.domain in the calling window.

+ +

For IDN host names only, the value of the origin property is not consistently Unicode or punycode; for greatest compatibility check for both the IDN and punycode values when using this property if you expect messages from IDN sites. This value will eventually be consistently IDN, but for now you should handle both IDN and punycode forms.

+ +

The value of the origin property when the sending window contains a javascript: or data: URL is the origin of the script that loaded the URL.

+ +

Utilizar window.postMessage nas extensões {{Non-standard_inline}}

+ +

window.postMessage is available to JavaScript running in chrome code (e.g., in extensions and privileged code), but the source property of the dispatched event is always null as a security restriction. (The other properties have their expected values.)

+ +

It is not possible for content or web context scripts to specify a targetOrigin to communicate directly with an extension (either the background script or a contet script).  Web or content scripts can use window.postMessage with a targetOrigin of "*" to broadcast to every listener, but this is discouraged, since an extension cannot be certain the origin of such messages, and other listeners (including those you do not control) can listen in.

+ +

Content scripts should use runtime.sendMessage to communicate with the background script.  Web context scripts can use custom events to communicate with content scripts (with randomly generated event names, if needed, to prevent snooping from the guest page).

+ +

Lastly, posting a message to a page at a file: URL currently requires that the targetOrigin argument be "*". file:// cannot be used as a security restriction; this restriction may be modified in the future.

+ +

Especificacações

+ + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('HTML WHATWG', "web-messaging.html#dom-window-postmessage", "postMessage()")}}{{Spec2('HTML WHATWG')}} 
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico1.0{{CompatVersionUnknown}}{{CompatGeckoDesktop(6.0)}}[1]
+ {{CompatGeckoDesktop(8.0)}}[2]
8.0[3]
+ 10.0[4]
9.54.0
transfer argument{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop(20.0)}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeAndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop(6.0)}}[1]
+ {{CompatGeckoDesktop(8.0)}}[2]
{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}[5]
transfer argument{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(20.0)}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Prior to Gecko 6.0 {{geckoRelease("6.0")}}, the message parameter must be a string. Starting in Gecko 6.0 {{geckoRelease("6.0")}}, the message parameter is serialized using the structured clone algorithm. This means you can pass a broad variety of data objects safely to the destination window without having to serialize them yourself.

+ +

[2] Gecko 8.0 introduced support for sending {{domxref("File")}} and {{domxref("FileList")}} objects between windows. This is only allowed if the recipient's principal is contained within the sender's principal for security reasons.

+ +

[3] IE8 and IE9 only support it for {{HTMLElement("frame")}} and {{HTMLElement("iframe")}}.

+ +

[4] IE10 has important limitations: see this article for details.

+ +

[5] Due to security reasons, to work properly on Safari, use construction with document.getElementId('your-frame').contentWindow

+ +

Consulte também

+ + + +
+ + + + + +
diff --git a/files/pt-pt/web/api/worker/index.html b/files/pt-pt/web/api/worker/index.html new file mode 100644 index 0000000000..cdeee23a8a --- /dev/null +++ b/files/pt-pt/web/api/worker/index.html @@ -0,0 +1,270 @@ +--- +title: Worker +slug: Web/API/Worker +translation_of: Web/API/Worker +--- +

{{APIRef("Web Workers API")}}

+ +

A interface do Worker da API de Workers da Web representa uma tarefa em segundo palno que pode ser criada facilmente e pode enviar mensagens de volta para o seu criador. Criar um worker é tão simples como chamar o criador de Worker() e especificar um script para ser executado na sequência do worker.

+ +

Os workers podem, por sua vez, gerar novos workers enquanto esses workers estiverem alojados dentro da mesma origem como a página original (Nota: os workers integrados não estão atualmente implementados no Blink).  Em adição os workers poderão utilizar XMLHttpRequest para I/O rede, com a estipulação que a responseXML e os atributos channel no XMLHttpRequest retornam sempre null.

+ +

Nem todas as interfaces e funções estão disposníveis para o script associado com um Worker.

+ +

No Firefox, se quiser utilziar os workers nas extensões e pretender ter acesso a js-ctypes, então deverá utilizar o objeto {{ domxref("ChromeWorker") }}.

+ +

Criadores

+ +
+
{{domxref("Worker.Worker", "Worker()")}}
+
Creates a dedicated web worker that executes the script at the specified URL. Workers can also be constructed using Blobs.
+
+ +

Propriedades

+ +

Inherits properties from its parent, {{domxref("EventTarget")}}, and implements properties from {{domxref("AbstractWorker")}}.

+ +

Manipuladores de evento

+ +
+
{{domxref("AbstractWorker.onerror")}}
+
An {{ domxref("EventListener") }} called whenever an {{domxref("ErrorEvent")}} of type error bubbles through to the worker. This is inherited from {{domxref("AbstractWorker")}}.
+
{{domxref("Worker.onmessage")}}
+
An {{ domxref("EventListener") }} called whenever a {{domxref("MessageEvent")}} of type message bubbles through the worker — i.e. when a message is sent to the parent document from the worker via {{domxref("DedicatedWorkerGlobalScope.postMessage")}}. The message is stored in the event's {{domxref("MessageEvent.data", "data")}} property.
+
{{domxref("Worker.onmessageerror")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("messageerror")}} event is raised.
+
+ +
+
+ +

Métodos

+ +

Inherits methods from its parent, {{domxref("EventTarget")}}, and implements methods from {{domxref("AbstractWorker")}}.

+ +
+
{{domxref("Worker.postMessage()")}}
+
Sends a message — which can consist of any JavaScript object — to the worker's inner scope.
+
{{domxref("Worker.terminate()")}}
+
Immediately terminates the worker. This does not offer the worker an opportunity to finish its operations; it is simply stopped at once. ServiceWorker instances do not support this method.
+
+ +

Exemplo

+ +

The following code snippet shows creation of a {{domxref("Worker")}} object using the {{domxref("Worker.Worker", "Worker()")}} constructor and usage of the object:

+ +
var myWorker = new Worker('worker.js');
+var first = document.querySelector('#number1');
+var second = document.querySelector('#number2');
+
+first.onchange = function() {
+  myWorker.postMessage([first.value,second.value]);
+  console.log('Message posted to worker');
+}
+ +

For a full example, see ourBasic dedicated worker example (run dedicated worker).

+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('HTML WHATWG', "#worker", "Worker")}}{{Spec2('HTML WHATWG')}} 
+ +

Compatibilidade de navegador

+ +

Support varies for different types of workers. See each worker type's page for specifics.

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support4{{CompatVersionUnknown}}3.510.010.64
Constructor name option{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop(55)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
onmessageerror60{{CompatUnknown}}{{CompatGeckoDesktop(57)}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support4.4{{CompatVersionUnknown}}3.510.011.55.1{{CompatUnknown}}
Constructor name option{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(55)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
onmessageerror60{{CompatUnknown}}{{CompatGeckoMobile(57)}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Cross-origin worker error behaviour

+ +

In earlier browser versions, trying to load a cross-origin worker script threw a SecurityError; in newer browsers an {{event("error")}} event is thrown instead due to a spec change. Find out more information on how to deal with this in Loading cross-origin worker now fires error event instead of throwing; worker in sandboxed iframe no longer allowed.

+ +

Consultar também

+ + + +
+ + + + + +
diff --git a/files/pt-pt/web/api/xmlhttprequest/index.html b/files/pt-pt/web/api/xmlhttprequest/index.html new file mode 100644 index 0000000000..3e5489f088 --- /dev/null +++ b/files/pt-pt/web/api/xmlhttprequest/index.html @@ -0,0 +1,174 @@ +--- +title: XMLHttpRequest +slug: Web/API/XMLHttpRequest +tags: + - AJAX + - API + - HTTP + - Interface + - Referencia + - Web + - XHR +translation_of: Web/API/XMLHttpRequest +--- +
{{APIRef("XMLHttpRequest")}}
+ +

Utilize os objetos XMLHttpRequest (XHR) para interagir com os servidores. Pode obter os dados de um URL sem ter que recarregar toda a página. Isto permite que uma página da Web atualize apenas parte da mesma, sem interromper o que o utilizador está a fazer. XMLHttpRequest é totalmente utilizado na programação Ajax.

+ +

{{InheritanceDiagram}}

+ +
História
+ +

XMLHttpRequest was originally designed by Microsoft around 1999 and later adopted by Mozilla, Apple, and Google. Since October 2014, it has been standardized at the WHATWG, together with the new promise-based {{domxref("WindowOrWorkerGlobalScope.fetch()", "fetch()")}} method.

+ +

Despite its name, XMLHttpRequest can be used to retrieve any type of data, not just XML, and it supports protocols other than HTTP (including file and ftp).

+ +

Constructor

+ +
+
{{domxref("XMLHttpRequest.XMLHttpRequest", "XMLHttpRequest()")}}
+
The constructor initializes an XMLHttpRequest. It must be called before any other method calls.
+
+ +

Propriedades

+ +

This interface also inherits properties of {{domxref("XMLHttpRequestEventTarget")}} and of {{domxref("EventTarget")}}.

+ +
+
{{domxref("XMLHttpRequest.onreadystatechange")}}
+
An {{domxref("EventHandler")}} that is called whenever the readyState attribute changes.
+
{{domxref("XMLHttpRequest.readyState")}} {{readonlyinline}}
+
Returns an unsigned short, the state of the request.
+
{{domxref("XMLHttpRequest.response")}} {{readonlyinline}}
+
Returns an {{domxref("ArrayBuffer")}}, {{domxref("Blob")}}, {{domxref("Document")}}, JavaScript object, or a {{domxref("DOMString")}}, depending on the value of {{domxref("XMLHttpRequest.responseType")}}. that contains the response entity body.
+
{{domxref("XMLHttpRequest.responseText")}} {{readonlyinline}}
+
Returns a {{domxref("DOMString")}} that contains the response to the request as text, or null if the request was unsuccessful or has not yet been sent.
+
{{domxref("XMLHttpRequest.responseType")}}
+
Is an enumerated value that defines the response type.
+
{{domxref("XMLHttpRequest.responseURL")}} {{readonlyinline}}
+
Returns the serialized URL of the response or the empty string if the URL is null.
+
{{domxref("XMLHttpRequest.responseXML")}} {{readonlyinline}}
+
Returns a {{domxref("Document")}} containing the response to the request, or null if the request was unsuccessful, has not yet been sent, or cannot be parsed as XML or HTML. Not available in workers.
+
{{domxref("XMLHttpRequest.status")}} {{readonlyinline}}
+
Returns an unsigned short with the status of the response of the request.
+
{{domxref("XMLHttpRequest.statusText")}} {{readonlyinline}}
+
Returns a {{domxref("DOMString")}} containing the response string returned by the HTTP server. Unlike {{domxref("XMLHTTPRequest.status")}}, this includes the entire text of the response message ("200 OK", for example).
+
+ +
+

Nota: via HTTP/2 specification (8.1.2.4 Response Pseudo-Header Fields), HTTP/2 does not define a way to carry the version or reason phrase that is included in an HTTP/1.1 status line.

+
+ +
+
{{domxref("XMLHttpRequest.timeout")}}
+
Is an unsigned long representing the number of milliseconds a request can take before automatically being terminated.
+
{{domxref("XMLHttpRequestEventTarget.ontimeout")}}
+
Is an {{domxref("EventHandler")}} that is called whenever the request times out. {{gecko_minversion_inline("12.0")}}
+
{{domxref("XMLHttpRequest.upload")}} {{readonlyinline}}
+
Is an {{domxref("XMLHttpRequestUpload")}}, representing the upload process.
+
{{domxref("XMLHttpRequest.withCredentials")}}
+
Is a {{domxref("Boolean")}} that indicates whether or not cross-site Access-Control requests should be made using credentials such as cookies or authorization headers.
+
+ +

Proriedades não padrão

+ +
+
{{domxref("XMLHttpRequest.channel")}}{{ReadOnlyInline}}
+
Is a {{Interface("nsIChannel")}}. The channel used by the object when performing the request.
+
{{domxref("XMLHttpRequest.mozAnon")}}{{ReadOnlyInline}}
+
Is a boolean. If true, the request will be sent without cookie and authentication headers.
+
{{domxref("XMLHttpRequest.mozSystem")}}{{ReadOnlyInline}}
+
Is a boolean. If true, the same origin policy will not be enforced on the request.
+
{{domxref("XMLHttpRequest.mozBackgroundRequest")}}
+
Is a boolean. It indicates whether or not the object represents a background service request.
+
{{domxref("XMLHttpRequest.mozResponseArrayBuffer")}}{{gecko_minversion_inline("2.0")}} {{obsolete_inline("6")}} {{ReadOnlyInline}}
+
Is an ArrayBuffer. The response to the request, as a JavaScript typed array.
+
{{domxref("XMLHttpRequest.multipart")}}{{obsolete_inline("22")}}
+
This Gecko-only feature, a boolean, was removed in Firefox/Gecko 22. Please use Server-Sent Events, Web Sockets, or responseText from progress events instead.
+
+ +

Manipuladores de evento

+ +

onreadystatechange as a property of the XMLHttpRequest instance is supported in all browsers.

+ +

Since then, a number of additional event handlers were implemented in various browsers (onload, onerror, onprogress, etc.). These are supported in Firefox. In particular, see nsIXMLHttpRequestEventTarget and Using XMLHttpRequest.

+ +

More recent browsers, including Firefox, also support listening to the XMLHttpRequest events via standard addEventListener APIs in addition to setting on* properties to a handler function.

+ +

Métodos

+ +
+
{{domxref("XMLHttpRequest.abort()")}}
+
Aborts the request if it has already been sent.
+
{{domxref("XMLHttpRequest.getAllResponseHeaders()")}}
+
Returns all the response headers, separated by CRLF, as a string, or null if no response has been received.
+
{{domxref("XMLHttpRequest.getResponseHeader()")}}
+
Returns the string containing the text of the specified header, or null if either the response has not yet been received or the header doesn't exist in the response.
+
{{domxref("XMLHttpRequest.open()")}}
+
Initializes a request. This method is to be used from JavaScript code; to initialize a request from native code, use openRequest() instead.
+
{{domxref("XMLHttpRequest.overrideMimeType()")}}
+
Overrides the MIME type returned by the server.
+
{{domxref("XMLHttpRequest.send()")}}
+
Sends the request. If the request is asynchronous (which is the default), this method returns as soon as the request is sent.
+
{{domxref("XMLHttpRequest.setRequestHeader()")}}
+
Sets the value of an HTTP request header. You must call setRequestHeader()after open(), but before send().
+
+ +

Métodos não padrão

+ +
+
{{domxref("XMLHttpRequest.init()")}}
+
Initializes the object for use from C++ code.
+
+ +
Aviso: este método não deve ser chamado do JavaScript.
+ +
+
{{domxref("XMLHttpRequest.openRequest()")}}
+
Initializes a request. This method is to be used from native code; to initialize a request from JavaScript code, use open() instead. See the documentation for open().
+
{{domxref("XMLHttpRequest.sendAsBinary()")}}{{deprecated_inline()}}
+
A variant of the send() method that sends binary data.
+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('XMLHttpRequest')}}{{Spec2('XMLHttpRequest')}}Live standard, latest version
+ +

Compatibilidade de navegador

+ + + +
{{Compat("api.XMLHttpRequest")}}
+ +

Consulte também

+ + diff --git a/files/pt-pt/web/componentes_web/index.html b/files/pt-pt/web/componentes_web/index.html new file mode 100644 index 0000000000..3a0dd68ffd --- /dev/null +++ b/files/pt-pt/web/componentes_web/index.html @@ -0,0 +1,226 @@ +--- +title: Componentes da Web +slug: Web/Componentes_Web +tags: + - Artigo da Web + - Componentes + - Componentes da Web + - Desenvolvimento da Web + - Importações HTML + - JavaScript + - Landing + - Modelo + - Resumo + - Sinopse + - elementos personalizados + - shadow dom + - slot +translation_of: Web/Web_Components +--- +
{{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/@font-face/index.html b/files/pt-pt/web/css/@font-face/index.html new file mode 100644 index 0000000000..8a150d736c --- /dev/null +++ b/files/pt-pt/web/css/@font-face/index.html @@ -0,0 +1,143 @@ +--- +title: '@font-face' +slug: Web/CSS/@font-face +translation_of: Web/CSS/@font-face +--- +

{{ CSSRef() }}

+ +

Resumo

+ +

@font-face permite que autores especifiquem fontes online para exibir texto em suas páginas web. Permitindo autores a proporcionar suas próprias fontes, @font-face elimina a necessidade de depender do limitado número de fontes que os usuários tem instalado em seus computadores.

+ +

Sintaxe

+ +
@font-face {
+  font-family: <a-remote-font-name>;
+  src: <source> [,<source>]*;
+  [font-weight: <weight>];
+  [font-style: <style>];
+}
+
+ +

Valores

+ +
+
<a-remote-font-name> 
+
Especifica um nome para a fonte que será usado como valor de font-face na propriedade font.
+
<source> 
+
URL para a localização remota do arquivo da fonte ou o nome da fonte no computador do usuário na forma local("Nome da Font").
+
<weight> 
+
Um valor para a espessura da fonte (font weight (en)).
+
<style> 
+
Um valor para o estilo da fonte (font style (en)).
+
+ +

Você pode especificar uma fonte local no computador do usuário através do nome, usando a sintaxe local(). Se esta fonte não for encontrada, outras fontes serão tentadas até que uma seja encontrada.

+ +

Formatos de fontes suportados

+ + + +

Exemplos

+ +

Este simples exemplo especifica uma fonte baixável para uso, aplicando-a ao corpo do documento.

+ +

Ver amostra

+ +
<html>
+<head>
+  <title>Web Font Sample</title>
+  <style type="text/css" media="screen, print">
+    @font-face {
+      font-family: "Bitstream Vera Serif Bold";
+      src: url("http://developer.mozilla.org/@api/deki/files/2934/=VeraSeBd.ttf");
+    }
+
+    body { font-family: "Bitstream Vera Serif Bold", serif }
+  </style>
+</head>
+<body>
+  This is Bitstream Vera Serif Bold.
+</body>
+</html>
+
+ +

Neste exemplo, a cópia local do usuário de "Helvetica Neue Bold" é usada; se o usuário não possuir a fonte instalada (dois diferentes nomes são tentados), então, a fonte baixável, chamada "MgOpenModernaBold.ttf" é usada em seu lugar:

+ +
@font-face {
+  font-family: MyHelvetica;
+  src: local("Helvetica Neue Bold"),
+  local("HelveticaNeue-Bold"),
+  url(MgOpenModernaBold.ttf);
+  font-weight: bold;
+}
+
+ +

Notas

+ + + +

Compatibilidade com navegadores

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NavegadorVersão mais antigaSuporte a
Internet Explorer4.0Somente fontes OpenType embutidas
Firefox (Gecko)3.5 (1.9.1)Somente fontes TrueType e OpenType
3.6 (1.9.2)Formato de fonte web aberta (WOFF)
Opera10.0Somente fontes TrueType e OpenType
Safari (WebKit)3.1 (525)Somente fontes TrueType e OpenType
+ +

Veja também MSDN Microsoft library @font-face (EN).

+ +

Especificações

+ + + +

Veja também

+ + diff --git a/files/pt-pt/web/css/@import/index.html b/files/pt-pt/web/css/@import/index.html new file mode 100644 index 0000000000..b67776898e --- /dev/null +++ b/files/pt-pt/web/css/@import/index.html @@ -0,0 +1,53 @@ +--- +title: '@import' +slug: Web/CSS/@import +tags: + - At-rule + - CSS + - Referencia + - Referencia_CSS + - import +translation_of: Web/CSS/@import +--- +

{{ CSSRef() }}

+ +

Resumo

+ +

@import é utilizado para importar regras de estilo de outros folhas de estilo.

+ +

Sintaxe

+ +
@import "url";
+@import "url"media1,media2,...;
+@import url("url");
+@import url("url")media1;
+
+ +

Notas

+ +

De modo que agentes do usuário possam evitar recuperar recursos para tipos não suportados de mídia, autores podem especificar regras @import dependentes de mídia. A importação destas condicionais especifica separado por vírgulas os tipos de mídia depois da URL. No all para o médio tem o mesmo efeito.

+ +

Exemplos

+ +
@import url("fineprint.css") print;
+@import url("bluish.css") projection, tv;
+
+ +

Especificações

+ + + +

Compatibilidade com navegadores

+ +

Veja também

+ +

{{ Cssxref("@media") }}, {{ Cssxref("@font-face") }}, {{ Cssxref("@import") }}

+ +

Categorias

+ +

Interwiki Language Links

+ +

{{ languages( { "en": "en/CSS/@import", "fr": "fr/CSS/@import", "pl": "pl/CSS/@import" } ) }}

diff --git a/files/pt-pt/web/css/@media/index.html b/files/pt-pt/web/css/@media/index.html new file mode 100644 index 0000000000..959cc3c59f --- /dev/null +++ b/files/pt-pt/web/css/@media/index.html @@ -0,0 +1,276 @@ +--- +title: '@media' +slug: Web/CSS/@media +tags: + - CSS + - Referencia + - Referencia_CSS +translation_of: Web/CSS/@media +--- +

{{ CSSRef() }}

+ +

A regra "at" @media de CSS permite aplicar parte de uma folha de estilos com a condição definida por uma ou mais consultas de média.

+ +

Pode utilizar-se tanto no início do código como dentro de qualquer outra regra "at" condicional.

+ +
+

Nota: Em JavaScript, a funcionalidade desta regra está disponível através da interface {{domxref("CSSMediaRule")}} do modelo/objeto CSS.

+
+ +

Sintaxe

+ +
/* No nível mais abrangente do código */
+@media screen and (min-width: 900px) {
+  article {
+    padding: 1rem 3rem;
+  }
+}
+
+/* Dentro de outra regra-"at" condicional */
+@supports (display: flex) {
+  @media screen and (min-width: 900px) {
+    article {
+      display: flex;
+    }
+  }
+}
+ +

Para aprofundar a sintaxe de consultas de média, por favor leia Utilizar consultas de média.

+ +

Tipos de média

+ +
+
all (todos)
+
Destinado para todos os dispositivos.
+
print (impressão)
+
Destinado para material paginado e para documentos visualizados no ecrã no modo de pré-visualizar impressão. Por favor, consulte a secção de média paginada, e a secção de média do tutorial de Como Começar para informação sobre a formatação de problemas que são específicos para a média paginada.
+
screen (ecrã)
+
Destinado primariamente para os ecrãs de computador a cores.
+
speech (elocução)
+
+

Pretendido para sintetizadores de fala. Nota: CSS2 tem um tipo de mídia similar chamado 'aural' para esta proposta. Veja o apêndice em folhas de estilo aural para detalhes.

+
+
+ +

Grupos de Média

+ +
+

Nota: Esta secção aplica-se a CSS 2.1. Há vários tipos de média, introduzidos nas especificações do CSS2.1 e Media Queries 3, que foram descontinuados, como ttytvprojectionhandheldbrailleembossed, and aural. O tipo aural foi substituído pelo speech, que é semelhante.

+
+ +

Tipos de média são também parte de diferentes grupos de média. A seguinte tabela indica que tipos estão em cada grupo.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Grupos
Tiposcontinuouspagedvisualaudiospeechtactilegridbitmapinteractivestatic
brailleXXXXX
embossedXXXX
handheldXXXXXXXXX
printXXXX
projectionXXXX
screenXXXXXX
auralXXXX
ttyXXXXX
tvXXXXXXX
+ +

Exemplos

+ +
  @media print {
+    body { font-size: 10pt }
+  }
+  @media screen {
+    body { font-size: 13px }
+  }
+  @media screen, print {
+    body { line-height: 1.2 }
+  }
+
+ +

Questões de acessibilidade

+ +

Para comodidade das pessoas que ampliam o tamanho do texto, deve-se utilizar medidas em em na definição de {{cssxref("<length>")}}. Esta medida funciona melhor do que px quando o utilizar muda o tamanho do texto no navegador.

+ +

Considere usar consulta de média Level 4 (Nível 4) para melhorar experiência de utilização. Por exemplo, prefers-reduced-motion para detetar se o utilizador pediu ao sistema para minimizar a quantidade de animaçõe ou movimentos.

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('CSS5 Media Queries', '#at-media5', '@media')}}{{Spec2('CSS5 Media Queries')}}Reinstituída consultas de média light-levelinverted-colors e consultas média personalizadas, as quais foram removidas do Level 4 (Nível 4).
+ Adicionados recursos de média prefers-reduced-motionprefers-reduced-transparencyprefers-contrast, e prefers-color-scheme.
{{SpecName('CSS3 Conditional', '#at-media', '@media')}}{{Spec2('CSS3 Conditional')}}Definida sintaxe básica da regra @media.
{{SpecName('CSS4 Media Queries', '#media', '@media')}}{{Spec2('CSS4 Media Queries')}} +

Adicionados recursos média scriptingpointerhoverupdateoverflow-block, e overflow-inline.
+ Descontinuação de todos os tipos de média excepto screenprintspeech, e all.
+ Tornou a sintaxe mais flexível com adição, entre outras coisas, da palavra-chave or.

+
{{SpecName('CSS3 Media Queries', '#media0', '@media')}}{{Spec2('CSS3 Media Queries')}}Sem alterações.
{{SpecName('CSS2.1', 'media.html#at-media-rule', '@media')}}{{Spec2('CSS2.1')}}Definição inicial.
+ +

== Compatibilidade com navegadores ==

+ +

Consulte também

+ + + +

{{ languages( { "en": "en/CSS/@media", "fr": "fr/CSS/@media", "pl": "pl/CSS/@media" } ) }}

diff --git a/files/pt-pt/web/css/_colon_after/index.html b/files/pt-pt/web/css/_colon_after/index.html new file mode 100644 index 0000000000..f59fbcd5dd --- /dev/null +++ b/files/pt-pt/web/css/_colon_after/index.html @@ -0,0 +1,34 @@ +--- +title: ':after | ::after' +slug: 'Web/CSS/:after' +tags: + - Referencia_CSS +translation_of: 'Web/CSS/::after' +--- +

{{ 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 new file mode 100644 index 0000000000..5572a818ef --- /dev/null +++ b/files/pt-pt/web/css/_colon_before/index.html @@ -0,0 +1,63 @@ +--- +title: ':before | ::before' +slug: 'Web/CSS/:before' +tags: + - Referencia_CSS +translation_of: 'Web/CSS/::before' +--- +

{{ 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/at-rule/index.html b/files/pt-pt/web/css/at-rule/index.html new file mode 100644 index 0000000000..bbf7651358 --- /dev/null +++ b/files/pt-pt/web/css/at-rule/index.html @@ -0,0 +1,83 @@ +--- +title: Regra "At" +slug: Web/CSS/At-rule +tags: + - AT + - CSS + - Referencia + - Regra +translation_of: Web/CSS/At-rule +--- +
{{cssref}}
+ +

Uma regra "at" is a CSS statement beginning with an at sign, '@' (U+0040 COMMERCIAL AT), followed by an identifier and includes everything up to the next semi-colon, ';' (U+003B SEMICOLON), or the next CSS block, whichever comes first.

+ +
/* General structure */
+@IDENTIFIER (RULE);
+
+/* Example: tells browser to use UTF-8 character set */
+@charset "utf-8";
+ +

There are several at-rules, designated by their identifiers, each with a different syntax:

+ + + +

Regras de grupo condicionais

+ +

Much like the values of properties, each at-rule has a different syntax. Nevertheless, several of them can be grouped into a special category named conditional group rules. These statements share a common syntax and each of them can include nested statements—either rulesets or nested at-rules. Furthermore, they all convey a common semantic meaning—they all link some type of condition, which at any time evaluates to either true or false. If the condition evaluates to true, then all of the statements within the group will be applied.

+ +

Conditional group rules are defined in CSS Conditionals Level 3 and are:

+ + + +

Since each conditional group may also contain nested statements, there may be an unspecified amount of nesting.

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('CSS3 Conditional')}}{{Spec2('CSS3 Conditional')}}Initial definition
{{SpecName('Compat', '#css-at-rules', 'CSS At-rules')}}{{Spec2('Compat')}}Standardizes @-webkit-keyframes.
+ +

Consultar também:

+ + diff --git a/files/pt-pt/web/css/azimuth/index.html b/files/pt-pt/web/css/azimuth/index.html new file mode 100644 index 0000000000..24e469dc63 --- /dev/null +++ b/files/pt-pt/web/css/azimuth/index.html @@ -0,0 +1,72 @@ +--- +title: azimuth +slug: Web/CSS/azimuth +tags: + - Referencia_CSS +translation_of: Archive/Web/CSS/azimuth +--- +

{{ CSSRef() }}

+

Resumo

+

Em combinação com elevation, azimuth habilita diferentes fontes de áudio para serem posicionadas espacialmente para apresentações aurais. Isto é importante porque proporciona uma maneira natural de contar várias vozes a parte, como cada uma pode ser posicionada para originar em uma localização diferente no estágio de som. Saída estéreo produz um estágio de som lateral, enquanto instalações de fones de ouvido e microfones permitem um estágio tridimencional completo.

+ +

Sintaxe

+
azimuth: angle | [[ left-side | far-left | left |
+    center-left | center | center-right | right |
+    far-right | right-side ] || behind ] | leftwards |
+    rightwards | inherit
+
+

Valores

+
+
+ angle 
+
+ Posição de fonte audível é descrita como um ângulo dentro da faixa de -360deg até 360deg. O valor 0deg significa diretamente adiante do centro do estágio de som (este é o valor padrão). 90deg é para a direita, 180deg é atrás e 270deg ou -90deg é para a esquerda.
+
+

Image:Azimuth.png

+

Palavras-chave relativas a posição

+ +

Exemplos

+
h1   { azimuth: 30deg }
+td.a { azimuth: far-right }          /*  60deg */
+#12  { azimuth: behind far-right }   /* 120deg */
+p.comment { azimuth: behind }        /* 180deg */
+
+

Especificações

+ +

== Compatibilidade com navegadores == TBD (this might be abandoned in favour of a centralized compatibility chart)

+

Veja também

+

{{ Cssxref("elevation") }}

+

Categorias

+

Interwiki Language Links

+

{{ languages( { "en": "en/CSS/azimuth", "fr": "fr/CSS/azimuth", "pl": "pl/CSS/azimuth" } ) }}

diff --git a/files/pt-pt/web/css/background-attachment/index.html b/files/pt-pt/web/css/background-attachment/index.html new file mode 100644 index 0000000000..ca851ae58c --- /dev/null +++ b/files/pt-pt/web/css/background-attachment/index.html @@ -0,0 +1,140 @@ +--- +title: background-attachment +slug: Web/CSS/background-attachment +tags: + - Referencia_CSS +translation_of: Web/CSS/background-attachment +--- +

{{ CSSRef() }}

+ +

Resumo

+ +

Se um {{ Cssxref("background-image") }} é especificado, background-attachment determina se a posição da imagem é fixa na tela, ou rola junto com o bloco que a contém.

+ + + +

Sintaxe

+ +
background-attachment: scroll | fixed | inherit
+
+ +

Valores

+ +
+
scroll 
+
Se scroll é especificado, a imagem de fundo irá rolar na tela com o bloco de imagem que a contém.
+
fixed 
+
Se fixed é especificado, a imagem de fundo não rolará com o elemento que a contém, em vez disso, continua estacionária no mesmo lugar da tela.
+
+

Exemplos

+ +

Simple example

+ +

CSS

+ +
p {
+  background-image: url("https://mdn.mozillademos.org/files/12057/starsolid.gif");
+  background-attachment: fixed;
+}
+
+ +

HTML

+ +
<p>
+  There were doors all round the hall, but they were all locked; and when
+  Alice had been all the way down one side and up the other, trying every
+  door, she walked sadly down the middle, wondering how she was ever to
+  get out again.
+</p>
+ +

Result

+ +

{{EmbedLiveSample("Simple_example")}}

+ +

Multiple background image support

+ +

This property supports multiple background images. You can specify a different <attachment> for each background, separated by commas. Each image is matched with the corresponding attachment type, from first specified to last.

+ +

CSS

+ +
p {
+  background-image: url("https://mdn.mozillademos.org/files/12057/starsolid.gif"), url("https://mdn.mozillademos.org/files/12059/startransparent.gif");
+  background-attachment: fixed, scroll;
+  background-repeat: no-repeat, repeat-y;
+}
+ +

HTML

+ +
<p>
+  There were doors all round the hall, but they were all locked; and when
+  Alice had been all the way down one side and up the other, trying every
+  door, she walked sadly down the middle, wondering how she was ever to
+  get out again.
+
+  Suddenly she came upon a little three-legged table, all made of solid
+  glass; there was nothing on it except a tiny golden key, and Alice's
+  first thought was that it might belong to one of the doors of the hall;
+  but, alas! either the locks were too large, or the key was too small,
+  but at any rate it would not open any of them. However, on the second
+  time round, she came upon a low curtain she had not noticed before, and
+  behind it was a little door about fifteen inches high: she tried the
+  little golden key in the lock, and to her great delight it fitted!
+</p>
+ +

Result

+ +

{{EmbedLiveSample("Multiple_background_image_support")}}

+ +

Especificações

+ + + +

Compatibilidade com navegadores

+ + + + + + + + + + + + + + + + + + + + + + + + +
NavegadorVersão mais antiga
Internet Explorer4
Firefox1
Netscape6
Opera3.5
+ +

Veja também

+ +

{{ Cssxref("background") }}, {{ Cssxref("background-attachment") }}, {{ Cssxref("background-color") }}, {{ Cssxref("background-image") }}, {{ Cssxref("background-position") }}, {{ Cssxref("background-repeat") }}

+ +

Categorias

+ +

Interwiki Language Links

+ +

 

+ +

{{ languages( { "en": "en/CSS/background-attachment", "fr": "fr/CSS/background-attachment", "pl": "pl/CSS/background-attachment" } ) }}

diff --git a/files/pt-pt/web/css/background-color/index.html b/files/pt-pt/web/css/background-color/index.html new file mode 100644 index 0000000000..4d713de239 --- /dev/null +++ b/files/pt-pt/web/css/background-color/index.html @@ -0,0 +1,108 @@ +--- +title: background-color +slug: Web/CSS/background-color +tags: + - Referencia_CSS +translation_of: Web/CSS/background-color +--- +

{{CSSRef}}

+ +

Resumo

+ +

background-color configura a cor de fundo de um elemento, com qualquer valor de cor ou a palavra-chave transparent.

+ +

{{cssinfo}}

+ +

Sintaxe

+ +
background-color: color | transparent | inherit
+
+ +

Valores

+ +
+
color 
+
A cor pode ser especificada com um valor RGB hexadecimal, um valor RGB regular ou usando umas das palavras-chave pré-definidas.
+
transparent 
+
O valor padrão para background-color é transparent, o que significa que o elemento não tem cor própria, em vez disso ele exibe a cor do elemento de trás.
+
+ +

Exemplos

+ +

HTML

+ +
<div class="exampleone">
+ Lorem ipsum dolor sit amet, consectetuer
+</div>
+
+<div class="exampletwo">
+  Lorem ipsum dolor sit amet, consectetuer
+</div>
+
+<div class="examplethree">
+  Lorem ipsum dolor sit amet, consectetuer
+</div>
+ +

CSS

+ +
.exampleone {
+  background-color: teal;
+  color: white;
+}
+
+.exampletwo {
+  background-color: rgb(153,102,153);
+  color: rgb(255,255,204);
+}
+
+.examplethree {
+  background-color: #777799;
+  color: #FFFFFF;
+}
+
+ +

Result

+ +

{{EmbedLiveSample("Exemplos","200","150")}}

+ + +

Especificações

+ + + +

Compatibilidade com navegadores

+ + + + + + + + + + + + + + + + + + + + + + + + +
NavegadoresVersão mais antiga
Internet Explorer4.0
Firefox (Gecko)1.0 (1.0)
Opera3.5
Safari (WebKit)1.0 (85)
+ +

Veja também

+ + diff --git a/files/pt-pt/web/css/background-image/index.html b/files/pt-pt/web/css/background-image/index.html new file mode 100644 index 0000000000..fd513e19b1 --- /dev/null +++ b/files/pt-pt/web/css/background-image/index.html @@ -0,0 +1,131 @@ +--- +title: background-image +slug: Web/CSS/background-image +tags: + - CSS_1 + - CSS_2.1 + - CSS_3 + - Referencia_CSS +translation_of: Web/CSS/background-image +--- +

{{ CSSRef() }}

+ +

Resumo

+ +

A propriedade background-image configura a imagem de fundo para um elemento.

+ + + +

Sintaxe

+ +
background-image:uri | none | inherit
+
+ +

Valores

+ +
+
uri 
+
A localização da imagem de recurso para ser usada como imagem de fundo.
+
none 
+
Usado para especificar que um elemento não tem imagem de fundo.
+
+ +

Exemplos

+ +

Note that the star image is partially transparent and is layered over the cat image.

+ +

HTML

+ +
<div>
+    <p class="catsandstars">
+        This paragraph is full of cats<br />and stars.
+    </p>
+    <p>This paragraph is not.</p>
+    <p class="catsandstars">
+        Here are more cats for you.<br />Look at them!
+    </p>
+    <p>And no more.</p>
+</div>
+ +

CSS

+ +
pre, p {
+    font-size: 1.5em;
+    color: #FE7F88;
+    background-color: transparent;
+}
+
+div {
+  background-image: url("https://mdn.mozillademos.org/files/6457/mdn_logo_only_color.png");
+}
+
+p {
+  background-image: none;
+}
+
+.catsandstars {
+  background-image:  url("https://mdn.mozillademos.org/files/11991/startransparent.gif"),
+                     url("https://mdn.mozillademos.org/files/7693/catfront.png");
+  background-color: transparent;
+}
+
+ +

Result

+ +

{{EmbedLiveSample('Exemplos')}}

+ +

Notas

+ +

Desenvolvedores devem assegurar-se de especificar um {{ Cssxref("background-color") }} para ser usado se uma imagem não estiver disponível. Imagens de fundo são renderizadas sobre a cor de fundo.

+ +

Especificações

+ + + +

Compatibilidade com navegadores

+ + + + + + + + + + + + + + + + + + + + + + + + +
NavegadorVersão mais antiga
Internet Explorer4
Firefox1
Netscape4
Opera3.5
+ +

Veja também

+ +

{{ Cssxref("background") }}, {{ Cssxref("background-attachment") }}, {{ Cssxref("background-color") }}, {{ Cssxref("background-image") }}, {{ Cssxref("background-position") }}, {{ Cssxref("background-repeat") }}

+ +

Categorias

+ +

Interwiki Language Links

+ +

{{ languages( { "en": "en/CSS/background-image", "fr": "fr/CSS/background-image", "pl": "pl/CSS/background-image" } ) }}

diff --git a/files/pt-pt/web/css/background-position/index.html b/files/pt-pt/web/css/background-position/index.html new file mode 100644 index 0000000000..5445184e42 --- /dev/null +++ b/files/pt-pt/web/css/background-position/index.html @@ -0,0 +1,85 @@ +--- +title: background-position +slug: Web/CSS/background-position +tags: + - Referencia_CSS +translation_of: Web/CSS/background-position +--- +

+{{ CSSRef() }} +

+

Resumo

+

background-position configura a posição inicial de qualquer imagem de fundo que seja configurada. +

+ +

Sintaxe

+
background-position: [ [ <percentage> | <length> | left | center | right ] [ <percentage> | <length> | top | center | bottom ]? ] | [ [ left | center | right ] || [ top | center | bottom ] ] | inherit
+
+

Valores

+
<percentage> <percentage>
Com um par de valores de '0% 0%', o canto superior esquerdo da imagem é alinhado com o canto superior esquerdo do enchimento da borda da caixa. Um par de valores de '100% 100%' coloca o canto inferior direito da imagem no canto inferior direito da área de enchimento. Com um par de valores de '14% 84%', o ponto de 14% na horizontal e 84% na vertical da imagem é colocado no ponto 14% na horizontal e 84% na vertical da área de enchimento. +
<length> <length>
Com um par de valores de '2cm 1cm', o canto superior esquerdo da imagem é colocado 2cm para a direita e 1cm abaixo do canto superior esquerdo da área de enchimento. +
top left e left top
O mesmo que '0% 0%'. +
top, top center e center top
O mesmo que '50% 0%'. +
right top e top right
O mesmo que '100% 0%'. +
left, left center e center left
O mesmo que '0% 50%'. +
center e center center
O mesmo que '50% 50%'. +
right, right center e center right
O mesmo que '100% 50%'. +
bottom left e left bottom
O mesmo que '0% 100%'. +
bottom, bottom center e center bottom
O mesmo que '50% 100%'. +
bottom right e right bottom
O mesmo que '100% 100%'. +
+

Se somente um valor é especificado, então ele configura a posição horizontal, com a posição vertical em 50%. Caso contrário, o primeiro valor especifica a posição horizontal. Combinações são permitidas de valores de palavras-chave, comprimento ou porcentagens, mas se palavras-chave forem misturadas com outros valores, 'left' e 'right' podem somente ser usados como o primeiro valor, e 'top' e 'down' podem somente ser usados como o segundo valor. Posições negativas são permitidas. +

+

Exemplos

+
.exampleone {
+	background-image: url("logo.png");
+	background-position: top center;
+}
+
+.exampletwo {
+	background-image: url("logo.png");
+	background-position: 25% 75%;
+}
+
+.examplethree {
+	background-image: url("logo.png");
+	background-position: 2cm bottom;
+}
+
+.examplefour {
+	background-image: url("logo.png");
+	background-position: center 10%;
+}
+
+.examplefive {
+	background-image: url("logo.png");
+	background-position: 2cm 50%;
+}
+
+
+

== Notas == +

+

Especificações

+ +

Compatibilidade com navegadores

+ +
Navegador Versão mais antiga
Internet Explorer 4
Firefox 1
Netscape 6
Opera 3.5
+

Veja também

+

{{ Cssxref("background") }}, +{{ Cssxref("background-attachment") }}, +{{ Cssxref("background-color") }}, +{{ Cssxref("background-image") }}, +{{ Cssxref("background-position") }}, +{{ Cssxref("background-repeat") }} +

Categorias +

Interwiki Language Links +

{{ languages( { "en": "en/CSS/background-position", "fr": "fr/CSS/background-position", "pl": "pl/CSS/background-position" } ) }} diff --git a/files/pt-pt/web/css/background-repeat/index.html b/files/pt-pt/web/css/background-repeat/index.html new file mode 100644 index 0000000000..582f6f86f8 --- /dev/null +++ b/files/pt-pt/web/css/background-repeat/index.html @@ -0,0 +1,138 @@ +--- +title: background-repeat +slug: Web/CSS/background-repeat +tags: + - Referencia_CSS +translation_of: Web/CSS/background-repeat +--- +

{{ CSSRef() }}

+ +

Resumo

+ +

background-repeat specifies whether the image is repeated (tiled), and how.

+ + + +

Sintaxe

+ +
background-repeat: repeat | repeat-x | repeat-y | no-repeat | inherit
+
+ +

Valores

+ +
+
repeat
+
A imagem é repetida vertical e horizontalmente.
+
repeat-x
+
A imagem é repetida somente horizontalmente.
+
repeat-y
+
A imagem é repetida somente verticalmente.
+
no-repeat
+
A imagem não é repetida: somente uma cópia da imagem é desenhada.
+
+ + +

Exemplos

+ +

HTML

+ +
<ol>
+    <li>no-repeat
+        <div class="one">&nbsp;</div>
+    </li>
+    <li>repeat
+        <div class="two">&nbsp;</div>
+    </li>
+    <li>repeat-x
+        <div class="three">&nbsp;</div>
+    </li>
+    <li>repeat-y
+        <div class="four">&nbsp;</div>
+    </li>
+    <li>repeat-x, repeat-y (multiple images)
+        <div class="five">&nbsp;</div>
+    </li>
+</ol>
+ +

CSS

+ +
/* Shared for all DIVS in example */
+li {margin-bottom: 12px;}
+div {
+    background-image: url(https://mdn.mozillademos.org/files/12005/starsolid.gif);
+    width: 144px;
+    height: 84px;
+}
+
+/* background repeat CSS */
+.one {
+    background-repeat: no-repeat;
+}
+.two {
+    background-repeat: repeat;
+}
+.three {
+    background-repeat: repeat-x;
+}
+.four {
+    background-repeat: repeat-y;
+}
+
+/* Multiple images */
+.five {
+    background-image:  url(https://mdn.mozillademos.org/files/12005/starsolid.gif),
+                       url(https://developer.cdn.mozilla.net/media/redesign/img/favicon32.png);
+    background-repeat: repeat-x,
+                       repeat-y;
+    height: 144px;
+}
+ +

Result

+ +

In this example, each list item is matched with a different value of background-repeat.

+ +

{{EmbedLiveSample('Exemplos', 240, 360)}}

+ +

Compatibilidade com navegadores

+ + + + + + + + + + + + + + + + + + + + + + + + +
NavegadorVersão mais antiga
Internet Explorer4
Firefox1
Netscape4
Opera3.5
+ +

Veja também

+ +

{{ Cssxref("background") }}, {{ Cssxref("background-attachment") }}, {{ Cssxref("background-color") }}, {{ Cssxref("background-image") }}, {{ Cssxref("background-position") }}, {{ Cssxref("background-repeat") }}

+ +

Categorias

+ +

Interwiki Language Links

+ +

{{ languages( { "en": "en/CSS/background-repeat", "fr": "fr/CSS/background-repeat", "pl": "pl/CSS/background-repeat" } ) }}

diff --git a/files/pt-pt/web/css/background/index.html b/files/pt-pt/web/css/background/index.html new file mode 100644 index 0000000000..3118d1b239 --- /dev/null +++ b/files/pt-pt/web/css/background/index.html @@ -0,0 +1,117 @@ +--- +title: background +slug: Web/CSS/background +tags: + - Referencia_CSS +translation_of: Web/CSS/background +--- +

{{ CSSRef() }}

+ +

Introdução

+ +

A propriedade background é usada para ajustar os valores do fundo em um único lugar na folha de estilos. background pode ser usada com os seguintes valores adicionais: {{ Cssxref("background-attachment") }}, {{ Cssxref("background-color") }}, {{ Cssxref("background-image") }}, {{ Cssxref("background-position") }}, {{ Cssxref("background-repeat") }}.

+ + + +

Sintaxe

+ +
background: [background-color ||background-image ||background-repeat ||background-attachment ||background-position] |inherit]
+
+ +

Valores

+ +
+
background-color
+
Veja background-color.
+
background-image 
+
Veja background-image.
+
background-repeat 
+
Veja background-repeat.
+
background-attachment 
+
Veja background-attachment.
+
background-position 
+
Veja background-position.
+
+ +

Exemplos

+ +

HTML

+ +
<p class="topbanner">
+  Starry sky<br/>
+  Twinkle twinkle<br/>
+  Starry sky
+</p>
+<p class="warning">Here is a paragraph<p>
+ +

CSS

+ +
.warning {
+  background: red;
+}
+
+.topbanner {
+  background: url("https://mdn.mozillademos.org/files/11983/starsolid.gif") #00D repeat-y fixed;
+}
+
+ +

Result

+ +

{{EmbedLiveSample("Exemplos")}}

+ +

Notas

+ +

Sendo uma declaração válida, a propriedade background ajusta primeiramente o background (fundo) individual para seus valores iniciais, e depois, atribui então os valores especificados na declaração. Você não precisa definir um valor para cada uma das propriedades, apenas para aquelas que você deseja alterar os valores padrões.

+ +

Especificações

+ + + +

Compatibilidade com navegadores

+ + + + + + + + + + + + + + + + + + + + + + + + +
NavegadorVersão mais antiga
Internet Explorer4
Firefox1
Netscape6
Opera3.5
+ +

Veja também

+ +

{{ Cssxref("background") }}, {{ Cssxref("background-attachment") }}, {{ Cssxref("background-color") }}, {{ Cssxref("background-image") }}, {{ Cssxref("background-position") }}, {{ Cssxref("background-repeat") }}

+ +


+ Categorias

+ +

Interwiki Language Links

+ +

{{ languages( { "en": "en/CSS/background", "fr": "fr/CSS/background", "pl": "pl/CSS/background" } ) }}

diff --git a/files/pt-pt/web/css/border-bottom-color/index.html b/files/pt-pt/web/css/border-bottom-color/index.html new file mode 100644 index 0000000000..0a6c79941e --- /dev/null +++ b/files/pt-pt/web/css/border-bottom-color/index.html @@ -0,0 +1,110 @@ +--- +title: border-bottom-color +slug: Web/CSS/border-bottom-color +tags: + - Referencia_CSS +translation_of: Web/CSS/border-bottom-color +--- +

{{ CSSRef() }}

+ +

Resumo

+ +

border-bottom-color configura a cor da borda inferior de um elemento, com o nome da cor ou a palavra-chave transparent.

+ + + +

Sintaxe

+ +
border-bottom-color:color | transparent | inherit
+
+ +

Valores

+ +
+
color 
+
A cor pode ser especificada como um valor RGB hexadecimal, um valor RGB regular ou usando uma das palavras-chave de cor pré-definidas.
+
transparent 
+
O elemento não tem cor própria, dessa forma exibe a cor do elemento que fica atrás dele.
+
+ +

Propriedades relacionadas

+ + + +

Exemplos

+ +

View Live Examples

+ +
element {
+	width: 300px;
+        padding: 15px;
+        border-bottom-size: 1px;
+        border-bottom-style: solid;
+        border-bottom-color: #000;
+}
+
+
+ +

Notas

+ + + +

Especificações

+ + + +

Compatibilidade com navegadores

+ + + + + + + + + + + + + + + + + + + + + + + + +
NavegadorVersão mais antiga
Internet Explorer4
Firefox1
Netscape6
Opera3.5
+ +

 

+ +

Veja também

+ +

{{ Cssxref("border") }}, {{ Cssxref("border-bottom") }}, {{ Cssxref("border-bottom-style") }}, {{ Cssxref("border-bottom-width") }},

+ +

Categorias

+ +

Interwiki Language Links

+ +

{{ languages( { "en": "en/CSS/border-bottom-color", "fr": "fr/CSS/border-bottom-color", "pl": "pl/CSS/border-bottom-color" } ) }}

diff --git a/files/pt-pt/web/css/border-bottom-style/index.html b/files/pt-pt/web/css/border-bottom-style/index.html new file mode 100644 index 0000000000..be873908d9 --- /dev/null +++ b/files/pt-pt/web/css/border-bottom-style/index.html @@ -0,0 +1,94 @@ +--- +title: border-bottom-style +slug: Web/CSS/border-bottom-style +tags: + - Referencia_CSS +translation_of: Web/CSS/border-bottom-style +--- +

{{ CSSRef() }}

+ +

Resumo

+ +

border-bottom-style configura o estilo da linha da borda inferior de uma caixa.

+ + + +

Sintaxe

+ +
border-bottom-style: <border-style> | inherit
+
+ +

<border-style> Valores

+ +
+
none 
+
Sem borda.
+
hidden 
+
O mesmo que 'none', exceto em termos de conflitos na resolução de bordas para elementos de tabela.
+
dotted 
+
Série de pontos.
+
dashed 
+
Série de traços ou segmentos de linha.
+
solid 
+
Simples, reto, linha contínua.
+
double 
+
Duas linhas retas que adicionam uma quantidade de pixels definida por border-width.
+
groove 
+
Efeito entalhado.
+
ridge 
+
Contrário de 'groove'.
+
inset 
+
Faz a caixa aparecer em baixo relevo.
+
outset 
+
Contrário de 'inset'. Faz a caixa aparecer em alto relevo.
+
+ +

Propriedades relacionadas

+ + + +

Exemplos

+ +

View Live Examples

+ +
element {
+        border-bottom-size: 1px;
+        border-bottom-style: dotted;
+        border-bottom-color: #000;
+}
+
+ +

Notas

+ +

A menos que seja configurado um valor para border-style, sua borda não aparecerá, pois o valor padrão configurado é 'none'.

+ +

Especificações

+ + + +

== Compatibilidade com navegadores ==

+ +

Veja também

+ +

{{ Cssxref("border-bottom-style") }}, {{ Cssxref("border-bottom") }}, {{ Cssxref("border-bottom-color") }}, {{ Cssxref("border-bottom-width") }},

+ +

Categorias

+ +

Interwiki Language Links

+ +

{{ languages( { "en": "en/CSS/border-bottom-style", "fr": "fr/CSS/border-bottom-style", "pl": "pl/CSS/border-bottom-style" } ) }}

diff --git a/files/pt-pt/web/css/border-bottom-width/index.html b/files/pt-pt/web/css/border-bottom-width/index.html new file mode 100644 index 0000000000..299636a962 --- /dev/null +++ b/files/pt-pt/web/css/border-bottom-width/index.html @@ -0,0 +1,112 @@ +--- +title: border-bottom-width +slug: Web/CSS/border-bottom-width +tags: + - Referencia_CSS +translation_of: Web/CSS/border-bottom-width +--- +

{{ CSSRef() }}

+ +

Resumo

+ +

border-bottom-width configura a largura da borda inferior de uma caixa.

+ + + +

Sintaxe

+ +
border-bottom-width: <border-width> | inherit
+
+ +

Valores de <border-width>

+ +
+
thin 
+
Uma borda fina.
+
medium 
+
Uma borda média.
+
thick 
+
Uma borda grossa.
+
<length> 
+
A espessura da borda tem um valor explícito. Valores explícitos de borda não podem ser negativos.
+
<percentage> 
+
A espessura da borda tem um valor em porcentagem, porcentagens da largura do bloco em que está contida. Larguras explícitas de borda não podem ser negativos.
+
+ +

Nota: Um valor em também é suportado.

+ +

Propriedades relacionadas

+ + + +

 

+ +

Exemplos

+ +

View Live Examples

+ +
element {
+    border-bottom-width: thin;
+    border-bottom-style: solid;
+    border-bottom-color: #000;
+}
+
+ +

Especificações

+ + + +

Compatibilidade com navegadores

+ + + + + + + + + + + + + + + + + + + + + + + + +
NavegadorVersão mais antiga
Internet Explorer 
Firefox 
Netscape 
Opera 
+ +

 

+ +

Veja também

+ +

{{ Cssxref("border") }}, {{ Cssxref("border-bottom") }}, {{ Cssxref("border-bottom-width") }}, {{ Cssxref("border-bottom-style") }}, {{ Cssxref("border-bottom-color") }},

+ +

Categorias

+ +

Interwiki Language Links

+ +

{{ languages( { "en": "en/CSS/border-bottom-width", "fr": "fr/CSS/border-bottom-width", "pl": "pl/CSS/border-bottom-width" } ) }}

diff --git a/files/pt-pt/web/css/border-bottom/index.html b/files/pt-pt/web/css/border-bottom/index.html new file mode 100644 index 0000000000..08da201a5f --- /dev/null +++ b/files/pt-pt/web/css/border-bottom/index.html @@ -0,0 +1,109 @@ +--- +title: border-bottom +slug: Web/CSS/border-bottom +tags: + - Referencia_CSS +translation_of: Web/CSS/border-bottom +--- +

{{ CSSRef() }}

+ +

Resumo

+ +

A propriedade border-bottom é uma propriedadeshorthand que configura os valores de {{ Cssxref("border-bottom-color") }}, {{ Cssxref("border-bottom-style") }} e {{ Cssxref("border-bottom-width") }}. Estas propriedades descrevem a borda inferior de elementos.

+ + + +

Sintaxe

+ +
border-bottom: [ <border-width> || <border-style> || <border-color> ] |inherit
+
+ +

Valores

+ +
+
<border-width> 
+
Veja {{ Cssxref("border-bottom-width") }}.
+
<border-style> 
+
Veja {{ Cssxref("border-bottom-style") }}.
+
<border-color> 
+
Veja {{ Cssxref("border-bottom-color") }}.
+
+ +

Exemplos

+ +

View Live Examples

+ +
element {
+    border-bottom-width: 1px solid #000;
+}
+
+ +

Notas

+ +

Os três valores da propriedadeshorthand podem ser especificados em qualquer ordem e um ou dois deles podem ser omitidos.

+ +

Como com todas as propriedadesshorthand, border-bottom sempre configura os valores de todas as propriedades que ele pode configurar, ainda que elas não sejam especificadas. Ele configura as que não especificadas para os seus valores padrão. De maneira que:

+ +
  border-bottom-style: dotted;
+  border-bottom: thick green;
+ +

é realmente o mesmo que

+ +
  border-bottom-style: dotted;
+  border-bottom: none thick green;
+ +

e o valor de {{ Cssxref("border-bottom-style") }} dado antes border-bottom é ignorado.

+ +

Desde que o valor padrão de {{ Cssxref("border-bottom-style") }} seja none, não especificar o <border-style> torna o valor, o mesmo que a propriedade especifica na borda.

+ +

Especificações

+ + + +

Compatibilidade com navegadores

+ + + + + + + + + + + + + + + + + + + + + + + + +
NavegadorVersão mais antiga
Internet Explorer4
Firefox1
Netscape4
Opera3.5
+ +

Veja também

+ +

{{ Cssxref("border") }}, {{ Cssxref("border-bottom") }}, {{ Cssxref("border-bottom-width") }}, {{ Cssxref("border-bottom-style") }}, {{ Cssxref("border-bottom-color") }},

+ +

Categorias

+ +

Interwiki Language Links

+ +

{{ languages( { "en": "en/CSS/border-bottom", "fr": "fr/CSS/border-bottom", "pl": "pl/CSS/border-bottom" } ) }}

diff --git a/files/pt-pt/web/css/border-collapse/index.html b/files/pt-pt/web/css/border-collapse/index.html new file mode 100644 index 0000000000..0f1acaaf50 --- /dev/null +++ b/files/pt-pt/web/css/border-collapse/index.html @@ -0,0 +1,87 @@ +--- +title: border-collapse +slug: Web/CSS/border-collapse +tags: + - Referencia_CSS +translation_of: Web/CSS/border-collapse +--- +

{{ CSSRef() }}

+ +

Resumo

+ +

The border-collapse property is used to make the border collapse. This has a big influence on the look and style of the table cells. The rendering of table borders is divided into two categories in CSS2 - "collapsed" and "separated". This property specifies which border rendering mode to use. In the collapsed border model, adjacent table cells share borders. In the separated model, adjacent cells each have their own distinct borders (the distance between them given by the 'border-spacing' property.)

+ + + +

Sintaxe

+ +
border-collapse: value
+
+ +

Valores

+ + + +

Exemplos

+ +

View Live Examples

+ +
<table border="1" style="border-collapse: collapse" bordercolor="#111111" width="500">
+
+ +
<table border="1" style="border-collapse: separate" bordercolor="#111111" width="500">
+
+ +

Notas

+ +

In the "collapsed border" rendering model, the 'border-style' value of "inset" behaves like "groove", and "outset" behaves like "ridge." CSS2 specifies that the initial value for this property is "collapse", but CSS2.1 and Mozilla/Opera all state or behave such that the initial value is "separate."

+ +

Especificações

+ + + +

Compatibilidade com navegadores

+ + + + + + + + + + + + + + + + + + + + +
NavegadorVersão mais antiga
Internet Explorer5.5
Netscape7
Opera5
+ +

 

+ +

Veja também

+ +

{{ Cssxref("border-collapse") }}, {{ Cssxref("border-spacing") }}

+ +

Categorias

+ +

Interwiki Language Links

+ +

{{ languages( { "en": "en/CSS/border-collapse", "fr": "fr/CSS/border-collapse" } ) }}

diff --git a/files/pt-pt/web/css/border-color/index.html b/files/pt-pt/web/css/border-color/index.html new file mode 100644 index 0000000000..e97253bd58 --- /dev/null +++ b/files/pt-pt/web/css/border-color/index.html @@ -0,0 +1,116 @@ +--- +title: border-color +slug: Web/CSS/border-color +tags: + - Referencia_CSS +translation_of: Web/CSS/border-color +--- +

{{ CSSRef() }}

+ +

Resumo

+ +

A propriedade border-color é muito útil para ajustar a cor dos quatro lados da borda do elemento.

+ + + +

Sintaxe

+ +
border-color: [ <color> || transparent ]{1,4} | inherit
+
+ +

Valores

+ +
+
<color> 
+
A cor pode ser especificada como um valor RGB hexadecimal, um valor RGB regular ou usando uma das palavras-chave de cores pré-definidas.
+
+ +
+
transparent 
+
A borda não é desenhada, mas ainda continua ocupando espaço na página.
+
+ +

Até quatro valores podem ser fornecidos;

+ +

Se um valor de cor é fornecido, então todas as quatros bordas ficam daquela cor.
+ Se dois valores são fornecidos, as bordas inferior e superior utilizam-se do primeiro valor e as esquerda e direita do segundo valor.
+ Se três valores são fornecidos, o primeiro é para a borda superior, o segundo para a esquerda e direita e o terceiro para a inferior.
+ Se quatro valores são dados, o primeiro é para a borda superior, o segundo para a direita, o terceiro para a inferior e o quarto para a esquerda.

+ +

Exemplos

+ +

View Live Examples

+ +
element {
+  border-width: 1px;
+  border-style: solid;
+  border-color: black;
+}
+
+ +

Notas

+ +

No caso de querer ver a borda, você deve ajustar o {{ Cssxref("border-width") }} para um valor positivo e o {{ Cssxref("border-style") }} para algo visível.

+ +

Especificações

+ + + +

Compatibilidade com navegadores

+ + + + + + + + + + + + + + + + + + + + + + + + +
NavegadorVersão mais antiga
Internet Explorer4
Firefox1
Netscape4
Opera3.5
+ +

Extensões Mozilla

+ +

As seguintes Extensões da Mozilla ajustam os respectivos lados da borda para múltiplas cores para navegadores Gecko.

+ + + +

Veja também

+ +

{{ Cssxref("border") }}, {{ Cssxref("border-color") }}, {{ Cssxref("border-width") }}, {{ Cssxref("border-style") }}

+ +

Categorias

+ +

Interwiki Language Links

+ +

{{ languages( { "en": "en/CSS/border-color", "fr": "fr/CSS/border-color", "pl": "pl/CSS/border-color" } ) }}

diff --git a/files/pt-pt/web/css/border-left-color/index.html b/files/pt-pt/web/css/border-left-color/index.html new file mode 100644 index 0000000000..f358f01aa0 --- /dev/null +++ b/files/pt-pt/web/css/border-left-color/index.html @@ -0,0 +1,16 @@ +--- +title: border-left-color +slug: Web/CSS/border-left-color +tags: + - Referencia_CSS +translation_of: Web/CSS/border-left-color +--- +

+{{ CSSRef() }} +

+

Resumo

+

border-left-color configura a cor da borda esquerda de um elemento. +

Veja a propriedade border-bottom-color para mais informações. +

Categorias +

Interwiki Language Links +

{{ languages( { "en": "en/CSS/border-left-color", "fr": "fr/CSS/border-left-color", "pl": "pl/CSS/border-left-color" } ) }} diff --git a/files/pt-pt/web/css/border-left-style/index.html b/files/pt-pt/web/css/border-left-style/index.html new file mode 100644 index 0000000000..f482151b58 --- /dev/null +++ b/files/pt-pt/web/css/border-left-style/index.html @@ -0,0 +1,16 @@ +--- +title: border-left-style +slug: Web/CSS/border-left-style +tags: + - Referencia_CSS +translation_of: Web/CSS/border-left-style +--- +

+{{ CSSRef() }} +

+

Resumo

+

border-left-style configura o estilo da linha da borda esquerda de uma caixa. +

Veja a propriedade border-bottom-style para mais informações. +

Categorias +

Interwiki Language Links +

{{ languages( { "en": "en/CSS/border-left-style", "fr": "fr/CSS/border-left-style" } ) }} diff --git a/files/pt-pt/web/css/border-left-width/index.html b/files/pt-pt/web/css/border-left-width/index.html new file mode 100644 index 0000000000..caf87d5d71 --- /dev/null +++ b/files/pt-pt/web/css/border-left-width/index.html @@ -0,0 +1,16 @@ +--- +title: border-left-width +slug: Web/CSS/border-left-width +tags: + - Referencia_CSS +translation_of: Web/CSS/border-left-width +--- +

+{{ CSSRef() }} +

+

Resumo

+

border-left-width configura a largura da borda esquerda de um elemento. +

Veja a propriedade border-bottom-width para mais informações. +

Categorias +

Interwiki Language Links +

{{ languages( { "en": "en/CSS/border-left-width", "fr": "fr/CSS/border-left-width" } ) }} diff --git a/files/pt-pt/web/css/border-left/index.html b/files/pt-pt/web/css/border-left/index.html new file mode 100644 index 0000000000..e0cd0e9f6f --- /dev/null +++ b/files/pt-pt/web/css/border-left/index.html @@ -0,0 +1,50 @@ +--- +title: border-left +slug: Web/CSS/border-left +tags: + - Referencia_CSS +translation_of: Web/CSS/border-left +--- +

+{{ CSSRef() }} +

+

Resumo

+

A propriedade border-left é uma propriedade shorthand para configurar a largura, estilo e cor da borda esquerda de uma caixa. Esta propriedade pode ser usada para configurar um ou mais valores de {{ Cssxref("border-left-width") }}, {{ Cssxref("border-left-style") }} e {{ Cssxref("border-left-color") }}. Valores omitidos são configurados com o valor inicial. +

+ +

Sintaxe

+
border-left: [border-width || border-style || border-color | inherit] ;
+
+

Valores

+
border-width 
Veja {{ Cssxref("border-width") }}. +
border-style 
Veja {{ Cssxref("border-style") }}. +
border-color 
Veja {{ Cssxref("border-color") }}. +
+

Exemplos

+
element {
+    border-left: 1px solid #000;
+}
+
+

Notas

+

Se a regra não especificar uma cor de borda, a borda terá a cor especificada pela propriedade {{ Cssxref("color") }}. +

+

Especificações

+ +

Compatibilidade com navegadores

+ +
Navegador Versão mais antiga
Internet Explorer 4
Firefox 1
Netscape 4
Opera 3.5
+

Veja também

+

{{ Cssxref("border") }}, +{{ Cssxref("border-left") }} +

Categorias +

Interwiki Language Links +

{{ languages( { "en": "en/CSS/border-left", "fr": "fr/CSS/border-left", "pl": "pl/CSS/border-left" } ) }} diff --git a/files/pt-pt/web/css/border-right-color/index.html b/files/pt-pt/web/css/border-right-color/index.html new file mode 100644 index 0000000000..9a58ad9d69 --- /dev/null +++ b/files/pt-pt/web/css/border-right-color/index.html @@ -0,0 +1,16 @@ +--- +title: border-right-color +slug: Web/CSS/border-right-color +tags: + - Referencia_CSS +translation_of: Web/CSS/border-right-color +--- +

+{{ CSSRef() }} +

+

Resumo

+

border-right-color configura a cor da borda direita de um elemento. +

Veja a propriedade border-bottom-color para mais informações. +

Categorias +

Interwiki Language Links +

{{ languages( { "en": "en/CSS/border-right-color", "fr": "fr/CSS/border-right-color", "pl": "pl/CSS/border-right-color" } ) }} diff --git a/files/pt-pt/web/css/border-right-style/index.html b/files/pt-pt/web/css/border-right-style/index.html new file mode 100644 index 0000000000..0aa34c58bd --- /dev/null +++ b/files/pt-pt/web/css/border-right-style/index.html @@ -0,0 +1,16 @@ +--- +title: border-right-style +slug: Web/CSS/border-right-style +tags: + - Referencia_CSS +translation_of: Web/CSS/border-right-style +--- +

+{{ CSSRef() }} +

+

Resumo

+

border-right-style configura o estilo da linha da borda direita de uma caixa. +

Veja a propriedade border-bottom-style para mais informações. +

Categorias +

Interwiki Language Links +

{{ languages( { "en": "en/CSS/border-right-style", "fr": "fr/CSS/border-right-style" } ) }} diff --git a/files/pt-pt/web/css/border-right-width/index.html b/files/pt-pt/web/css/border-right-width/index.html new file mode 100644 index 0000000000..60840f3117 --- /dev/null +++ b/files/pt-pt/web/css/border-right-width/index.html @@ -0,0 +1,16 @@ +--- +title: border-right-width +slug: Web/CSS/border-right-width +tags: + - Referencia_CSS +translation_of: Web/CSS/border-right-width +--- +

+{{ CSSRef() }} +

+

Resumo

+

border-right-width configura a largura da borda direita de uma caixa. +

Veja a propriedade border-bottom-width para mais informações. +

Categorias +

Interwiki Language Links +

{{ languages( { "en": "en/CSS/border-right-width", "fr": "fr/CSS/border-right-width" } ) }} diff --git a/files/pt-pt/web/css/border-right/index.html b/files/pt-pt/web/css/border-right/index.html new file mode 100644 index 0000000000..964e932736 --- /dev/null +++ b/files/pt-pt/web/css/border-right/index.html @@ -0,0 +1,49 @@ +--- +title: border-right +slug: Web/CSS/border-right +tags: + - Referencia_CSS +translation_of: Web/CSS/border-right +--- +

+{{ CSSRef() }} +

+

Resumo

+

A propriedade border-right é uma propriedade shorthand para configurar a largura, estilo e cor da borda esquerda de uma caixa. Esta propriedade pode ser usada para configurar um ou mais valores de {{ Cssxref("border-right-width") }}, {{ Cssxref("border-right-style") }} e {{ Cssxref("border-right-color") }}. Valores omitidos são configurados com o valor inicial. +

+ +

Sintaxe

+
border-right: [border-width || border-style || border-color | inherit] ;
+
+

Valores

+
border-width 
Veja {{ Cssxref("border-width") }}. +
border-style 
Veja {{ Cssxref("border-style") }}. +
border-color 
Veja {{ Cssxref("border-color") }}. +
+

Exemplos

+
element {
+    border-right: 1px solid #000;
+}
+
+

Notas

+

Se a regra não especificar uma cor de borda, a borda terá a cor especificada pela propriedade {{ Cssxref("color") }}. +

+

Especificações

+ +

== Compatibilidade com navegadores == +

+

Veja também

+

{{ Cssxref("border") }}, +{{ Cssxref("border-right") }} +

Categorias +

Interwiki Language Links +

{{ languages( { "en": "en/CSS/border-right", "fr": "fr/CSS/border-right", "pl": "pl/CSS/border-right" } ) }} diff --git a/files/pt-pt/web/css/border-spacing/index.html b/files/pt-pt/web/css/border-spacing/index.html new file mode 100644 index 0000000000..36747dc64d --- /dev/null +++ b/files/pt-pt/web/css/border-spacing/index.html @@ -0,0 +1,100 @@ +--- +title: border-spacing +slug: Web/CSS/border-spacing +tags: + - Referencia_CSS +translation_of: Web/CSS/border-spacing +--- +

{{ CSSRef() }}

+ +

Resumo

+ +

The border-spacing property specifies the distance between the borders of adjacent cells (only for the separated borders model). This is equivalent to the cellspacing attribute in presentational HTML.

+ + + +

Sintaxe

+ +

border-spacing: <length> | <length> <length> | inherit

+ +

Valores

+ + + +

Exemplos

+ +

View Live Examples

+ +
table#space {
+  border-collapse: separate;
+  border-spacing: 10px 5px;
+}
+
+ +

Notas

+ +

This property applies only when {{ Cssxref("border-collapse") }} is "separate".

+ +

The border-spacing is also used along the outside edge of the table, where the distance between the table's border and the cells in the first/last column or row is the sum of the relevant (horizontal or vertical) border-spacing and the relevant (top, right, bottom, or left) padding on the table.

+ +

Especificações

+ + + +

Compatibilidade com navegadores

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NavegadorVersão mais antiga
Netscape6
Internet Explorer7
Firefox1
Mozilla1
Safari1
Opera6
+ +

 

+ +

Veja também

+ +

{{ Cssxref("border-collapse") }}, {{ Cssxref("border-spacing") }}

+ +

Categorias

+ +

Interwiki Language Links

+ +

{{ languages( { "en": "en/CSS/border-spacing", "fr": "fr/CSS/border-spacing" } ) }}

diff --git a/files/pt-pt/web/css/border-top-color/index.html b/files/pt-pt/web/css/border-top-color/index.html new file mode 100644 index 0000000000..5df05465a6 --- /dev/null +++ b/files/pt-pt/web/css/border-top-color/index.html @@ -0,0 +1,16 @@ +--- +title: border-top-color +slug: Web/CSS/border-top-color +tags: + - Referencia_CSS +translation_of: Web/CSS/border-top-color +--- +

+{{ CSSRef() }} +

+

Resumo

+

border-top-color configura a cor da borda superior de um elemento. +

Veja a propriedade border-bottom-color para mais informações. +

Categorias +

Interwiki Language Links +

{{ languages( { "en": "en/CSS/border-top-color", "fr": "fr/CSS/border-top-color" } ) }} diff --git a/files/pt-pt/web/css/border-top-style/index.html b/files/pt-pt/web/css/border-top-style/index.html new file mode 100644 index 0000000000..b5132d5a35 --- /dev/null +++ b/files/pt-pt/web/css/border-top-style/index.html @@ -0,0 +1,16 @@ +--- +title: border-top-style +slug: Web/CSS/border-top-style +tags: + - Referencia_CSS +translation_of: Web/CSS/border-top-style +--- +

+{{ CSSRef() }} +

+

Resumo

+

border-top-style configura o estilo da linha da borda superior de uma caixa. +

Veja a propriedade border-bottom-style para mais informações. +

Categorias +

Interwiki Language Links +

{{ languages( { "en": "en/CSS/border-top-style", "fr": "fr/CSS/border-top-style" } ) }} diff --git a/files/pt-pt/web/css/border-top-width/index.html b/files/pt-pt/web/css/border-top-width/index.html new file mode 100644 index 0000000000..45fcd9b374 --- /dev/null +++ b/files/pt-pt/web/css/border-top-width/index.html @@ -0,0 +1,16 @@ +--- +title: border-top-width +slug: Web/CSS/border-top-width +tags: + - Referencia_CSS +translation_of: Web/CSS/border-top-width +--- +

+{{ CSSRef() }} +

+

Resumo

+

border-top-width configura a largura da borda superiror de uma caixa. +

Veja a propriedade border-bottom-width para mais informações. +

Categorias +

Interwiki Language Links +

{{ languages( { "en": "en/CSS/border-top-width", "fr": "fr/CSS/border-top-width" } ) }} diff --git a/files/pt-pt/web/css/border-top/index.html b/files/pt-pt/web/css/border-top/index.html new file mode 100644 index 0000000000..d284e0bc7a --- /dev/null +++ b/files/pt-pt/web/css/border-top/index.html @@ -0,0 +1,49 @@ +--- +title: border-top +slug: Web/CSS/border-top +tags: + - Referencia_CSS +translation_of: Web/CSS/border-top +--- +

+{{ CSSRef() }} +

+

Resumo

+

A propriedade border-top é uma propriedade shorthand para configurar a largura, estilo e cor da borda esquerda de uma caixa. Esta propriedade pode ser usada para configurar um ou mais valores de {{ Cssxref("border-top-width") }}, {{ Cssxref("border-top-style") }} e {{ Cssxref("border-top-color") }}. Valores omitidos são configurados com o falor inicial. +

+ +

Sintaxe

+
border-top: [border-width || border-style || border-color | inherit] ;
+
+

Valores

+
border-width 
Veja {{ Cssxref("border-width") }}. +
border-style 
Veja {{ Cssxref("border-style") }}. +
border-color 
Veja {{ Cssxref("border-color") }}. +
+

Exemplos

+
element {
+    border-top: 1px solid #000;
+}
+
+

Notas

+

Se a regra não especificar uma cor de borda, a borda terá a cor especificada pela propriedade {{ Cssxref("color") }}. +

+

Especificações

+ +

== Compatibilidade com navegadores == +

+

Veja também

+

{{ Cssxref("border") }}, +{{ Cssxref("border-top") }} +

Categorias +

Interwiki Language Links +

{{ languages( { "en": "en/CSS/border-top", "fr": "fr/CSS/border-top", "pl": "pl/CSS/border-top" } ) }} diff --git a/files/pt-pt/web/css/border-width/index.html b/files/pt-pt/web/css/border-width/index.html new file mode 100644 index 0000000000..c3cd9915f2 --- /dev/null +++ b/files/pt-pt/web/css/border-width/index.html @@ -0,0 +1,112 @@ +--- +title: border-width +slug: Web/CSS/border-width +tags: + - Referencia_CSS +translation_of: Web/CSS/border-width +--- +

{{ CSSRef() }}

+ +

Resumo

+ +

border-width configura a largura da borda de uma caixa.

+ + + +

Sintaxe

+ +
border-width: <border-width> {1,4} | inherit
+
+ +

Valores de <border-width>

+ +
+
thin 
+
Uma borda fina.
+
medium 
+
Uma borda média.
+
thick 
+
Uma borda grossa.
+
<length> 
+
A espessura da borda tem um valor explícito. Valores explícitos de borda não podem ser negativos.
+
<percentage> 
+
A espessura da borda tem um valor em porcentagem, porcentagens da largura do bloco em que está contida. Larguras explícitas de borda não podem ser negativos.
+
+ +

Nota: Um valor em também é suportado.

+ +

Propriedades relacionadas

+ + + +

 

+ +

Exemplos

+ +

View Live Examples

+ +
element {
+    border-width: thin;
+    border-style: solid;
+    border-color: #000;
+}
+
+ +

Especificações

+ + + +

Compatibilidade com navegadores

+ + + + + + + + + + + + + + + + + + + + + + + + +
NavegadorVersão mais antiga
Internet Explorer 
Firefox 
Netscape 
Opera 
+ +

 

+ +

Veja também

+ +

{{ Cssxref("border") }}, {{ Cssxref("border-width") }}, {{ Cssxref("border-style") }}, {{ Cssxref("border-color") }}

+ +

Categorias

+ +

Interwiki Language Links

+ +

{{ languages( { "en": "en/CSS/border-width", "fr": "fr/CSS/border-width" } ) }}

diff --git a/files/pt-pt/web/css/border/index.html b/files/pt-pt/web/css/border/index.html new file mode 100644 index 0000000000..7110cc6c8d --- /dev/null +++ b/files/pt-pt/web/css/border/index.html @@ -0,0 +1,51 @@ +--- +title: border +slug: Web/CSS/border +tags: + - Referencia_CSS +translation_of: Web/CSS/border +--- +

+{{ CSSRef() }} +

+

Resumo

+

A propriedade border é uma propriedade para ajustar os valores de propriedades individuais da borda em um único elemento na folha do estilo. border pode ser usado com as seguintes propriedades adicionais: {{ Cssxref("border-width") }}, {{ Cssxref("border-style") }}, {{ Cssxref("border-color") }}. +

+ +

Sintaxe

+
border: [border-width || border-style || border-color | inherit] ;
+
+

Valores

+
border-width
Ver {{ Cssxref("border-width") }}. +
border-style 
Ver {{ Cssxref("border-style") }}. +
border-color 
Ver {{ Cssxref("border-color") }}. +
+

Exemplos

+

Exemplos +

+
elemento {
+    border: 1px solid #000;
+}
+
+

Notas

+

Quando as propriedades {{ Cssxref("border-width") }}, {{ Cssxref("border-style") }}, e {{ Cssxref("border-color") }} aceitarem acima de quatro valores, esta propriedade aceitará somente um valor para cada propriedade. +

+

Especificações

+ +

Compatibilidade com navegadores

+ +
Navegador Versões mais antigas
Internet Explorer 4
Firefox 1
Netscape 4
Opera 3.5
+

Veja também

+

{{ Cssxref("border") }} +

Categorias +

Interwiki Language Links +

{{ languages( { "en": "en/CSS/border", "fr": "fr/CSS/border", "pl": "pl/CSS/border" } ) }} diff --git a/files/pt-pt/web/css/bottom/index.html b/files/pt-pt/web/css/bottom/index.html new file mode 100644 index 0000000000..2aa2e1e2f7 --- /dev/null +++ b/files/pt-pt/web/css/bottom/index.html @@ -0,0 +1,81 @@ +--- +title: bottom +slug: Web/CSS/bottom +tags: + - Referencia_CSS +translation_of: Web/CSS/bottom +--- +

+{{ CSSRef() }} +

+

Resumo

+

The bottom property specifies part of the position of positioned elements. +

For absolutely positioned elements (those with position: absolute or position: fixed), it specifies the distance between the bottom margin edge of the element and the bottom edge of its containing block. +

For relatively positioned elements (those with position: relative), it specifies the amount the element is moved above its normal position. However, the {{ Cssxref("top") }} property overrides the bottom property, so if top is not auto, the computed value of bottom is the negative of the computed value of top. +

+ +

Sintaxe

+
   bottom: <length> | <percentage> | auto | inherit
+
+

Valores

+
<length> 
A length, used as described in the summary. Can be negative, zero, or positive. +
<percentage> 
A percentage of the containing block's height, used as described in the summary. +
auto 
For absolutely positioned elements, position the element based on the {{ Cssxref("top") }} property and treat height: auto as a height based on the content. For relatively positioned elements, offset the element from its original position based on the {{ Cssxref("top") }} property, or if top is also auto, do not offset it at all. +
inherit 
Inherits the computed value from its parent element (which may not be its containing block). This computed value is then handled like it was a <length>, a <percentage>, or auto +
+

Exemplos

+
element {
+    position: absolute;
+    bottom: 20px;
+    height: 200px;
+    border: 1px solid #000;
+}
+
+

The following sample page contrasts position:absolute and position:fixed. When the regular text becomes taller than the viewable portion of the page (the browser window's viewport), blocks positioned with position:absolute will scroll with the page, while blocks positioned with position:fixed will not. Note that IE6 does not support position:fixed. +

+
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
+   "http://www.w3.org/TR/html4/strict.dtd">
+<html>
+<head>
+<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
+<title>Position at bottom, absolute or fixed</title>
+<style type="text/css">
+p {font-size:30px; line-height:3em;}
+div.pos {width:49%; text-align:center; border:2px solid #00f;}
+div#abs {position:absolute; bottom:0; left:0;}
+div#fix {position:fixed; bottom:0; right:0;}
+</style>
+</head>
+<body>
+  <p>This<br>is<br>some<br>tall,<br>tall,
+    <br>tall,<br>tall,<br>tall<br>content.</p>
+  <div id="fix" class="pos"><p>Fixed</p></div>
+  <div id="abs" class="pos"><p>Absolute</p></div>
+</body>
+</html>
+

Notas

+

For absolutely positioned elements whose containing block is based on a block-level element, this property is an offset from the padding edge of that element. +

For absolutely positioned elements, the bottom property has no visible effect when all of {{ Cssxref("top") }}, {{ Cssxref("height") }}, and {{ Cssxref("margin-top") }} are not auto (which is the default value for top and height). +

+

Especificações

+ +

Compatibilidade com navegadores

+This is as far back as the documentaion goes. +
Navegador Versão mais antiga
Internet Explorer 5
Firefox 1
Netscape 6
Opera 6
+

Veja também

+

{{ Cssxref("bottom") }}, +{{ Cssxref("position") }}, +{{ Cssxref("top") }}, +{{ Cssxref("left") }}, +{{ Cssxref("right") }} +

Categorias +

Interwiki Language Links +

{{ languages( { "en": "en/CSS/bottom", "fr": "fr/CSS/bottom", "pl": "pl/CSS/bottom" } ) }} diff --git a/files/pt-pt/web/css/clear/index.html b/files/pt-pt/web/css/clear/index.html new file mode 100644 index 0000000000..8fcfd728ca --- /dev/null +++ b/files/pt-pt/web/css/clear/index.html @@ -0,0 +1,93 @@ +--- +title: clear +slug: Web/CSS/clear +tags: + - Referencia_CSS +translation_of: Web/CSS/clear +--- +

{{ CSSRef() }}

+ +

Resumo

+ +

A propriedadeclear especifica se um elemento deve ser posicionado ao lado dos elementos flutuantes ou se devem ser colocados abaixo deles, "forçando" os elementos com float para cima.

+ + + +

Sintaxe

+ +

clear: none | left | right | both | inherit

+ +

Valores

+ + + +

Exemplos

+ +

View Live Examples

+ +
h1 { clear: none }
+h2 { clear: right }
+ +

Notas

+ +

The clear property applies to both floating and non-floating elements.

+ +

When it applies to non-floating blocks, it moves the border edge of the element down until it is below the margin edge of all relevant floats. This movement (when it happens) causes margin collapsing not to occur.

+ +

When it applies to floating elements, it moves the margin edge of the element below the margin edge of all relevant floats. This affects the position of later floats, since later floats cannot be positioned higher than earlier ones.

+ +

The floats that are relevant to be cleared are the earlier floats within the same block formatting context.

+ +

Especificações

+ + + +

Compatibilidade com navegadores

+ + + + + + + + + + + + + + + + + + + + + + + + +
NavegadorVersão mais antiga
Internet Explorer4
Firefox1
Netscape4
Mozilla1
+ +

Veja também

+ +

{{ Cssxref("float") }}, {{ Cssxref("clear") }}

+ +

Categorias

+ +

Interwiki Language Links

+ +

{{ languages( { "en": "en/CSS/clear", "fr": "fr/CSS/clear", "pl": "pl/CSS/clear" } ) }}

diff --git a/files/pt-pt/web/css/color/index.html b/files/pt-pt/web/css/color/index.html new file mode 100644 index 0000000000..bd7fe973b2 --- /dev/null +++ b/files/pt-pt/web/css/color/index.html @@ -0,0 +1,47 @@ +--- +title: color +slug: Web/CSS/color +tags: + - Referencia_CSS +translation_of: Web/CSS/color +--- +

+{{ CSSRef() }} +

+

Resumo

+

A propriedade color ajusta a cor de primeiro plano de um texto contido no elemento. +

+ +

Sintaxe

+
border-bottom-color: color | inherit
+
+

Valores

+
color 
O color pode ser especificado como valor hexadecimal RGB, valor RGB regular, ou usando as cores pre-definidas. +
+

Exemplos

+

As maneiras seguintes são todas um exemplo de como deixar um elemento de texto com a cor vermelho: +

+
element { color: red }
+element { color: #f00 }
+element { color: #ff0000 }
+element { color: rgb(255,0,0) }
+element { color: rgb(100%, 0%, 0%) }
+
+

Notas

+ +

Especificações

+ +

== Compatibilidade com navegadores == +

Categorias +

Interwiki Language Links +

{{ languages( { "en": "en/CSS/color", "fr": "fr/CSS/color", "pl": "pl/CSS/color" } ) }} 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" new file mode 100644 index 0000000000..b3906acb4f --- /dev/null +++ "b/files/pt-pt/web/css/como_come\303\247ar/caixas/index.html" @@ -0,0 +1,358 @@ +--- +title: Caixas +slug: Web/CSS/Como_começar/Caixas +tags: + - 'CSS:Como_começar' +translation_of: Learn/CSS/Building_blocks +--- +

{{ 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" new file mode 100644 index 0000000000..ee12da94f0 --- /dev/null +++ "b/files/pt-pt/web/css/como_come\303\247ar/cascata_e_heran\303\247a/index.html" @@ -0,0 +1,134 @@ +--- +title: Cascata e herança +slug: Web/CSS/Como_começar/Cascata_e_herança +tags: + - 'CSS:Como_começar' +translation_of: Learn/CSS/Building_blocks/Cascade_and_inheritance +--- +

{{ 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" new file mode 100644 index 0000000000..d291b92e03 --- /dev/null +++ "b/files/pt-pt/web/css/como_come\303\247ar/como_o_css_trabalha/index.html" @@ -0,0 +1,129 @@ +--- +title: Como o CSS trabalha +slug: Web/CSS/Como_começar/Como_o_CSS_trabalha +tags: + - 'CSS:Como_começar' +translation_of: Learn/CSS/First_steps/How_CSS_works +--- +

{{ 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" new file mode 100644 index 0000000000..523c408aad --- /dev/null +++ "b/files/pt-pt/web/css/como_come\303\247ar/conte\303\272do/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/web/css/como_come\303\247ar/cor/index.html" "b/files/pt-pt/web/css/como_come\303\247ar/cor/index.html" new file mode 100644 index 0000000000..6ebb2347b9 --- /dev/null +++ "b/files/pt-pt/web/css/como_come\303\247ar/cor/index.html" @@ -0,0 +1,340 @@ +--- +title: Cor +slug: Web/CSS/Como_começar/Cor +tags: + - 'CSS:Como_começar' +translation_of: Learn/CSS/Introduction_to_CSS/Values_and_units#Colors +--- +

{{ 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" new file mode 100644 index 0000000000..7edd9f859e --- /dev/null +++ "b/files/pt-pt/web/css/como_come\303\247ar/css_leg\303\255vel/index.html" @@ -0,0 +1,187 @@ +--- +title: CSS legível +slug: Web/CSS/Como_começar/CSS_legível +tags: + - 'CSS:Como_começar' +translation_of: Learn/CSS/Introduction_to_CSS/Syntax#Beyond_syntax_make_CSS_readable +--- +

{{ 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/dados_xml/index.html" "b/files/pt-pt/web/css/como_come\303\247ar/dados_xml/index.html" new file mode 100644 index 0000000000..d0245353fa --- /dev/null +++ "b/files/pt-pt/web/css/como_come\303\247ar/dados_xml/index.html" @@ -0,0 +1,239 @@ +--- +title: Dados XML +slug: Web/CSS/Como_começar/Dados_XML +tags: + - 'CSS:Como_começar' +translation_of: Archive/Beginner_tutorials/XML_data +--- +

{{ Previous("Web/CSS/Como_começar/Gráficos_SVG") }}

+ +

 

+ +

Esta página contém um exemplo de como você pode usar o CSS com dados XML.

+ +

Você cria um documento XML de amostra e uma folha de estilo que você pode usar para exibí-lo em seu navegador.

+ +

Informação: Dados XML

+ +

XML (eXtensible Markup Language) é uma linguagem de propósito geral para qualquer tipo de dados estruturados.

+ +

Por padrão, seu navegador Mozilla mostra o XML em um formato muito similar aos dados originais no arquivo XML. Você vê as tags reais que definem a estrutura dos dados.

+ +

Ligando a folha de estilo CSS com o documento XML, você pode definir outras maneiras para mostrá-lo. Para fazer isto, sua folha de estilo usa regras que mapeiam os tags no documento XML para mostrar tipos usados pelo HTML.

+ + + + + + + + +
Exemplo
Dados em um documento XML usando tags <INFO>. Você quer que os elementos INFO do documento sejam mostrados como parágrafos no HTML. +

Na folha de estilo do documento, você especifica como os elementos INFO serão exibidos:

+ +
+
+INFO {
+  display: block;
+  margin: 1em 0;
+  }
+
+
+
+ +

Os valores mais comuns para a propriedade display são:

+ + + + + + + + + + + + +
blockMonstrado como DIV do HTML (para cabeçalhos, parágrafos)
inlineMostrado como SPAN do HTML (para ênfases no texto)
+ +

Adicione seu próprio estilo de regras para especificar a fonte, espaçamento e outros detalhes da mesma maneira que no HTML.

+ + + + + + + + +
Mais detalhes
Outros valores de display mostram o elemento como o item de uma lista, ou como o componente de uma tabela. +

Para a lista completa de tipos de exibição, veja The display property em CSS Specification.

+ +

Usando CSS sozinho, a estrutura de exibição precisa ser a mesma da estrutura do documento. Outras tecnologias pode modificar a estrutura da exibição — por exemplo, o XBL pode adicionar conteúdo, e o JavaScript pode modificar o DOM.

+ +

Para mais informações sobre o XML no Mozilla, veja a página XML neste wiki.

+
+ +

Ação: Uma demonstração XML

+ +

Crie um novo arquivo XML, doc9.xml. Copie e cole o conteúdo daqui, tendo certeza de ter rolado a tela e pego tudo isto:

+ +
+
<?xml version="1.0"?>
+<!-- XML demonstration -->
+
+<?xml-stylesheet type="text/css" href="style9.css"?>
+
+<!DOCTYPE planet>
+<planet>
+
+<ocean>
+<name>Arctic</name>
+<area>13,000</area>
+<depth>1,200</depth>
+</ocean>
+
+<ocean>
+<name>Atlantic</name>
+<area>87,000</area>
+<depth>3,900</depth>
+</ocean>
+
+<ocean>
+<name>Pacific</name>
+<area>180,000</area>
+<depth>4,000</depth>
+</ocean>
+
+<ocean>
+<name>Indian</name>
+<area>75,000</area>
+<depth>3,900</depth>
+</ocean>
+
+<ocean>
+<name>Southern</name>
+<area>20,000</area>
+<depth>4,500</depth>
+</ocean>
+
+</planet>
+
+
+ +

Crie um novo arquivo CSS, style9.css. Copie e cole o conteúdo daqui, tendo certeza de ter rolado a tela e pego tudo isto:

+ +
+
/*** XML demonstration ***/
+
+planet:before {
+  display: block;
+  width: 8em;
+  font-weight: bold;
+  font-size: 200%;
+  content: "Oceans";
+  margin: -.75em 0px .25em -.25em;
+  padding: .1em .25em;
+  background-color: #cdf;
+  }
+
+planet {
+  display: block;
+  margin: 2em 1em;
+  border: 4px solid #cdf;
+  padding: 0px 1em;
+  background-color: white;
+  }
+
+ocean {
+  display: block;
+  margin-bottom: 1em;
+  }
+
+name {
+  display: block;
+  font-weight: bold;
+  font-size: 150%;
+  }
+
+area {
+  display: block;
+  }
+
+area:before {
+  content: "Area: ";
+  }
+
+area:after {
+  content: " million km\B2";
+  }
+
+depth {
+  display: block;
+  }
+
+depth:before {
+  content: "Mean depth: ";
+  }
+
+depth:after {
+  content: " m";
+  }
+
+
+ +

Abra o documento em seu navegador:

+ + + + + + + +
+
+

Oceans

+ +

Arctic
+ Area: 13,000 million km²
+ Mean depth: 1,200 m

+ +

Atlantic
+ Area: 87,000 million km²
+ Mean depth: 3,900 m

+ +

. . .

+
+
+ +


+ Notas sobre esta demonstração:

+ + + +

 

+ + + + + + + + +
Desafio
Mude a folha de estilo de modo que ela mostre o documento como uma tabela. +

(Veja o capítulo Tables em CSS Specification para exemplos que você pode adaptar.)

+
+ +

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.

+ +

Esta é a última página do tutorial. Para mais informações sobre CSS no Mozilla, veja a página principal CSS neste wiki.

+ +

{{ Previous("Web/CSS/Como_começar/Gráficos_SVG") }}

+ +

Categorias

+ +

Interwiki Language Links

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" new file mode 100644 index 0000000000..e4efedf77a --- /dev/null +++ "b/files/pt-pt/web/css/como_come\303\247ar/disposi\303\247\303\243o/index.html" @@ -0,0 +1,452 @@ +--- +title: Disposição +slug: Web/CSS/Como_começar/Disposição +tags: + - 'CSS:Como_começar' +translation_of: Learn/CSS/CSS_layout +--- +

{{ 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" new file mode 100644 index 0000000000..2e32166761 --- /dev/null +++ "b/files/pt-pt/web/css/como_come\303\247ar/estilos_de_texto/index.html" @@ -0,0 +1,157 @@ +--- +title: Estilos de texto +slug: Web/CSS/Como_começar/Estilos_de_texto +tags: + - 'CSS:Como_começar' +translation_of: Learn/CSS/Styling_text/Fundamentals +--- +

{{ 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" new file mode 100644 index 0000000000..074f78c92d --- /dev/null +++ "b/files/pt-pt/web/css/como_come\303\247ar/gr\303\241ficos_svg/index.html" @@ -0,0 +1,215 @@ +--- +title: Gráficos SVG +slug: Web/CSS/Como_começar/Gráficos_SVG +tags: + - 'CSS:Como_começar' +translation_of: Web/SVG/Tutorial/SVG_and_CSS +--- +

{{ 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" new file mode 100644 index 0000000000..a0cf76e018 --- /dev/null +++ "b/files/pt-pt/web/css/como_come\303\247ar/index.html" @@ -0,0 +1,91 @@ +--- +title: Como começar +slug: Web/CSS/Como_começar +tags: + - CSS + - 'CSS:Como_começar' + - Todas_as_Categorias +translation_of: Learn/CSS/First_steps +--- +

 

+ +

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/interfaces_de_usu\303\241rio_xul/index.html" "b/files/pt-pt/web/css/como_come\303\247ar/interfaces_de_usu\303\241rio_xul/index.html" new file mode 100644 index 0000000000..46408abaa8 --- /dev/null +++ "b/files/pt-pt/web/css/como_come\303\247ar/interfaces_de_usu\303\241rio_xul/index.html" @@ -0,0 +1,336 @@ +--- +title: Interfaces de usuário XUL +slug: Web/CSS/Como_começar/Interfaces_de_usuário_XUL +tags: + - 'CSS:Como_começar' +translation_of: Archive/Beginner_tutorials/XUL_user_interfaces +--- +

{{ PreviousNext("CSS:Como começar:XBL bindings", "CSS:Como começar:Gráficos SVG") }}

+ +

Esta página ilustra a linguagem especializada do Mozilla para criação de interfaces de usuário.

+ +

Você cria uma simples demonstração que roda no seu navegador Mozilla.

+ +

Informação: Interfaces de usuário

+ +

Embora o HTML tenha algum suporte à interfaces de usuário, ele não suporta todas as características que você precisa para fazer uma aplicação autônoma.

+ +

O Mozilla supera esta limitação providenciando uma linguagem especializada para criar interfaces de usuário: XUL (XML User-interface Language, usualmente pronunciada como "zool").

+ +

Em XUL, muitas características comuns de interfaces de usuário podem ser construídas. Por exemplo, XUL proporciona janelas especializadas como diálogos, assim como barras de estado, menus, barras de ferramenta, e mesmo navegadores.

+ +

Mais características especializadas podem ser construídas em partes usando XUL juntamente com outras tecnologias que você viu neste tutorial: estilo CSS, código JavaScript e XBL bindings.

+ +

Como outras linguagens baseadas em XML, XUL usa folhas de estilo CSS.

+ + + + + + + + +
Mais detalhes
Para maiores informações sobre interfaces de usuário XUL, veja a página XUL neste wiki.
+ +

Ação: Uma demonstração XUL

+ +

Crie um novo documento XUL de um simples arquivo de texto, doc7.xul. Copie e cole o conteúdo daqui, tendo certeza de ter rolado a tela para pegar tudo isto:

+ +
+
<?xml version="1.0"?>
+<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
+<?xml-stylesheet type="text/css" href="style7.css"?>
+
+<window
+  xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
+  title="CSS Getting Started - XUL demonstration"
+  onload="init();">
+
+<script type="application/x-javascript" src="script7.js"/>
+
+<label class="head-1" value="XUL demonstration"/>
+
+<vbox>
+
+  <groupbox class="demo-group">
+    <caption label="Day of week calculator"/>
+    <grid>
+      <columns>
+        <column/>
+        <column/>
+        </columns>
+      <rows>
+        <row>
+          <label class="text-prompt" value="Date:"
+            accesskey="D" control="date-text"/>
+          <textbox id="date-text" type="timed"
+            timeout="750" oncommand="refresh();"/>
+          </row>
+        <row>
+          <label value="Day:"/>
+          <hbox id="day-box">
+            <label class="day" value="Sunday" disabled="true"/>
+            <label class="day" value="Monday" disabled="true"/>
+            <label class="day" value="Tuesday" disabled="true"/>
+            <label class="day" value="Wednesday" disabled="true"/>
+            <label class="day" value="Thursday" disabled="true"/>
+            <label class="day" value="Friday" disabled="true"/>
+            <label class="day" value="Saturday" disabled="true"/>
+            </hbox>
+          </row>
+        </rows>
+      </grid>
+    <hbox class="buttons">
+      <button id="clear" label="Clear" accesskey="C"
+        oncommand="clearDate();"/>
+      <button id="today" label="Today" accesskey="T"
+        oncommand="setToday();"/>
+      </hbox>
+    </groupbox>
+
+  <statusbar>
+    <statusbarpanel id="status"/>
+    </statusbar>
+
+</vbox>
+
+</window>
+
+
+ +

Crie um novo arquivo CSS, style7.css. Copie e cole o conteúdo daqui, tendo certeza de ter rolado a tela para pegar tudo isto:

+ +
+
/*** XUL demonstration ***/
+window {
+  -moz-box-align: start;
+  background-color: -moz-dialog;
+  font: -moz-dialog;
+  padding: 2em;
+  }
+
+.head-1 {
+  font-weight: bold;
+  font-size: 200%;
+  padding-left: 5px;
+  }
+
+
+/* the group box */
+.demo-group {
+  padding: 1em;
+  }
+
+.demo-group grid {
+  margin-bottom: 1em;
+  }
+
+.demo-group column {
+  margin-right: .5em;
+  }
+
+.demo-group row {
+  margin-bottom: .5em;
+  }
+
+.demo-group .buttons {
+  -moz-box-pack: end;
+  }
+
+
+/* the day-of-week labels */
+.day {
+  margin-left: 1em;
+  }
+
+.day[disabled] {
+  color: #777;
+  }
+
+.day:first-child {
+  margin-left: 4px;
+  }
+
+
+/* the left column labels */
+.text-prompt {
+  padding-top: .25em;
+  }
+
+
+/* the date input box */
+#date-text {
+  max-width: 8em;
+  }
+
+
+/* the status bar */
+statusbar {
+  width: 100%;
+  border: 1px inset -moz-dialog;
+  margin: 4px;
+  padding: 0px 4px;
+  }
+
+#status {
+  padding: 4px;
+  }
+
+#status[warning] {
+  color: red;
+  }
+
+
+ +

Crie um novo arquivo de texto, script7.js. Copie e cole o conteúdo daqui, tendo certeza de ter rolado a tela e pego todo o conteúdo daqui:

+ +
+
// XUL demonstration
+
+var dateBox, dayBox, currentDay, status; // elements
+
+// called by window onLoad
+function init() {
+  dateBox = document.getElementById("date-text")
+  dayBox = document.getElementById("day-box")
+  status = document.getElementById("status")
+  setToday();
+  }
+
+// called by Clear button
+function clearDate() {
+  dateBox.value = ""
+  refresh()
+  }
+
+// called by Today button
+function setToday() {
+  var d = new Date()
+  dateBox.value = (d.getMonth() + 1)
+    + "/" + d.getDate()
+    + "/" + d.getFullYear()
+  refresh()
+  }
+
+// called by Date textbox
+function refresh() {
+  var d = dateBox.value
+  var theDate = null
+
+  showStatus(null)
+  if (d != "") {
+    try {
+      var a = d.split("/")
+      var theDate = new Date(a[2], a[0] - 1, a[1])
+      showStatus(theDate)
+      }
+    catch (ex) {}
+    }
+  setDay(theDate)
+  }
+
+// internal
+function setDay(aDate) {
+  if (currentDay) currentDay.setAttribute("disabled", "true")
+  if (aDate == null) currentDay = null
+  else {
+    var d = aDate.getDay()
+    currentDay = dayBox.firstChild
+    while (d-- > 0) currentDay = currentDay.nextSibling
+    currentDay.removeAttribute("disabled")
+    }
+  dateBox.focus();
+  }
+
+function showStatus(aDate) {
+  if (aDate == null) {
+    status.removeAttribute("warning")
+    status.setAttribute("label", "")
+    }
+  else if (aDate === false || isNaN(aDate.getTime())) {
+    status.setAttribute("warning", "true")
+    status.setAttribute("label", "Date is not valid")
+    }
+  else {
+    status.removeAttribute("warning")
+    status.setAttribute("label", aDate.toLocaleDateString())
+    }
+  }
+
+
+ +

Para ver o resultado exatamente como pretendido use o tema padrão do seu navegador. Se você usa um tema diferente, isto mode mudar alguns estilos da interface do usuário e a demonstração pode parecer estranha.

+ +

Abra o documento no seu navegador Mozilla e use a interface.

+ +

Este wiki não suporta XUL e JavaScript nas páginas, então não é possível fazer a demonstração aqui. Deve se parecer com isto:

+ + + + + + + +
+

XUL demonstration

+ +
+

Day of week calculator

+ + + + + + + + + + + + + + + + +
Date:6/27/2005
Day:Sunday Monday Tuesday Wednesday Thurdsay Friday Saturday
+
+

Clear Today

+
+
+
+ +
+

June 27, 2005

+
+
+ +

Notas sobre esta demonstração:

+ + + +

Examine a folha de estilo do documento para ver se você entende todas as regras dele. Se houver alguma regra que você não entende, comente-a e atualize o seu navegador para ver o efeito no documento.

+ + + + + + + + +
Desafio
Use a ferramenta DOM Inspector para examinar a caixa de texto Date. Ela é feita de outros elementos que são gerados por seu XBL binding. +

Descubra a classe do elemento html:input. Este é o elemento que atualmente recebe a entrada do usuário.

+ +

Usando este conhecimento, adicione uma regra à sua folha de estilo que faça o fundo da caixa Date de um azul pálido quando ele tiver o foco do teclado (mas branco quando o foco do teclado estiver em outro lugar).

+
+ +

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, você viu que as formas retangulares padrão são comuns na maioria das interfaces de usuário. Mozilla também suporta uma linguagem especializada de gráficos para criar padrões, usando folhas de estilo CSS para especificar o estilo. A próxima página demonstra isto: Gráficos SVG

+ +

{{ PreviousNext("CSS:Como começar:XBL bindings", "CSS:Como começar:Gráficos SVG") }}

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" new file mode 100644 index 0000000000..5cb8faf696 --- /dev/null +++ "b/files/pt-pt/web/css/como_come\303\247ar/javascript/index.html" @@ -0,0 +1,159 @@ +--- +title: JavaScript +slug: Web/CSS/Como_começar/JavaScript +tags: + - 'CSS:Como_começar' +translation_of: Learn/JavaScript/Client-side_web_APIs/Manipulating_documents +--- +

{{ 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" new file mode 100644 index 0000000000..5d6ca00f01 --- /dev/null +++ "b/files/pt-pt/web/css/como_come\303\247ar/listas/index.html" @@ -0,0 +1,361 @@ +--- +title: Listas +slug: Web/CSS/Como_começar/Listas +tags: + - 'CSS:Como_começar' +translation_of: Learn/CSS/Styling_text/Styling_lists +--- +

{{ 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" new file mode 100644 index 0000000000..0038962474 --- /dev/null +++ "b/files/pt-pt/web/css/como_come\303\247ar/m\303\255dia/index.html" @@ -0,0 +1,433 @@ +--- +title: Média +slug: Web/CSS/Como_começar/Mídia +tags: + - 'CSS:Como_começar' +translation_of: Web/Progressive_web_apps/Responsive/Media_types +--- +

{{ 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" new file mode 100644 index 0000000000..a87487b3a3 --- /dev/null +++ "b/files/pt-pt/web/css/como_come\303\247ar/o_que_\303\251_css/index.html" @@ -0,0 +1,134 @@ +--- +title: O que é CSS +slug: Web/CSS/Como_começar/O_que_é_CSS +tags: + - 'CSS:Como_começar' +translation_of: Learn/CSS/First_steps/How_CSS_works +--- +

{{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" new file mode 100644 index 0000000000..d386670557 --- /dev/null +++ "b/files/pt-pt/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/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" new file mode 100644 index 0000000000..fad0fc8ea8 --- /dev/null +++ "b/files/pt-pt/web/css/como_come\303\247ar/porque_usar_css/index.html" @@ -0,0 +1,110 @@ +--- +title: Porque usar CSS +slug: Web/CSS/Como_começar/Porque_usar_CSS +tags: + - 'CSS:Como_começar' +translation_of: Learn/CSS/First_steps/How_CSS_works +--- +

{{ 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" new file mode 100644 index 0000000000..250eb58d3f --- /dev/null +++ "b/files/pt-pt/web/css/como_come\303\247ar/seletores/index.html" @@ -0,0 +1,207 @@ +--- +title: Seletores +slug: Web/CSS/Como_começar/Seletores +tags: + - 'CSS:Como_começar' +translation_of: Learn/CSS/Building_blocks/Selectors +--- +

{{ 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" new file mode 100644 index 0000000000..c8daefb048 --- /dev/null +++ "b/files/pt-pt/web/css/como_come\303\247ar/tabelas/index.html" @@ -0,0 +1,654 @@ +--- +title: Tabelas +slug: Web/CSS/Como_começar/Tabelas +tags: + - 'CSS:Como_começar' +translation_of: Learn/CSS/Building_blocks/Styling_tables +--- +

{{ 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" new file mode 100644 index 0000000000..2bf4f5470c --- /dev/null +++ "b/files/pt-pt/web/css/consulta_de_m\303\255dia/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/consultas_de_media/index.html b/files/pt-pt/web/css/consultas_de_media/index.html new file mode 100644 index 0000000000..f9bbd7b94e --- /dev/null +++ b/files/pt-pt/web/css/consultas_de_media/index.html @@ -0,0 +1,110 @@ +--- +title: Consultas de média +slug: Web/CSS/Consultas_de_media +tags: + - CSS + - Consultas de Média + - Consultas de média CSS3 + - Desenho Adaptável + - Referencia + - Visão Geral +translation_of: Web/CSS/Media_Queries +--- +
{{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/content/index.html b/files/pt-pt/web/css/content/index.html new file mode 100644 index 0000000000..cc627821d8 --- /dev/null +++ b/files/pt-pt/web/css/content/index.html @@ -0,0 +1,18 @@ +--- +title: content +slug: Web/CSS/content +translation_of: Web/CSS/content +--- +

« Referência CSS

+

Resumo

+

A propriedade content é usada com os pseudo-elementos :before e :after para gerar conteúdo com o elemento.

+ +

Sintáxe

+
content: normal | none |
+       [ <string> | <uri> | <counter> | attr() |
+         open-quote | close-quote | no-open-quote | no-close-quote ]+ | inherit
+
+

Valores

+
none
O pseudo-elemento não é gerado.
normal
Computado como none para os pseudo-elementos :before e :after.
<string>
Conteúdo de texto.
<uri> url()
O valor especifica um recurso externo (como uma imagem). Se o recurso não puder ser exibido, ele é ignorado ou um marcador aparece em seu lugar.
<counter>
Contadores podem ser especificados como duas funções: 'counter()' ou 'counters()'. O primeiro tem duas formas: 'counter(name)' ou 'counter(name, style)'. O texto gerado é o valor do contador de intimidades de o nome dado no âmbito deste pseudo-elemento, que é formatado no estilo indicado ('decimal' por padrão).A segunda também tem duas formas: 'counters(name, string)' ou 'counters(name, string, style)'. O texto gerado é o valor de todos os contadores com o nome dado no âmbito deste pseudo-elemento, a partir ultraperiféricas intimidades separadas pela seqüência especificada. Os contadores são testados da maneira indicada ('decimal' por padrão). Veja a seção contadores automáticos e numeração para mais informação. O nome não pode ser 'none', 'inherit' ou 'initial'. Isso faz com que a função seja ignorada.
attr(X)
Retorna o valor da propriedade X do elemento. Se não existir a propriedade X, será retornado um texto vazio. A diferenciação entre maiúsculas e minúsculas depende do idioma do documento.
open-quote | close-quote
Esses valores são trocadas pelo texto apropriado da propriedade quotes.
no-open-quote | no-close-quote
Não introduz conteúdo, previne a inserção em um elemento de um open-quote ou close quote.
+
diff --git a/files/pt-pt/web/css/counter-increment/index.html b/files/pt-pt/web/css/counter-increment/index.html new file mode 100644 index 0000000000..43197dba12 --- /dev/null +++ b/files/pt-pt/web/css/counter-increment/index.html @@ -0,0 +1,66 @@ +--- +title: counter-increment +slug: Web/CSS/counter-increment +tags: + - CSS + - CSS List + - CSS Property + - Reference +translation_of: Web/CSS/counter-increment +--- +

{{ CSSRef() }}

+ +

Resumo

+ +

counter-increment é usado para aumentar o valor de CSS Counters com um valor dado.

+ +

{{cssinfo}}

+ +

Sintaxe

+ +
counter-increment: [<identifier> <integer>?]+ | inherit | none
+
+ +

Valores

+ +
+
identifier 
+
O nome do contador para incrementar.
+
integer 
+
O valor para adicionar ao contador. O padrão é 1 se nada for dado.
+
+ +

Você pode especificar como muitos contadores para incrementar como você quiser, cada um separado por um espaço.

+ +

Propriedades relacionadas

+ + + +

Exemplos

+ +
h1 {
+  counter-increment: chapter section 2 page;
+  /* Aumenta o valor dos contadores de capítulo e página em 1
+     e o contador da seção em 2. */
+}
+
+ +

== Notas ==

+ +

Especificações

+ + + +

== Compatibilidade com navegadores ==

+ +

Veja também

+ +

CSS Counters, {{ Cssxref("counter-increment") }}, {{ Cssxref("counter-reset") }}

+ +

Categorias

+ +

Interwiki Language Links

diff --git a/files/pt-pt/web/css/counter-reset/index.html b/files/pt-pt/web/css/counter-reset/index.html new file mode 100644 index 0000000000..709c4f8112 --- /dev/null +++ b/files/pt-pt/web/css/counter-reset/index.html @@ -0,0 +1,69 @@ +--- +title: counter-reset +slug: Web/CSS/counter-reset +tags: + - CSS + - CSS List + - CSS Property + - CSS Reference +translation_of: Web/CSS/counter-reset +--- +

{{ CSSRef() }}

+ +

Resumo

+ +

counter-reset é usado para reiniciar os CSS Counters a um valor dado.

+ + + +

Sintaxe

+ +
counter-reset: [<identifier> <integer>?]+ | inherit | none
+
+ +

Valores

+ +
+
identifier 
+
O nome do contador para reiniciar.
+
integer 
+
O valor para reiniciar o contador para cada ocorrência do elemento. O padrão é 0 se nada for dado.
+
+ +

Você pode especificar como muitos contadores para reiniciar quando você quiser, cada um separado por um espaço.

+ +

Propriedades relacionadas

+ + + +

Exemplos

+ +
h1 {
+  counter-reset: chapter section 1 page;
+  /* Configura os contadores de capítulo e página em 0
+     e o contador da seção em 1. */
+}
+
+ +

== Notas ==

+ +

Especificações

+ + + +

== Browser compatibility ==

+ +

Veja também

+ +

CSS Counters, {{ Cssxref("counter-increment") }}, {{ Cssxref("counter-reset") }}

+ +

Categorias

+ +

Interwiki Language Links

diff --git a/files/pt-pt/web/css/css_background_and_borders/index.html b/files/pt-pt/web/css/css_background_and_borders/index.html new file mode 100644 index 0000000000..87b26bd607 --- /dev/null +++ b/files/pt-pt/web/css/css_background_and_borders/index.html @@ -0,0 +1,154 @@ +--- +title: CSS Background and Borders +slug: Web/CSS/CSS_Background_and_Borders +tags: + - CSS + - CSS Backgrounds and Borders + - CSS Reference + - NeedsTranslation + - Overview + - TopicStub +translation_of: Web/CSS/CSS_Backgrounds_and_Borders +--- +

{{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" new file mode 100644 index 0000000000..dbd858e82c --- /dev/null +++ "b/files/pt-pt/web/css/css_background_and_borders/m\303\272ltiplos_planos_de_fundo/index.html" @@ -0,0 +1,57 @@ +--- +title: Utilização de múltiplos fundos em CSS +slug: Web/CSS/CSS_Background_and_Borders/Múltiplos_planos_de_fundo +tags: + - CSS + - CSS Background + - Example + - Guide + - Intermediate +translation_of: Web/CSS/CSS_Backgrounds_and_Borders/Using_multiple_backgrounds +--- +

{{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/index.html b/files/pt-pt/web/css/css_box_model/index.html new file mode 100644 index 0000000000..cb4dd91343 --- /dev/null +++ b/files/pt-pt/web/css/css_box_model/index.html @@ -0,0 +1,167 @@ +--- +title: CSS Box Model +slug: Web/CSS/CSS_Box_Model +tags: + - CSS + - CSS Box Model + - CSS Reference + - NeedsTranslation + - Overview + - TopicStub +translation_of: Web/CSS/CSS_Box_Model +--- +
{{CSSRef}}
+ +

CSS Box Model is a CSS module that defines the rectangular boxes, including their padding and margin, that are generated for elements and laid out according to the visual formatting model.

+ +

Reference

+ +

Properties

+ +

Properties controlling the flow of content in a box

+ +
+ +
+ +

Properties controlling the size of a box

+ +
+ +
+ +

Properties controlling the margins of a box

+ +
+ +
+ +

Properties controlling the paddings of a box

+ +
+ +
+ +

Other properties

+ +
+ +
+ +

Guides and tools

+ +
+
Introduction to the CSS box model
+
Explains one of the fundamental concept of CSS, the box model: describes the meaning of the margin, padding, as well as the different areas of a box.
+
Mastering margin collapsing
+
In several cases, two adjacent margins are collapsed into one. This article describes when this is happening and how to control it.
+
Box-shadow generator
+
An interactive tool that allows to visually create shadows and to generate the needed syntax for the {{cssxref("box-shadow")}} property.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("CSS3 Box")}}{{Spec2("CSS3 Box")}} 
{{SpecName("CSS2.1", "box.html")}}{{Spec2("CSS2.1")}} 
{{SpecName("CSS1")}}{{Spec2("CSS1")}}Initial definition
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support1.0{{CompatGeckoDesktop("1")}}3.03.51.0 (85)
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support1.0{{CompatGeckoMobile("1")}}6.06.01.0
+
diff --git a/files/pt-pt/web/css/css_box_model/introducao_modelo_caixa_css/index.html b/files/pt-pt/web/css/css_box_model/introducao_modelo_caixa_css/index.html new file mode 100644 index 0000000000..388a72ab39 --- /dev/null +++ b/files/pt-pt/web/css/css_box_model/introducao_modelo_caixa_css/index.html @@ -0,0 +1,69 @@ +--- +title: Introdução ao modelo de Caixa de CSS +slug: Web/CSS/CSS_Box_Model/Introducao_modelo_caixa_CSS +tags: + - CSS + - Modelo de Caixa de CSS + - Principiante + - Referencia +translation_of: Web/CSS/CSS_Box_Model/Introduction_to_the_CSS_box_model +--- +

{{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/ferramenta_selecao_cor/index.html b/files/pt-pt/web/css/css_colors/ferramenta_selecao_cor/index.html new file mode 100644 index 0000000000..696f2afd11 --- /dev/null +++ b/files/pt-pt/web/css/css_colors/ferramenta_selecao_cor/index.html @@ -0,0 +1,3243 @@ +--- +title: Ferramenta de seleção de cor +slug: Web/CSS/CSS_Colors/Ferramenta_selecao_cor +tags: + - CSS + - Ferramentas + - Seleção de cor + - cor +translation_of: Web/CSS/CSS_Colors/Color_picker_tool +--- +
+

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_columns/index.html b/files/pt-pt/web/css/css_columns/index.html new file mode 100644 index 0000000000..6a356077b5 --- /dev/null +++ b/files/pt-pt/web/css/css_columns/index.html @@ -0,0 +1,240 @@ +--- +title: CSS Multi-column Layout +slug: Web/CSS/CSS_Columns +tags: + - CSS + - CSS Multi-column Layout + - Layout + - NeedsTranslation + - Overview + - Reference + - TopicStub +translation_of: Web/CSS/CSS_Columns +--- +
{{CSSRef("CSS3 Multicol")}}
+ +

The CSS Multi-column Layout standard is a CSS module that adds support for multi-column layouts to CSS. This module makes it easier and more reliable than ever to produce columnar layouts without having to hand-code complicated and fragile structures. Support is included for establishing the number of columns in a layout, as well as how content should flow from column to column, gap sizes, column dividing lines (known as column rules), and so forth.

+ +

Multi-column layout basics

+ +

The three key properties used to produce the layout of columns in CSS are {{cssxref("column-count")}}, {{cssxref("column-width")}}, and {{cssxref("column-gap")}}. Other properties provide ways to fine-tune details of how things are organized and rendered within the layout structure built using those properties, but the job of figuring out what goes where is generally handled by these four.

+ +

Suggesting the number of columns and their widths

+ +

The first two properties, column-count and column-width, are both the most important and the most potentially misleading. It's important to understand that:

+ + + +

In a way, then, they're more like recommendations than hard and fast rules. And this makes sense once you consider the logic of it; this allows multi-column layouts to be responsive and adaptive to the screen width, while also supporting the overall layout of the page and the intent of the author. As the width of the containing space (or the screen) shrinks, the browser will reduce the number of columns it creates, adjusting the remaining columns' widths to ensure that the overall width is as expected.

+ +

The other thing you can control is the distance between the columns, known as the column gap. The column gap can be controlled using the {{cssxref("column-gap")}} property. By convention, the default gap is 1em, but this may or may not be the case in any given browser, so if it matters to you, explicitly set it. The column  gap, unlike the column count and width, doesn't get adjusted by the browser as it tries to fit the content into the available space.

+ +

Take a look at the example below, in which you can use the range control at the top to adjust the width of the columns' containing element.

+ + + +

{{EmbedLiveSample("Suggesting_the_number_of_columns_and_their_widths", 650, 800)}}

+ +

Text wrapping in multi-column layouts

+ +

The {{cssxref("column-fill")}} property also affects layout. By default, the browser will create as many appropriately-sized columns as it can, then balance the contents across them so that each column is approximately the same length. If, however, you prefer to have the browser fill the first column to its maximum height before moving on to the next column, you can set column-fill to auto (instead of the default, balance).

+ +

If there is no constraint on the column height, however, there will only be one column created, as it will never reach its maximum height to trigger wrapping to the second column, so be sure to either place your columns inside a container which constrains their height, either by using {{cssxref("height")}} or {{cssxref("max-height")}}.

+ +
+

While the CSS specification defines the {{cssxref("break-before")}}, {{cssxref("break-after")}}, and {{cssxref("break-inside")}} properties to help control wrapping of elements across region, column, or page boundaries, these properties are generally not implemented widely enough to use in real-world code at this time.

+
+ +

Column appearance

+ +

You can specify that a column rule—a dividing line drawn in the center of each column gap—be drawn between each column in the rendered output of your layout by using the {{cssxref("column-rule-style")}}, {{cssxref("column-rule-width")}}, and {{cssxref("column-rule-color")}} properties, or the shorthand property {{cssxref("column-rule")}}.

+ +

Reference

+ +

CSS properties

+ +
+ +
+ +

Guides

+ +
+
Using CSS multi-column layouts
+
Step-by-step tutorial about how to build layouts using several columns.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Multicol')}}{{Spec2('CSS3 Multicol')}}Initial definition
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}} {{property_prefix('-webkit')}}{{CompatGeckoDesktop(9)}}{{property_prefix('-moz')}}
+ {{CompatGeckoDesktop(52)}}
1011.10
+ 15{{property_prefix('-webkit')}}
3.0 (522){{property_prefix('-webkit')}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support2.1{{property_prefix('-webkit')}}{{compatGeckoMobile(22)}}{{property_prefix('-moz')}}
+ {{CompatGeckoMobile(52)}}
1011.5
+ 32{{property_prefix('-webkit')}}
3.2{{property_prefix('-webkit')}}
+
+ +

See also

+ +

Other CSS layout technologies include:

+ + diff --git a/files/pt-pt/web/css/css_flexible_box_layout/alinhamento_de_itens_num_recipiente_flex/index.html b/files/pt-pt/web/css/css_flexible_box_layout/alinhamento_de_itens_num_recipiente_flex/index.html new file mode 100644 index 0000000000..4e1d10f5de --- /dev/null +++ b/files/pt-pt/web/css/css_flexible_box_layout/alinhamento_de_itens_num_recipiente_flex/index.html @@ -0,0 +1,215 @@ +--- +title: Alinhamento de Itens num Recipiente Flex +slug: Web/CSS/CSS_Flexible_Box_Layout/alinhamento_de_itens_num_recipiente_flex +tags: + - Alinhar + - CSS + - Flex + - Guía + - align-content + - align-items + - align-self + - alinhamento + - flexbox + - justificar + - justify-content +translation_of: Web/CSS/CSS_Flexible_Box_Layout/Aligning_Items_in_a_Flex_Container +--- +

{{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 new file mode 100644 index 0000000000..cd89209634 --- /dev/null +++ b/files/pt-pt/web/css/css_flexible_box_layout/casos_de_utilizacao_tipicos_do_flexbox/index.html @@ -0,0 +1,143 @@ +--- +title: Casos de utilização típicos do Flexbox +slug: Web/CSS/CSS_Flexible_Box_Layout/casos_de_utilizacao_tipicos_do_flexbox +tags: + - CSS + - Caixa Flexível + - Flexible Box + - Guía + - flexbox + - padrões + - utilizações comuns +translation_of: Web/CSS/CSS_Flexible_Box_Layout/Typical_Use_Cases_of_Flexbox +--- +

{{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/index.html b/files/pt-pt/web/css/css_flexible_box_layout/index.html new file mode 100644 index 0000000000..ec5c17b62e --- /dev/null +++ b/files/pt-pt/web/css/css_flexible_box_layout/index.html @@ -0,0 +1,155 @@ +--- +title: CSS Flexible Box Layout +slug: Web/CSS/CSS_Flexible_Box_Layout +tags: + - CSS + - CSS Flexible Boxes + - NeedsTranslation + - Overview + - Reference + - TopicStub +translation_of: Web/CSS/CSS_Flexible_Box_Layout +--- +
{{CSSRef}}
+ +

CSS Flexible Box Layout is a module of CSS that defines a CSS box model optimized for user interface design, and the layout of items in one dimension. In the flex layout model, the children of a flex container can be laid out in any direction, and can “flex” their sizes, either growing to fill unused space or shrinking to avoid overflowing the parent. Both horizontal and vertical alignment of the children can be easily manipulated.

+ +

Basic Example

+ +

In the following example a container has been set to display: flex, which means that the three child items become flex items. The value of justify-content has been set to space-between in order to space the items out evenly on the main axis. An equal amount of space is placed between each item with the left and right items being flush with the edges of the flex container. You can also see that the items are stretching on the cross axis, due to the default value of align-items being stretch. The items stretch to the height of the flex container, making them each appear as tall as the tallest item.

+ +

{{EmbedGHLiveSample("css-examples/flexbox/basics/simple-example.html", '100%', 500)}}

+ +

Reference

+ +

CSS Properties

+ +
+ +
+ +

Glossary entries

+ +
+ +
+ +

Guides

+ +
+
Basic Concepts of Flexbox
+
An overview of the features of flexbox
+
Relationship of flexbox to other layout methods
+
How flexbox relates to other layout methods, and other CSS specifications
+
Aligning items in a flex container
+
How the Box Alignment properties work with flexbox.
+
Ordering flex items
+
Explaining the different ways to change the order and direction of items, and covering the potential issues in doing so.
+
Controlling Ratios of flex items along the main axis
+
This article explains the flex-grow, flex-shrink and flex-basis properties.
+
Mastering wrapping of flex items
+
How to create flex containers with multiple lines and control the display of the items in those lines.
+
Typical use cases of flexbox
+
Common design patterns that are typical flexbox use cases.
+
Backwards compatibility of Flexbox
+
Browser status of flexbox, interoperability issues and supporting older browsers and versions of the spec
+
+ +

External resources

+ + + +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSS3 Flexbox') }}{{ Spec2('CSS3 Flexbox') }}Initial definition.
+ +

Browser compatibility

+ +

{{CompatibilityTable()}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Basic support{{CompatGeckoDesktop("20.0")}}21.0{{property_prefix("-webkit")}}
+ 29.0
10.0{{property_prefix("-ms")}}
+ 11.0
12.106.1{{property_prefix("-webkit")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox Mobile (Gecko)AndroidIE PhoneOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown()}}4.41112.107.1{{property_prefix("-webkit")}}
+
+ +

 

diff --git a/files/pt-pt/web/css/css_flexible_box_layout/ordenacao_dos_itens_flex/index.html b/files/pt-pt/web/css/css_flexible_box_layout/ordenacao_dos_itens_flex/index.html new file mode 100644 index 0000000000..b2bc22df09 --- /dev/null +++ b/files/pt-pt/web/css/css_flexible_box_layout/ordenacao_dos_itens_flex/index.html @@ -0,0 +1,140 @@ +--- +title: Ordenação do itens Flex +slug: Web/CSS/CSS_Flexible_Box_Layout/ordenacao_dos_itens_flex +tags: + - Acessibilidade + - CSS + - Flex + - Guía + - direção + - flexbox + - ordem + - reverter +translation_of: Web/CSS/CSS_Flexible_Box_Layout/Ordering_Flex_Items +--- +

{{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/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" new file mode 100644 index 0000000000..83c570f33e --- /dev/null +++ "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" @@ -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_tipos/index.html b/files/pt-pt/web/css/css_tipos/index.html new file mode 100644 index 0000000000..ea7049f5a4 --- /dev/null +++ b/files/pt-pt/web/css/css_tipos/index.html @@ -0,0 +1,65 @@ +--- +title: CSS - Tipos de datos básicos +slug: Web/CSS/CSS_Tipos +tags: + - CSS + - Referencia + - Resumo + - Sinopse + - Tipos de Dados de CSS +translation_of: Web/CSS/CSS_Types +--- +
{{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/cursor/index.html b/files/pt-pt/web/css/cursor/index.html new file mode 100644 index 0000000000..152fe3b344 --- /dev/null +++ b/files/pt-pt/web/css/cursor/index.html @@ -0,0 +1,159 @@ +--- +title: cursor +slug: Web/CSS/cursor +tags: + - Referencia_CSS +translation_of: Web/CSS/cursor +--- +

{{ CSSRef() }}

+ +

Resumo

+ +

A propriedade {{ Cssxref("cursor") }} especifica o estilo do ponteiro do mouse quando estiver sobre o elemento.

+ + + +

Sintaxe

+ +

cursor: [ {{ mediawiki.external(' ,') }}* {{ mediawiki.external(' auto | crosshair | default | pointer | move | e-resize | ne-resize | nw-resize | n-resize | se-resize | sw-resize | s-resize | w-resize | text | wait | help | progress | copy | alias | context-menu | cell | not-allowed | col-resize | row-resize | no-drop | vertical-text | all-scroll | nesw-resize | nwse-resize | ns-resize | ew-resize ') }} ] | {{ Cssxref("inherit") }}

+ +

Valores

+ +
+
<url> 
+
URL of custom cursor. More than one URL may be provided as fallback, in case some cursor image types are not supported. A non-URL fallback (one of the other values) must be at the end of the fallback list. See Using URL values for the cursor property for more details.
+
default 
+
default cursor (typically an arrow)
+
auto 
+
equivalent to text when over text and default otherwise
+
crosshair 
+
cross cursor, often used to indicate selection in a bitmap
+
pointer 
+
cursor used when over links (typically a hand)
+
move 
+
move cursor
+
e-resize 
+
cursor for resizing the right edge of a box
+
ne-resize 
+
cursor for resizing the top right corner of a box
+
nw-resize 
+
cursor for resizing the top left corner of a box
+
n-resize 
+
cursor for resizing the top edge of a box
+
se-resize 
+
cursor for resizing the bottom right corner of a box
+
sw-resize 
+
cursor for resizing the bottom left corner of a box
+
s-resize 
+
cursor for resizing the bottom edge of a box
+
w-resize 
+
cursor for resizing the left edge of a box
+
text 
+
cursor indicating text can be selected (typically an I-beam)
+
wait 
+
cursor indicating the program is busy (sometimes an hourglass or a watch)
+
help 
+
cursor indicating help is available
+
progress 
+
cursor indicating that the program is busy but the user can still interact with it (unlike for busy)
+
copy 
+
cursor showing something that can be copied
+
alias 
+
cursor indicating an alias or shortcut is to be created
+
context-menu 
+
cursor indicating that a context menu is available under the cursor
+
cell 
+
cursor indicating that cells can be selected
+
not-allowed 
+
cursor showing that something cannot be done
+
col-resize 
+
cursor for resizing columns horizontally
+
row-resize 
+
cursor for resizing rows vertically
+
no-drop 
+
cursor showing that a drop is not allowed at the current location
+
vertical-text 
+
cursor indicating that vertical text can be selected (typically a sideways I-beam)
+
all-scroll 
+
cursor showing that something can be scrolled in any direction (panned)
+
nesw-resize 
+
cursor for resizing in the top-right or bottom-left directions
+
nwse-resize 
+
cursor for resizing in the top-left or bottom-right directions
+
ns-resize 
+
cursor for resizing up or down
+
ew-resize 
+
cursor for resizing left or right
+
+ +

Exemplos

+ +

View Live Examples

+ +
Inline:
+
+<span style="cursor: crosshair">Some Text</span>
+
+External:
+
+.pointer {
+	cursor: pointer;
+}
+.move {
+	cursor: move;
+}
+
+
+ +

Notas

+ +

While this property works on older browsers, not all values are fully supported.

+ +

Especificações

+ + + +

Compatibilidade com navegadores

+ + + + + + + + + + + + + + + + + + + + + + + + +
NavegadorVersão mais antiga/th>
Internet Explorer4
Firefox1.5
Netscape6
Opera7
+ +

Veja também

+ +

Categorias

+ +

Interwiki Language Links

+ +

{{ languages( { "en": "en/CSS/cursor", "fr": "fr/CSS/cursor", "pl": "pl/CSS/cursor" } ) }}

diff --git a/files/pt-pt/web/css/direction/index.html b/files/pt-pt/web/css/direction/index.html new file mode 100644 index 0000000000..a89e7a1b6c --- /dev/null +++ b/files/pt-pt/web/css/direction/index.html @@ -0,0 +1,46 @@ +--- +title: direction +slug: Web/CSS/direction +tags: + - Referencia_CSS +translation_of: Web/CSS/direction +--- +

+{{ CSSRef() }} +

+

Resumo

+

The direction property should be set to match the direction of the text: rtl for Hebrew or Arabic text and ltr for other scripts. This should normally be done as part of the document (e.g., using the dir attribute in HTML) rather than through direct use of CSS. +

The property sets the base text direction of block-level elements and the direction of embeddings created by the {{ Cssxref("unicode-bidi") }} property. It also sets the default alignment of text and block-level elements and the direction that cells flow within a table row. +

+ +

Sintaxe

+
direction: [ 'ltr' | 'rtl' | inherit ] ;
+
+

Valores

+
ltr 
The default value of direction. Text and other elements go from left to right +
rtl 
Text and other elements go from right to left +
+

For the direction property to have any effect on inline-level elements, the {{ Cssxref("unicode-bidi") }} property's value must be 'embed' or 'override'. +

+

Exemplos

+
blockquote {
+  direction : rtl ;
+}
+
+

Notas

+

Unlike the dir attribute in HTML, the direction property is not inherited from table columns into table cells, since CSS inheritance follows the document tree, and table cells are inside of the rows but not inside of the columns. +

+

Especificação

+ +

Veja também

+

{{ Cssxref("unicode-bidi") }} +

Categorias +

Interwiki Language Links +

{{ languages( { "en": "en/CSS/direction", "fr": "fr/CSS/direction", "pl": "pl/CSS/direction" } ) }} diff --git a/files/pt-pt/web/css/display/index.html b/files/pt-pt/web/css/display/index.html new file mode 100644 index 0000000000..43db53135e --- /dev/null +++ b/files/pt-pt/web/css/display/index.html @@ -0,0 +1,707 @@ +--- +title: display +slug: Web/CSS/display +tags: + - CSS + - CSS Display + - Propriedade de CSS +translation_of: Web/CSS/display +--- +
{{CSSRef}}
+ +

Esta propriedade display de CSS especifica o tipo de caixa de renderização utilizado para um elemento. Em HTML, os valores da propriedade display predefinidos têm o seu comportamento descrito nas especificações de HTML ou de uma folha de estilo predefinida do navegador ou do utilizador. O valor predefinido no XML é  inline, incluindo os elementos de SVG .

+ +

Em adição aos diferentes tipos de caixa de exibição, o valor none deixa-o desativar a exibição de um elemento; quando utiliza none, todos os elementos descendentes também têm as suas exibições desativadas. O documento é renderizado como se o elemento não existisse na árvore do documento.

+ +
/* <display-outside> values */
+display: block;
+display: inline;
+display: run-in;
+
+/* <display-inside> values */
+display: flow;
+display: flow-root;
+display: table;
+display: flex;
+display: grid;
+display: ruby;
+display: subgrid;
+
+/* <display-outside> plus <display-inside> values */
+display: block flow;
+display: inline table;
+display: flex run-in;
+
+/* <display-listitem> values */
+display: list-item;
+display: list-item block;
+display: list-item inline;
+display: list-item flow;
+display: list-item flow-root;
+display: list-item block flow;
+display: list-item block flow-root;
+display: flow list-item block;
+
+/* <display-internal> values */
+display: table-row-group;
+display: table-header-group;
+display: table-footer-group;
+display: table-row;
+display: table-cell;
+display: table-column-group;
+display: table-column;
+display: table-caption;
+display: ruby-base;
+display: ruby-text;
+display: ruby-base-container;
+display: ruby-text-container;
+
+/* <display-box> values */
+display: contents;
+display: none;
+
+/* <display-legacy> values */
+display: inline-block;
+display: inline-table;
+display: inline-flex;
+display: inline-grid;
+
+/* Global values */
+display: inherit;
+display: initial;
+display: unset;
+
+ +

{{cssinfo}}

+ +

Sintaxe

+ +

A propriedade display é especificada utilizando os valores chave. Os valores chave são agrupados em seis categorias:

+ + + +

Currently it's best to specify display using a single keyword; although the latest specifications allow you to combine some keywords, this is not yet well supported by browsers.

+ +

Valores

+ +
+
<display-outside>
+
These keywords specify the element’s outer display type, which is essentially its role in flow layout. They are defined as follows: + + + + + + + + + + + + + + + + + + + + + +
ValorDescrição
blockThe element generates a block element box.
inlineThe element generates one or more inline element boxes.
run-in {{experimental_inline}}The element generates a run-in box. Run-in elements act like inlines or blocks, depending on the surrounding elements. That is: +
    +
  • If the run-in box contains a block box, same as block.
  • +
  • If a block box follows the run-in box, the run-in box becomes the first inline box of the block box.
  • +
  • If an inline box follows, the run-in box becomes a block box.
  • +
+
+
+
<display-inside>
+
These keywords specify the element’s inner display type, which defines the type of formatting context that lays out its contents (assuming it is a non-replaced element). They are defined as follows: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ValueDescription
flow {{experimental_inline}}The element lays out its contents using flow layout (block-and-inline layout). +

If its outer display type is inline or run-in, and it is participating in a block or inline formatting context, then it generates an inline box. Otherwise it generates a block container box.

+ +

Depending on the value of other properties (such as {{cssxref("position")}}, {{cssxref("float")}}, or {{cssxref("overflow")}}) and whether it is itself participating in a block or inline formatting context, it either establishes a new block formatting context for its contents or integrates its contents into its parent formatting context.

+
flow-root {{experimental_inline}}The element generates a block element box that establishes a new block formatting context.
tableThese elements behave like {{HTMLElement("table")}} HTML elements. It defines a block-level box.
flexThe element behaves like a block element and lays out its content according to the flexbox model.
gridThe element behaves like a block element and lays out its content according to the grid model.
subgrid {{experimental_inline}}If the parent element has display:grid, the element itself and its content are laid out according to the grid model.
ruby {{experimental_inline}}The element behaves like an inline element and lays out its content according to the ruby formatting model. It behaves like the corresponding {{HTMLElement("ruby")}} HTML elements.
+
+
<display-listitem>
+
+

The element generates a block box for the content and a separate list-item inline box.

+ +

If no <display-inside> value is specified, the principal box’s inner display type defaults to flow. If no <display-outside> value is specified, the principal box’s outer display type defaults to block.

+
+
<display-internal>
+
+

Some layout models, such as table and ruby, have a complex internal structure, with several different roles that their children and descendants can fill. This section defines those "internal" display values, which only have meaning within that particular layout mode.

+ +

Unless otherwise specified, both the inner display type and the outer display type of elements using these display values are set to the given keyword.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ValorDescrição
table-row-groupThese elements behave like {{HTMLElement("tbody")}} HTML elements
table-header-groupThese elements behave like {{HTMLElement("thead")}} HTML elements.
table-footer-groupThese elements behave like {{HTMLElement("tfoot")}} HTML elements.
table-rowThese elements behave like {{HTMLElement("tr")}} HTML elements.
table-cellThese elements behave like {{HTMLElement("td")}} HTML elements.
table-column-groupThese elements behave like {{HTMLElement("colgroup")}} HTML elements.
table-columnThese elements behave like {{HTMLElement("col")}} HTML elements.
table-captionThese elements behave like {{HTMLElement("caption")}} HTML elements.
ruby-base {{experimental_inline}}These elements behave like {{HTMLElement("rb")}} elements.
ruby-text {{experimental_inline}}These elements behave like {{HTMLElement("rt")}} elements.
ruby-base-container {{experimental_inline}}These elements behave like {{HTMLElement("rbc")}} elements generated as anonymous boxes.
ruby-text-container {{experimental_inline}}These elements behave like {{HTMLElement("rtc")}} elements.
+
+
<display-box>
+
These values define whether an element generates display boxes at all. + + + + + + + + + + + + + + + + + +
ValorDescrição
contents {{experimental_inline}}These elements don't produce a specific box by themselves. They are replaced by their pseudo-box and their child boxes.
none +

Turns off the display of an element so that it has no effect on layout (the document is rendered as though the element did not exist). All descendant elements also have their display turned off.

+ +

To have an element take up the space that it would normally take, but without actually rendering anything, use the {{cssxref("visibility")}} property instead.

+
+
+
<display-legacy>
+
CSS 2 used a single-keyword syntax for the display property, requiring separate keywords for block-level and inline-level variants of the same layout mode. They are defined as follows: + + + + + + + + + + + + + + + + + + + + + + + + + +
ValorDescrição
inline-block +

The element generates a block element box that will be flowed with surrounding content as if it were a single inline box (behaving much like a replaced element would)

+ +

It is equivalent to inline flow-root.

+
inline-table +

The inline-table value does not have a direct mapping in HTML. It behaves like a {{HTMLElement("table")}} HTML element, but as an inline box, rather than a block-level box. Inside the table box is a block-level context.

+ +

It is equivalent to inline table.

+
inline-flex +

The element behaves like an inline element and lays out its content according to the flexbox model.

+ +

It is equivalent to inline flex.

+
inline-gridThe element behaves like an inline element and lays out its content according to the grid model.
+
+
+ +

Sintaxe formal

+ +
{{csssyntax}}
+ +

Exemplos

+ +

Elementos Hide

+ +

Conteúdo de HTML

+ +
<p>Visible text</p>
+<p class="secret">Invisible text</p>
+ +

Conteúdo de CSS

+ +
p.secret {
+  display: none;
+}
+ +

Resultado

+ +

{{EmbedLiveSample("Hide_element", 300, 60)}}

+ +

View Live Examples

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('CSS3 Display', '#the-display-properties', 'display')}}{{Spec2('CSS3 Display')}}Added run-in, flow, flow-root, contents, and multi-keyword values.
{{SpecName('CSS3 Ruby', '#ruby-display', 'display')}}{{Spec2('CSS3 Ruby')}}Added ruby, ruby-base, ruby-text, ruby-base-container, and ruby-text-container.
{{SpecName('CSS3 Grid', '#grid-containers', 'display')}}{{Spec2('CSS3 Grid')}}Added the grid box model values.
{{SpecName('CSS3 Flexbox', '#flex-containers', 'display')}}{{Spec2('CSS3 Flexbox')}}Added the flexible box model values.
{{SpecName('CSS2.1', 'visuren.html#display-prop', 'display')}}{{Spec2('CSS2.1')}}Added the table model values and inline-block.
{{SpecName('CSS1', '#display', 'display')}}{{Spec2('CSS1')}}Initial definition. Basic values: none, block, inline, and list-item.
+ +

Compatibilidade de navegador

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
none, inline and block1.0{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.0")}}4.07.01.0 (85)
inline-block1.0{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9")}}5.5[4]7.01.0 (85)
list-item1.0{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.0")}}6.07.01.0 (85)
run-in {{experimental_inline}}1.0 [5]{{CompatNo}}{{CompatNo}}8.07.01.0 (85)[5]
4.0 Removed in 32Not Blink versions (15 upwards)5.0 (532.5) Removed in 8.0
inline-table1.0{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9")}}8.07.01.0 (85)
table, table-cell, table-column, table-column-group, table-header-group, table-row-group, table-footer-group, table-row, and table-caption1.0{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.0")}}8.0 +

7.0

+
1.0 (85)
flex +

21.0{{property_prefix("-webkit")}}

+ +

29.0

+
{{CompatVersionUnknown}}{{CompatGeckoDesktop("18.0")}}[1]
+ {{CompatGeckoDesktop("20.0")}}
+

10{{property_prefix("-ms")}}[8]
+ 11

+
12.50 +

6.1{{property_prefix("-webkit")}}

+ +

9.0

+
inline-flex21.0{{property_prefix("-webkit")}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("18.0")}}[1]
+ {{CompatGeckoDesktop("20.0")}}
10{{property_prefix("-ms")}}[8]
+ 11
12.506.1{{property_prefix("-webkit")}}
grid {{experimental_inline}}{{CompatChrome(57)}}{{CompatVersionUnknown}}{{property_prefix("-ms")}}{{CompatGeckoDesktop("45.0")}}[6]10.0{{property_prefix("-ms")}}{{CompatOpera(44)}}TP
inline-grid {{experimental_inline}}{{CompatChrome(57)}}{{CompatVersionUnknown}}{{property_prefix("-ms")}}{{CompatGeckoDesktop("45.0")}}[6]10.0{{property_prefix("-ms")}}{{CompatOpera(44)}}TP
subgrid {{experimental_inline}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
ruby, ruby-base, ruby-text, ruby-base-container, ruby-text-container {{experimental_inline}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("34.0")}}[3]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
contents {{experimental_inline}}{{CompatChrome(58)}}[7]{{CompatNo}}{{CompatGeckoDesktop("37")}}[2]{{CompatNo}}{{CompatNo}}{{CompatNo}}
flow-root{{CompatChrome(58)}}{{CompatUnknown}}{{CompatGeckoDesktop("53.0")}}{{CompatUnknown}}{{CompatOpera(45)}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}7.0{{property_prefix("-webkit")}}
grid {{experimental_inline}}{{CompatChrome(57)}}{{CompatChrome(57)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOperaMobile(44)}}{{CompatUnknown}}
inline-grid {{experimental_inline}}{{CompatChrome(57)}}{{CompatChrome(57)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOperaMobile(44)}}{{CompatUnknown}}
flow-root{{CompatChrome(58)}}{{CompatChrome(58)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOperaMobile(45)}}{{CompatUnknown}}
+
+ +

[1] To activate flexbox support, for Firefox 18 and 19, the user has to change the about:config preference "layout.css.flexbox.enabled" to true. Multi-line flexbox are supported since Firefox 28.

+ +

[2] Before Firefox 37, the contents value was disabled by default, and could be enabled by setting the layout.css.display-contents.enabled pref to true. In Firefox 37, it was enabled by default, and in Firefox 53 the pref was removed altogether.

+ +

[3] CSS Ruby support is behind pref "layout.css.ruby.enabled". The user has to change this pref to true to activate this.

+ +

[4] In IE < 8, natural inline elements only.

+ +

[5] Not before inline-elements.

+ +

[6] CSS Grid support is unprefixed in Nightly/Alpha builds and behind pref "layout.css.grid.enabled" in Beta/release builds.

+ +

[7] In Chrome, the contents value is currently disabled by default, but can be enabled with the "Experimental Web Platform features" flag.

+ +

[8] In IE 10, only special prefixed values, -ms-flexbox and -ms-inline-flexbox, are recognized.

+ +

Consulte também

+ + + +
+ + + + + +
diff --git a/files/pt-pt/web/css/float/index.html b/files/pt-pt/web/css/float/index.html new file mode 100644 index 0000000000..62f8ddf017 --- /dev/null +++ b/files/pt-pt/web/css/float/index.html @@ -0,0 +1,111 @@ +--- +title: float +slug: Web/CSS/float +tags: + - Referencia_CSS +translation_of: Web/CSS/float +--- +

{{ CSSRef() }}

+ +

Resumo

+ +

A propriedade float especifica se um elemento deve flutuar pelo lado direito, pelo esquerdo ou não flutuar, onde os elementos inline envolverão ao redor dele.

+ + + +

Um elemento flutuante é um elemento onde o valor computado é diferente de none.

+ +

Note que se você estiver referenciando a esta propriedade do JavaScript como um membro do objeto element.style, você precisa escrever isto em cssFloat (veja a lista do DOM:CSS). Note também que para o IE você precisa escrever styleFloat.

+ +

Sintaxe

+ +

float: left | right | none | inherit

+ +

Valores

+ + + +

Exemplos

+ +

View Live Examples

+ +
<html>
+ <head>
+  <style type="text/css">
+   b
+   {
+     font-size: 25px;
+     float:right;
+   }
+  </style>
+ </head>
+ <body>
+
+  <p>
+    <b>HELLO!</b>
+    Isto é algum texto. Isto é algum texto. Isto é algum texto.
+    Isto é algum texto. Isto é algum texto. Isto é algum texto.
+    Isto é algum texto. Isto é algum texto. Isto é algum texto.
+    Isto é algum texto. Isto é algum texto. Isto é algum texto.
+    Isto é algum texto. Isto é algum texto. Isto é algum texto.
+    Isto é algum texto. Isto é algum texto. Isto é algum texto.
+    Isto é algum texto. Isto é algum texto. Isto é algum texto.
+    Isto é algum texto. Isto é algum texto. Isto é algum texto.
+  </p>
+
+</body>
+</html>
+
+ +

Notas

+ +

TODO: deve explicar como os flutuantes se posicionam. Mencionar o contexto de formatação de bloco.

+ +

Especificações

+ + + +

Compatibilidade com navegadores

+ + + + + + + + + + + + + + + + + + + + +
NavegadorVersão mais antiga
Internet Explorer4
Netscape4
Opera3.5
+ +

Veja também

+ +

{{ Cssxref("clear") }}, {{ Cssxref("display") }}, {{ Cssxref("position") }}, {{ Cssxref("float") }}

+ +

Categorias

+ +

Interwiki Language Links

+ +

{{ languages( { "en": "en/CSS/float", "fr": "fr/CSS/float" } ) }}

diff --git a/files/pt-pt/web/css/folhas_de_estilo_alternativas/index.html b/files/pt-pt/web/css/folhas_de_estilo_alternativas/index.html new file mode 100644 index 0000000000..250bb3eef9 --- /dev/null +++ b/files/pt-pt/web/css/folhas_de_estilo_alternativas/index.html @@ -0,0 +1,23 @@ +--- +title: Folhas de estilo alternativas +slug: Web/CSS/Folhas_de_estilo_alternativas +translation_of: Web/CSS/Alternative_style_sheets +--- +

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/font-size-adjust/index.html b/files/pt-pt/web/css/font-size-adjust/index.html new file mode 100644 index 0000000000..bc7b060a83 --- /dev/null +++ b/files/pt-pt/web/css/font-size-adjust/index.html @@ -0,0 +1,75 @@ +--- +title: font-size-adjust +slug: Web/CSS/font-size-adjust +tags: + - Referencia_CSS +translation_of: Web/CSS/font-size-adjust +--- +

{{ CSSRef() }}

+ +

Resumo

+ +

A propriedade {{ Cssxref("font-size-adjust") }} especifica que o tamanho da fonte deve ser escolhido baseado na altura das letras minúsculas antes da altura das letras maísculas.

+ +

Isto é útil desde a legibilidade das fontes, especialmente em tamanhos pequenos, é mais determinado pelo tamanho das letras minúsculas do que pelo tamanho das letras maíusculas. Isto pode causar problemas quando a primeira escolha {{ Cssxref("font-family") }} não está disponível e sua substituição tem uma relação de aspecto significativamente diferente (a relação do tamanho das fontes minúsculas para o tamanho da fonte).

+ +

Para fazer isto de forma que seja compatível com os navegadores que não suportam {{ Cssxref("font-size-adjust") }}, é especificado um número que a propriedade {{ Cssxref("font-size") }} é multiplicada por. Isto significa que o valor especificado para a propriedade deve geralmente ser a relação de aspecto da primeira escolha de fonte. Por exemplo, uma folha de estilo que especifica font-size: 16px; font-size-adjust: 0.5 está realmente especificando que as letras minúsculas da fonte deverão ter 8px de altura (16px vezes 0.5).

+ + + +

Sintaxe

+ +

font-size-adjust: <number> | none | {{ Cssxref("inherit") }}

+ +

Valores

+ +
+
none 
+
Escolha o tamanho da fonte baseado somente na propriedade {{ Cssxref("font-size") }}.
+
<number> 
+
+

Escolha o tamanho da fonte de modo que suas letras minúsculas (como determinado pela métrica x-height da fonte) sejam o número especificado de vezes pelo {{ Cssxref("font-size") }}.

+ +

O número especificado deve geralmente ser a relação de aspecto (relação de x-height para o tamanho da fonte) da primeira escolha de {{ Cssxref("font-family") }}. Isto significará que a primeira escolha de fonte, quando disponível, aparecerá no mesmo tamanho nos navegadores, se não suportarem o {{ Cssxref("font-size-adjust") }}.

+
+
+ +

Exemplos

+ +

View Live Examples

+ +
p{
+  font: 12px Verdana, sans-serif;
+  font-size-adjust: 0.58;
+}
+
+
+ +

Notas

+ +

Especificações

+ + + +

Compatibilidade com navegadores

+ +

Suportado em todas as plataformas começando em Gecko 1.9 / Firefox 3, mas suportado no Windows somente signitivamente mais cedo.

+ +

Veja também

+ +

{{ Cssxref("font-size") }}, {{ Cssxref("font-size-adjust") }}, {{ Cssxref("font-family") }}

+ +

Categorias

+ +

Interwiki Language Links

+ +

{{ languages( { "en": "en/CSS/font-size-adjust", "fr": "fr/CSS/font-size-adjust" } ) }}

diff --git a/files/pt-pt/web/css/font-size/index.html b/files/pt-pt/web/css/font-size/index.html new file mode 100644 index 0000000000..e3d0ca9fa8 --- /dev/null +++ b/files/pt-pt/web/css/font-size/index.html @@ -0,0 +1,83 @@ +--- +title: font-size +slug: Web/CSS/font-size +tags: + - Referencia_CSS +translation_of: Web/CSS/font-size +--- +

{{ CSSRef() }}

+ +

Resumo

+ +

The font-size property specifies the size of the font. The font size may, in turn, change the size of other things, since it is used to compute the value of em and ex length units.

+ + + +

Sintaxe

+ +

font-size: xx-small | x-small | small | medium | large | x-large | xx-large

+ +

font-size: smaller | larger

+ +

font-size: <length> | <percentage> | {{ Cssxref("inherit") }}

+ +

Valores

+ +
+
xx-small, x-small, small, medium, large, x-large, xx-large 
+
A set of absolute size keywords based on the user's default font size (which is medium). Similar to presentational HTML's <font size="1"> through <font size="7"> where the user's default font size is <font size="3">.
+
larger, smaller 
+
Larger or smaller than the parent element's font size, by roughly the ratio used to separate the absolute size keywords above.
+
<length> 
+
A positive length.
+
<percentage> 
+
A positive percentage of the parent element's font size.
+
+ +

It is best to avoid using values that are not relative to the user's default font size, such as <lengths> with units other than em or ex. However, if such values must be used, px are preferred over other units because their meaning does not vary depending on what the operating system thinks (generally incorrectly) the resolution of the monitor is.

+ +

Exemplos

+ +

View Live Examples

+ +
/* Set paragraph text to be very large. */
+p { font-size: xx-large }
+
+/* Set h1 (level 1 heading) text to be 2.5 times the size
+ * of the text around it. */
+h1 { font-size: 250% }
+
+/* Sets text enclosed within span tag to be 16px */
+span { font-size: 16px; }
+
+ +

Notas

+ +

em and ex units on the {{ Cssxref("font-size") }} property are relative to the parent element's font size (unlike all other properties, where they're relative to the font size on the element). This means em units and percentages do the same thing for {{ Cssxref("font-size") }}.

+ +

Especificações

+ + + +

== Compatibilidade com navegadores ==

+ +

Veja também

+ +

{{ Cssxref("font") }} {{ Cssxref("font-family") }}, {{ Cssxref("font-size") }}, {{ Cssxref("font-size-adjust") }}, {{ Cssxref("font-style") }}, {{ Cssxref("font-variant") }}, {{ Cssxref("font-weight") }}, {{ Cssxref("line-height") }}

+ +

Categorias

+ +

Interwiki Language Links

+ +

{{ languages( { "en": "en/CSS/font-size", "fr": "fr/CSS/font-size" } ) }}

diff --git a/files/pt-pt/web/css/font-smooth/index.html b/files/pt-pt/web/css/font-smooth/index.html new file mode 100644 index 0000000000..2cab7696d8 --- /dev/null +++ b/files/pt-pt/web/css/font-smooth/index.html @@ -0,0 +1,85 @@ +--- +title: font-smooth +slug: Web/CSS/font-smooth +translation_of: Web/CSS/font-smooth +--- +
{{ CSSRef }} {{ Non-standard_header }}
+ +

A propriedade CSS font-smooth  controla a aplicação anti-aliasing quando as fontes são renderizadas.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
{{ Xref_cssinitial() }}auto
Applies totodos os elementos e conteúdos gerados
{{ Xref_cssinherited() }}sim
Percentagesrelativo ao tamanho da fonte do elemento pai
Media{{ Xref_cssvisual() }}
{{ Xref_csscomputed() }}como especificado
+ +

Sintaxe

+ +
/* Keyword values */
+font-smooth: auto;
+font-smooth: never;
+font-smooth: always;
+
+/* <length> value */
+font-smooth: 2em;
+
+ +
+

WebKit implementa uma propriedade similar, mas com valores diferentes: -webkit-font-smoothing. Isto só funciona no Mac OS X/macOS.

+ + +
+ +
+

Firefox implementa uma propriedade similar, mas com valores diferentes: -moz-osx-font-smoothing. Isto só funciona no Mac OS X/macOS.

+ + +
+ +

Especificações

+ +

Embora presente no início (2002) rascunhos de CSS3 Fonts, font-smooth foi removido e esta especificação não está na faixa de padrões.

+ +

Compatibilidade dos Navegadores

+ + + +

{{Compat("css.properties.font-smooth")}}

+ +

Veja também

+ + diff --git a/files/pt-pt/web/css/font-style/index.html b/files/pt-pt/web/css/font-style/index.html new file mode 100644 index 0000000000..55bd8de94f --- /dev/null +++ b/files/pt-pt/web/css/font-style/index.html @@ -0,0 +1,40 @@ +--- +title: font-style +slug: Web/CSS/font-style +tags: + - Referencia_CSS +translation_of: Web/CSS/font-style +--- +

{{ CSSRef() }}

+ +

Sumário

+ +

A propriedade font-style especifica normal (também conhecido comoupright ouroman), itálico, e oblíquo faces dentro dofont-family.

+ +

{{cssinfo}}

+ +

Sintaxe

+ +

font-style: normal | italic | oblique

+ +

Valores

+ +
+
normal, oblique, italic 
+
Especifica que ouser-agent deve escolher a tipografia 'normal', 'oblique' ou 'italic' dentro do {{ Cssxref("font-family") }}.
+
+ +

Exemplos

+ +
h1 { font-style: italic }
+p { font-style: oblique }
+
+
+ +

Especificações

+ + diff --git a/files/pt-pt/web/css/font-weight/index.html b/files/pt-pt/web/css/font-weight/index.html new file mode 100644 index 0000000000..8879e55501 --- /dev/null +++ b/files/pt-pt/web/css/font-weight/index.html @@ -0,0 +1,119 @@ +--- +title: font-weight +slug: Web/CSS/font-weight +tags: + - Referencia_CSS +translation_of: Web/CSS/font-weight +--- +

{{ CSSRef() }}

+ +

Resumo

+ +

A propeidade {{ Cssxref("font-weight") }} especifica o peso ou o traço da fonte:

+ + + +

Sintaxe

+ +

font-weight: normal | bold | bolder | lighter | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900 | {{ Cssxref("inherit") }}

+ +

Valores

+ +
+
normal 
+
O peso normal da fonte. Semelhante ao 400.
+
bold 
+
O peso negrito da fonte. Semelhante ao 700.
+
lighter 
+
Um peso de fonte mais leve que o elemento pai (entre os pesos disponíveis da fonte).
+
bolder 
+
Um peso de fonte duas vezes grosso que o elemento pai (entre os pesos disponíveis da fonte).
+
100, 200, 300, 400, 500, 600, 700, 800, 900 
+
Os pesos numéricos de fontes para fontes que fornecem mais do que apenas normal e negrito. Se o peso exato fornecido não estiver disponível, então 600-900 utiliza o mais próximo e disponível peso mais duas vezes grosso (ou, se não houver, o peso mais leve disponível e mais próximo) e 100-500 utiliza o peso mais leve disponível e mais próximo (ou, se não houver, o peso mais escuro disponível e mais próximo). Significa que para fontes que fornecem apenas normal e negrito, 100-500 são normais e 600-900 são negritos.
+
+ +

Exemplos

+ +

HTML

+ +
<p>
+Alice começava a ficar muito cansada de sentar-se junto à irmã no banco e
+de não ter nada para fazer: uma ou duas vezes ela espiou o livro que a irmã
+estava a ler, mas não tinha fotos nem conversas nele, «e qual é a utilização
+de um livro», pensou Alice, «sem fotos ou conversas?»
+</p>
+
+<div>Sou quatro vezes grosso<br/>
+  <span>Sou mais leve</span>
+</div>
+
+ +

CSS

+ +
/* Definir o texto do parágrafo como negrito. */
+p {
+  font-weight: bold;
+}
+
+/* Defina o texto div para dois passos mais grossos do
+que o normal, mas menos que um negrito padrão. */
+div {
+ font-weight: 600;
+}
+
+/* Define o texto dentro da tag span para
+ser um passo mais leve que o pai. */
+span {
+  font-weight: lighter;
+}
+ +

Resultado

+ +

{{EmbedLiveSample("Exemplos","400","300")}}

+ +

Especificações

+ + + +

Compatibilidade com navegadores

+ + + + + + + + + + + + + + + + + + + + +
NavegadorVersão mais antiga
Internet Explorer3
Netscape4
Opera3.5
+ +

Veja também

+ +

{{ Cssxref("font") }} {{ Cssxref("font-family") }}, {{ Cssxref("font-size") }}, {{ Cssxref("font-size-adjust") }}, {{ Cssxref("font-style") }}, {{ Cssxref("font-variant") }}, {{ Cssxref("font-weight") }}, {{ Cssxref("line-height") }}

+ +

Categorias

+ +

Interwiki Language Links

+ +

{{ languages( { "en": "en/CSS/font-weight", "fr": "fr/CSS/font-weight" } ) }}

diff --git a/files/pt-pt/web/css/font/index.html b/files/pt-pt/web/css/font/index.html new file mode 100644 index 0000000000..e212941e9f --- /dev/null +++ b/files/pt-pt/web/css/font/index.html @@ -0,0 +1,140 @@ +--- +title: font +slug: Web/CSS/font +tags: + - Referencia_CSS +translation_of: Web/CSS/font +--- +

{{ CSSRef() }}

+ +

Resumo

+ +

The font property is a shorthand property for setting {{ Cssxref("font-style") }}, {{ Cssxref("font-variant") }}, {{ Cssxref("font-weight") }}, {{ Cssxref("font-size") }}, {{ Cssxref("line-height") }} and {{ Cssxref("font-family") }} at the same place in the style sheet.

+ + + +

 

+ +

Sintaxe

+ +

font: [ <font-style> || <font-variant> || <font-weight> ]? <font-size> [ / <line-height> ]? <font-family>

+ +

font: caption | icon | menu | message-box | small-caption | status-bar | -moz-window | -moz-document | -moz-workspace | -moz-desktop | -moz-info | -moz-dialog | -moz-button | -moz-pull-down-menu | -moz-list | -moz-field

+ +

font: {{ Cssxref("inherit") }}

+ +

Valores

+ +

Using the {{ Cssxref("font") }} shorthand property sets the longhand properties as specified, and sets all other font-related properties to their initial values.

+ +

See {{ Cssxref("font-style") }}, {{ Cssxref("font-variant") }}, {{ Cssxref("font-weight") }}, {{ Cssxref("font-size") }}, and {{ Cssxref("font-family") }} for legal values of each property.

+ +

System fonts can also be specified using the {{ Cssxref("font") }} property,instead of specifying individual longhand properties:

+ +
+
caption 
+
The font used for captioned controls (e.g., buttons, drop-downs, etc.).
+
icon 
+
The font used to label icons.
+
menu 
+
The font used in menus (e.g., dropdown menus and menu lists).
+
message-box 
+
The font used in dialog boxes.
+
small-caption 
+
The font used for labeling small controls.
+
status-bar 
+
The font used in window status bars.
+
-moz-window 
+
 
+
-moz-document 
+
 
+
-moz-workspace 
+
 
+
-moz-desktop 
+
 
+
-moz-info 
+
 
+
-moz-dialog 
+
 
+
-moz-button 
+
 
+
-moz-pull-down-menu 
+
 
+
-moz-list 
+
 
+
-moz-field 
+
 
+
+ +

Exemplos

+ +

View Live Examples

+ +
/* Set the font size to 12pt and the line height to 14pt. Set the font family to sans-serif */
+p { font: 12pt/14pt sans-serif }
+
+ +
/* Set the font size to 80% of the parent tag or default value (if no parent tag present)
+and set the font family to sans-serif */
+p { font: 80% sans-serif }
+
+ +
/* Set the font weight to bold, the font-style to italic, the font size to large,
+and the font family to serif. */
+p { font: bold italic large serif }
+
+ +

Notas

+ +

The {{ Cssxref("font-size") }} and {{ Cssxref("font-family") }} parts of the shorthand are mandatory. Omitting them is a syntax error, and causes the entire declaration to be ignored.

+ +

Properties for which no values are given are set to their initial value, which is normal for all properties that can be omitted ({{ Cssxref("font-style") }}, {{ Cssxref("font-variant") }}, {{ Cssxref("font-weight") }}, and {{ Cssxref("line-height") }}).

+ +

The {{ Cssxref("font-size-adjust") }} property is also set to its initial value (none) when the {{ Cssxref("font") }} shorthand property is specified.

+ +

Especificações

+ + + +

Compatibilidade com navegadores

+ + + + + + + + + + + + + + + + + + + + +
NavegadorVersão mais antiga
Internet Explorer3
Netscape4
Opera3.5
+ +

Veja também

+ +

{{ Cssxref("font") }} {{ Cssxref("font-family") }}, {{ Cssxref("font-size") }}, {{ Cssxref("font-size-adjust") }}, {{ Cssxref("font-style") }}, {{ Cssxref("font-variant") }}, {{ Cssxref("font-weight") }}, {{ Cssxref("line-height") }}

+ +

Categorias

+ +

Interwiki Language Links

+ +

{{ languages( { "en": "en/CSS/font", "fr": "fr/CSS/font", "pl": "pl/CSS/font" } ) }}

diff --git a/files/pt-pt/web/css/grid-gap/index.html b/files/pt-pt/web/css/grid-gap/index.html new file mode 100644 index 0000000000..fef808f4cb --- /dev/null +++ b/files/pt-pt/web/css/grid-gap/index.html @@ -0,0 +1,177 @@ +--- +title: grid-gap +slug: Web/CSS/grid-gap +translation_of: Web/CSS/gap +--- +

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/height/index.html b/files/pt-pt/web/css/height/index.html new file mode 100644 index 0000000000..e3b2b71c2c --- /dev/null +++ b/files/pt-pt/web/css/height/index.html @@ -0,0 +1,86 @@ +--- +title: height +slug: Web/CSS/height +tags: + - Referencia_CSS +translation_of: Web/CSS/height +--- +

{{ CSSRef() }}

+ +

Resumo

+ +

A propriedade height é usada para configurar a altura dada a um elemento.

+ + + +

Sintaxe

+ +
 height: [ <length> || <percentage> ] auto | inherit
+
+ +

Valores

+ + + +

Exemplos

+ +

View Live Examples

+ +
table{height: 100%;}
+
+img{height: 200px;}
+
+form{height: auto;}
+
+ +

== Notas ==

+ +

Especificações

+ + + +

Compatibilidade com navegadores

+ + + + + + + + + + + + + + + + + + + + +
NavegadorVersão mais antiga
Internet Explorer4
Netscape4
Opera3.5
+ +

Veja também

+ +

box model, {{ Cssxref("width") }}, {{ Cssxref("-moz-box-sizing") }}

+ +

Categorias

+ +

Interwiki Language Links

+ +

{{ languages( { "en": "en/CSS/height", "fr": "fr/CSS/height" } ) }}

diff --git a/files/pt-pt/web/css/index.html b/files/pt-pt/web/css/index.html new file mode 100644 index 0000000000..9f7a65ea5f --- /dev/null +++ b/files/pt-pt/web/css/index.html @@ -0,0 +1,105 @@ +--- +title: 'CSS: Folhas de Estilo em Cascata' +slug: Web/CSS +tags: + - Apresentação + - CSS + - Desenho + - Design + - Disposição + - Estilos + - Folhas de Estilo em Cascata + - Folhas de estilo + - Landing + - Referencia + - 'l10n:prioridade' +translation_of: Web/CSS +--- +
{{CSSRef}}
+ +

Folhas de Estilo em Cascata (CSS - Cascading Style Sheets) é uma linguagem de folha de estilo utilizada para descrever a apresentação de um documento escrito em HTML or XML (incluindo dialetos de XML, tais como SVG, MathML ou {{Glossary("XHTML", "", 1)}}). CSS descreve como os elementos deverão ser renderizados no ecrã, no papel, na fala, ou em outra média.

+ +

CSS é uma das principais linguagens da Web aberta e está estandardizada nos navegadores de acordo com a especificação W3C. Desenvolvida em níveis, CSS1 está agora obsoleta, CSS2.1 é a recomendação, e CSS3, agora divida em pequenos módulos, está a progredir a caminho da estandardização

+ +
+ + +
+
+

Tutoriais

+ +

A nossa Área de Aprendizagem de CSS apresenta múltiplos módulos que ensinam CSS desde o início  — não é necessário conhecimento prévio.

+ +
+
Introdução ao CSS
+
Este módulo permite-lhe começar com os básicos de como o CSS funciona, incluindo selectores e propriedades, escrever regras CSS, aplicar CSS a HTML, como especificar comprimento, cor e outras unidades em CSS, cascata e herança, modelos básicos de caixa e depuração de CSS.
+
Estilizar texto
+
Aqui aprendemos os fundamentos do estilo do texto, incluindo a definição da fonte, negrito e itálico, espaçamento entre linhas e letras, e sombras e outras características do texto. Nós terminamos o módulo, aplicando fontes personalizadas à sua página, e estilizando listas e links.
+
Estilizar caixas
+
A seguir, focamos em estilizar caixas, um dos passos fundamentais para a criação de uma página web. Neste módulo, recapitulamos o modelo da caixa e depois aprendemos a controlar a disposição das caixas, definindo preenchimentos, bordas e margens, cores de fundo personalizadas, imagens e outras características, bem como características mais avancadas como sombras e filtros nas caixas.
+
Disposição de CSS (layout)
+
Até agora, já analisámos os fundamentos do CSS, como estilizar os textos, e como estilizar e manipular as caixas que o seu conteúdo contém. Agora é altura de ver como colocar as suas caixas no lugar certo em relação ao {{Glossary("layout viewport", "viewport")}}, e umas às outras. Cobrimos os pré-requisitos necessários para que possa agora mergulhar profundamente no layout do CSS, observando diferentes configurações de visualização, métodos tradicionais de layout envolvendo float e posicionamento, e novas ferramentas de posicionamento como o flexbox.
+
+
+ +
+

Referência

+ + + +

Cookbook

+ +

The CSS layout cookbook aims to bring together recipes for common layout patterns, things you might need to implement in your own sites. In addition to providing code you can use as a starting point in your projects, these recipes highlight the different ways layout specifications can be used, and the choices you can make as a developer.

+ +

Ferramentas para o desenvolvimento de CSS

+ + + +

Erros de metadados

+ +
    +
  • Firefox: {{bug(1323667)}}
  • +
+
+
+
+ +

Consultar também:

+ + diff --git a/files/pt-pt/web/css/inherit/index.html b/files/pt-pt/web/css/inherit/index.html new file mode 100644 index 0000000000..8bfcd334e5 --- /dev/null +++ b/files/pt-pt/web/css/inherit/index.html @@ -0,0 +1,7 @@ +--- +title: inherit +slug: Web/CSS/inherit +translation_of: Web/CSS/inherit +--- +

Herda propriedade do elemento pai. +

diff --git a/files/pt-pt/web/css/layout_de_grelha_css/index.html b/files/pt-pt/web/css/layout_de_grelha_css/index.html new file mode 100644 index 0000000000..db142d2dde --- /dev/null +++ b/files/pt-pt/web/css/layout_de_grelha_css/index.html @@ -0,0 +1,250 @@ +--- +title: CSS - Layout de Grade +slug: Web/CSS/layout_de_grelha_css +tags: + - CSS + - Grades + - Layout + - Layout de Grade + - Referencia + - Resumo +translation_of: Web/CSS/CSS_Grid_Layout +--- +

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/list-style/index.html b/files/pt-pt/web/css/list-style/index.html new file mode 100644 index 0000000000..3a6cf6d36d --- /dev/null +++ b/files/pt-pt/web/css/list-style/index.html @@ -0,0 +1,79 @@ +--- +title: list-style +slug: Web/CSS/list-style +tags: + - Referencia_CSS +translation_of: Web/CSS/list-style +--- +

{{ CSSRef() }}

+ +

Resumo

+ +

A propriedade list-style é uma propriedade usada para configurar list-style-type, list-style-image, e list-style-position.

+ + + +

Sintaxe

+ +
 list-style: [disc | circle | square | decimal | lower-roman | upper-roman | lower-alpha | upper-alpha | none] || [inside | outside] || [<url> | none]
+
+ +

Valores

+ +

disc, circle, square, decimal, lower-roman, upper-roman, lower-alpha, upper-alpha, inside, outside, <url>, none

+ +

Exemplos

+ +

HTML

+ +
List 1
+<ul class="one">
+  <li>List Item1</li>
+  <li>List Item2</li>
+  <li>List Item3</li>
+</ul>
+List 2
+<ul class="two">
+  <li>List Item A</li>
+  <li>List Item B</li>
+  <li>List Item C</li>
+</ul>
+
+ +

CSS

+ +
.one {
+  list-style: circle;
+}
+
+.two {
+  list-style: square inside;
+}
+ +

Result

+ +

{{EmbedLiveSample('Exemplos')}}

+ +

Especificações

+ + + +

* {{ mediawiki.external('http://www.w3.org/TR/CSS21/visudet.html#the-height-property CSS 2.1') }} == Compatibilidade com navegadores == <table class="standard-table"> <tr> <th>Navegador</th> <th>Versão mais antiga</th> </tr> <tr> <td>Internet Explorer</td> <td>4</td> </tr> <tr> <td>Netscape</td> <td>4</td> </tr> <tr> <td>Opera</td> <td>3.5</td> </tr> </table>

+ +

Veja também

+ +

list-style-image, {{ Cssxref("list-style-type") }}, {{ Cssxref("list-style-position") }}

+ +

Categorias

+ +

Interwiki Language Links

+ +

{{ languages( { "en": "en/CSS/list-style", "fr": "fr/CSS/list-style" } ) }}

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" new file mode 100644 index 0000000000..49df122031 --- /dev/null +++ "b/files/pt-pt/web/css/m\303\251dia_paginada/index.html" @@ -0,0 +1,19 @@ +--- +title: Média paginada +slug: Web/CSS/Média_paginada +tags: + - CSS + - CSS3 + - Quebras de Página +translation_of: Web/CSS/Paged_Media +--- +

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/pseudoclasses/index.html b/files/pt-pt/web/css/pseudoclasses/index.html new file mode 100644 index 0000000000..d65bef9e51 --- /dev/null +++ b/files/pt-pt/web/css/pseudoclasses/index.html @@ -0,0 +1,165 @@ +--- +title: Pseudoclasses +slug: Web/CSS/Pseudoclasses +tags: + - CSS + - Pseudoclasse + - Referencia + - Resumo + - Seletores + - Sinopse +translation_of: Web/CSS/Pseudo-classes +--- +
{{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 new file mode 100644 index 0000000000..780d17c378 --- /dev/null +++ b/files/pt-pt/web/css/pseudoelementos/index.html @@ -0,0 +1,104 @@ +--- +title: Pseudoelementos +slug: Web/CSS/Pseudoelementos +tags: + - CSS + - Pseudoelemento + - Referencia + - Resumo + - Seletores + - Sinopse +translation_of: Web/CSS/Pseudo-elements +--- +
{{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/refer\303\252ncia_css/index.html" "b/files/pt-pt/web/css/refer\303\252ncia_css/index.html" new file mode 100644 index 0000000000..1be349b1c9 --- /dev/null +++ "b/files/pt-pt/web/css/refer\303\252ncia_css/index.html" @@ -0,0 +1,171 @@ +--- +title: CSS - Referência +slug: Web/CSS/Referência_CSS +tags: + - CSS + - Referencia + - Resumo + - Sinopse + - 'l10n:priority' +translation_of: Web/CSS/Reference +--- +
{{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/replaced_element/index.html b/files/pt-pt/web/css/replaced_element/index.html new file mode 100644 index 0000000000..47f2e968f9 --- /dev/null +++ b/files/pt-pt/web/css/replaced_element/index.html @@ -0,0 +1,23 @@ +--- +title: Elemento substituído +slug: Web/CSS/Replaced_element +tags: + - CSS + - Element +translation_of: Web/CSS/Replaced_element +--- +
{{CSSRef()}}
+ +

Resumo

+ +

No CSS, um elemento substituído é um elemento cuja representação está fora do âmbito do CSS. Estes são um tipo de objecto externo cuja representação é independente do CSS. Elementos substituídos típicos são {{HTMLElement("img")}}, {{HTMLElement("object")}}, {{HTMLElement("video")}} ou elementos de formulário como {{HTMLElement("textarea")}} e {{HTMLElement("input")}}Alguns elementos, como {{HTMLElement("audio")}} ou {{HTMLElement("canvas")}} são elementos só em casos específicos substituído.  Objetos inseridos usando as propriedades CSS {{cssxref("content")}} são elementos substituídos anônimos.

+ +

CSS manipula elementos substituídos especificamente em alguns casos, como ao calcular margens e alguns valores automáticos.

+ +

Note-se que alguns elementos substituído,mas não todos,têm dimensões intrínsecas ou uma linha de base definida (baseline), que é utilizada por algumas propriedades CSS como {{cssxref("vertical-align")}}.

+ +

Veja também

+ + diff --git a/files/pt-pt/web/css/shorthand_properties/index.html b/files/pt-pt/web/css/shorthand_properties/index.html new file mode 100644 index 0000000000..8bfb4a4bbc --- /dev/null +++ b/files/pt-pt/web/css/shorthand_properties/index.html @@ -0,0 +1,143 @@ +--- +title: Propriedades de taquigrafia +slug: Web/CSS/Shorthand_properties +tags: + - CSS + - Guía + - Referencia +translation_of: Web/CSS/Shorthand_properties +--- +
{{cssref}}
+ +

Propriedades de taquigrafia são propriedades de CSS que lhe permitem definir simultaneamente os valores de várias outras propriedades de CSS. Ao utilizar uma propriedade de taquigrafia, pode escrever folhas de estilo mais concisas (e muitas vezes mais legíveis), poupando tempo e energia .

+ +

The CSS specification defines shorthand properties to group the definition of common properties acting on the same theme. For instance, the CSS {{cssxref("background")}} property is a shorthand property that's able to define the values of {{cssxref("background-color")}}, {{cssxref("background-image")}}, {{cssxref("background-repeat")}}, and {{cssxref("background-position")}}. Similarly, the most common font-related properties can be defined using the shorthand {{cssxref("font")}}, and the different margins around a box can be defined using the {{cssxref("margin")}} shorthand.

+ +

Tricky edge cases

+ +

Even if they are very convenient to use, there are a few edge cases to keep in mind when using them:

+ +
    +
  1. A value which is not specified is set to its initial value. That sounds anecdotal, but it really means that it overrides previously set values. Therefore: + +
    background-color: red;
    +background: url(images/bg.gif) no-repeat left top;
    +
    + will not set the color of the background to red but to {{cssxref("background-color")}}'s default, transparent, as the second rule has precedence.
  2. +
  3. Only the individual properties values can inherit. As missing values are replaced by their initial value, it is impossible to allow inheritance of individual properties by omitting them. The keyword inherit can be applied to a property, but only as a whole, not as a keyword for one value or another. That means that the only way to make some specific value to be inherited is to use the longhand property with the keyword inherit.
  4. +
  5. Shorthand properties try not to force a specific order for the values of the properties they replace. This works well when these properties use values of different types, as the order has no importance, but this does not work as easily when several properties can have identical values. Handling of these cases are grouped in several categories: +
      +
    1. Shorthands handling properties related to edges of a box, like {{cssxref("border-style")}}, {{cssxref("margin")}} or {{cssxref("padding")}}, always use a consistent 1-to-4-value syntax representing those edges: + + + + + + + + + + + + + + + + + + + +
      border1.pngThe 1-value syntax: border-width: 1em — The unique value represents all edges
      border2.pngThe 2-value syntax: border-width: 1em 2em — The first value represents the vertical, that is top and bottom, edges, the second the horizontal ones, that is the left and right ones.
      border3.pngThe 3-value syntax: border-width: 1em 2em 3em — The first value represents the top edge, the second, the horizontal, that is left and right, ones, and the third value the bottom edge
      border4.png +

      The 4-value syntax: border-width: 1em 2em 3em 4em — The four values represent the top, right, bottom and left edges respectively, always in that order, that is clock-wise starting at the top (The initial letter of Top-Right-Bottom-Left matches the order of the consonant of the word trouble: TRBL)

      +
      +
    2. +
    3. Similarly, shorthands handling properties related to corners of a box, like {{cssxref("border-radius")}}, always use a consistent 1-to-4-value syntax representing those corners: + + + + + + + + + + + + + + + + + + + +
      corner1.pngThe 1-value syntax: border-radius: 1em — The unique value represents all corners
      corner2.pngThe 2-value syntax: border-radius: 1em 2em — The first value represents the top left and bottom right corner, the second the top right and bottom left ones.
      corner3.pngThe 3-value syntax: border-radius: 1em 2em 3em — The first value represents the top left corner, the second the top right and bottom left ones, and the third value the bottom right corner
      corner4.png +

      The 4-value syntax: border-radius: 1em 2em 3em 4em — The four values represent the top left, top right, bottom right and bottom left corners respectively, always in that order, that is clock-wise starting at the top left.

      +
      +
    4. +
    +
  6. +
+ +

Propriedades de segundo plano

+ +

A background with the following properties ...

+ +
background-color: #000;
+background-image: url(images/bg.gif);
+background-repeat: no-repeat;
+background-position: left top;
+ +

... can be shortened to just one declaration:

+ +
background: #000 url(images/bg.gif) no-repeat left top;
+ +

(The shorthand form is actually the equivalent of the longhand properties above plus background-attachment: scroll and, in CSS3, some additional properties.)

+ +

Propriedades de tipo de letra

+ +

The following declarations ...

+ +
font-style: italic;
+font-weight: bold;
+font-size: .8em;
+line-height: 1.2;
+font-family: Arial, sans-serif;
+ +

... can be shortened to the following:

+ +
font: italic bold .8em/1.2 Arial, sans-serif;
+ +

This shorthand declaration is actually equivalent to the longhand declarations above plus font-variant: normal and font-size-adjust: none (CSS2.0 / CSS3), font-stretch: normal (CSS3).

+ +

Propriedades de margem

+ +

With borders, the width, color, and style can be simplified into one declaration. For example, the following CSS ...

+ +
border-width: 1px;
+border-style: solid;
+border-color: #000;
+ +

... can be simplified as:

+ +
border: 1px solid #000;
+ +

Margin and padding properties

+ +

Shorthand versions of margin and padding values work the same way. The following CSS declarations ...

+ +
margin-top: 10px;
+margin-right: 5px;
+margin-bottom: 10px;
+margin-left: 5px;
+ +

... are the same as the following declaration. Note that the values are in clockwise order, beginning at the top: top, right, bottom, then left (TRBL, the consonants in "trouble").

+ +
margin: 10px 5px 10px 5px;
+ +

Consulte também

+ + diff --git a/files/pt-pt/web/css/top/index.html b/files/pt-pt/web/css/top/index.html new file mode 100644 index 0000000000..3e2f304073 --- /dev/null +++ b/files/pt-pt/web/css/top/index.html @@ -0,0 +1,54 @@ +--- +title: top +slug: Web/CSS/top +translation_of: Web/CSS/top +--- +

« Referência CSS
+

+

Resumo

+

A propriedade top especifica o posicionamento vertical do elemento de acordo com o topo.

+

Para elementos absolutamente posicionados (com a propriedade position ajustada como absolute ou fixed) especifica a distância apartir a margem superior do objeto (até onde vai o background).

+

Para relativamente posicionados (com a propriedade position ajustada como relative) especifica a distância de acordo com o posicionamento do objeto se a propriedade position fosse qualquer uma que não absolute, relative ou fixed.

+ +

Sintáxe

+
top: <length> | <percentage> | auto | inherit
+
+

Exemplos

+
<?xml version="1.0" encoding="utf-8"?>
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
+<head>
+<meta http-equiv="Content-Type" content="application/xhtml+xml" />
+<title>Mozilla.org altura, topo, esquerda, largura e direita - CSS</title>
+<style type="text/css">
+/* As medidas de body podem ser mudadas para px para testar o comportamento da div */
+body{
+  width: 100%;
+  height: 100%;
+}
+/* agora a div pode operar com porcentagem (a altura e a largura do body são a referência) */
+div{
+  position: absolute;
+  left: 15%;
+  top: 30%;
+  bottom: 30%;
+  width: 70%;
+  height: 40%;
+  text-align: left;
+  border: 3px #000 solid;
+  background: #CCC;
+}
+</style>
+</head>
+<body>
+<center>
+  <div>...Qualquer conteúdo...</div>
+</center>
+</body>
+</html>
+
+

Notas

+

top é mais relevante que bottom porque o alinhamento vertical padrão é no topo. Com mais propriedades de posicionamento, top torna-se dispensável.

+

Veja mais

+

position, right, bottom, left

diff --git a/files/pt-pt/web/css/transform/index.html b/files/pt-pt/web/css/transform/index.html new file mode 100644 index 0000000000..8dc2ee3951 --- /dev/null +++ b/files/pt-pt/web/css/transform/index.html @@ -0,0 +1,238 @@ +--- +title: transform +slug: Web/CSS/transform +tags: + - CSS + - Experimental + - NeedsBrowserCompatibility + - Propriedade + - Propriedade de CSS + - Referencia + - Transforms +translation_of: Web/CSS/transform +--- +
{{CSSRef}}{{SeeCompatTable}}
+ +

The CSS transform property lets you modify the coordinate space of the CSS visual formatting model. Using it, elements can be translated, rotated, scaled, and skewed.

+ +
/* Keyword values */
+transform: none;
+
+/* Function values */
+transform: matrix(1.0, 2.0, 3.0, 4.0, 5.0, 6.0);
+transform: translate(12px, 50%);
+transform: translateX(2em);
+transform: translateY(3in);
+transform: scale(2, 0.5);
+transform: scaleX(2);
+transform: scaleY(0.5);
+transform: rotate(0.5turn);
+transform: skew(30deg, 20deg);
+transform: skewX(30deg);
+transform: skewY(1.07rad);
+transform: matrix3d(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
+transform: translate3d(12px, 50%, 3em);
+transform: translateZ(2px);
+transform: scale3d(2.5, 1.2, 0.3);
+transform: scaleZ(0.3);
+transform: rotate3d(1, 2.0, 3.0, 10deg);
+transform: rotateX(10deg);
+transform: rotateY(10deg);
+transform: rotateZ(10deg);
+transform: perspective(17px);
+
+/* Multiple function values */
+transform: translateX(10px) rotate(10deg) translateY(5px);
+
+/* Global values */
+transform: inherit;
+transform: initial;
+transform: unset;
+
+ +

If the property has a value different than none, a stacking context will be created. In that case the object will act as a containing block for position: fixed elements that it contains.

+ +

{{cssinfo}}

+ +

Sintaxe

+ +

The transform property may be specified as either the keyword value none or as one or more <transform-function> values.

+ +

Valores

+ +
+
<transform-function>
+
One or more of the CSS transform functions to be applied, see below. Composite transforms are effectively applied in order from right to left.
+
none
+
Specifies that no transform should be applied.
+
+ +

Formal syntax

+ +
{{csssyntax}}
+ +

Exemplos

+ +

See Using CSS transforms.

+ +

Live example

+ +

HTML content

+ +
<p>Transformed element</p>
+ +

CSS content

+ +
p {
+  border: solid red;
+
+  -webkit-transform: translate(100px) rotate(20deg);
+  -webkit-transform-origin: 0 -250px;
+
+  transform: translate(100px) rotate(20deg);
+  transform-origin: 0 -250px;
+}
+ +

{{EmbedLiveSample("Live_example", "400", "170")}}

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS Transforms 2', '#transform-functions', 'transform')}}{{Spec2('CSS Transforms 2')}}Adds 3D transform functions.
{{SpecName('CSS3 Transforms', '#transform-property', 'transform')}}{{Spec2('CSS3 Transforms')}}Initial definition
+ +

Compatibilidade do navegador

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FunionalidadeChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}} {{property_prefix("-webkit")}}
+ 36
{{CompatVersionUnknown}}{{property_prefix("-webkit")}}
+ {{CompatVersionUnknown}}
{{CompatGeckoDesktop("1.9.1")}}{{property_prefix("-moz")}}[1]
+ {{CompatGeckoDesktop("16.0")}}[2]
9.0{{property_prefix("-ms")}}[3]
+ 10.0
10.5{{property_prefix("-o")}}
+ 12.10
+ 15.0{{property_prefix("-webkit")}}
+ 23
3.1{{property_prefix("-webkit")}}
+ 9.0
Suporte 3D12.0{{property_prefix("-webkit")}}
+ 36
{{CompatVersionUnknown}}10.0{{property_prefix("-moz")}}
+ {{CompatGeckoDesktop("16.0")}}
10.015.0{{property_prefix("-webkit")}}
+ 23
+

4.0{{property_prefix("-webkit")}}
+ 9.0

+
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatAndroid(2.1)}}{{property_prefix("-webkit")}}[4]{{CompatVersionUnknown}}{{property_prefix("-webkit")}}{{CompatVersionUnknown}}{{property_prefix("-webkit")}}
+ {{CompatVersionUnknown}}
{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+ 11.0{{property_prefix("-webkit")}}[5]
11.5{{property_prefix("-webkit")}}3.2 {{CompatVersionUnknown}}{{property_prefix("-webkit")}}
+ 9.0
Suporte 3D{{CompatAndroid(3.0)}}{{property_prefix("-webkit")}}{{CompatVersionUnknown}}{{ property_prefix("-webkit")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}22{{property_prefix("-webkit")}}3.2 {{CompatVersionUnknown}}{{property_prefix("-webkit")}}
+ 9.0
+
+ +

[1] Gecko 14.0 removed the experimental support for skew(), but it was reintroduced in Gecko 15.0 for compatibility reasons. As it is non-standard and will likely be removed in the future, do not use it.

+ +

[2] Before Firefox 16, the translation values of matrix() and matrix3d() could be {{cssxref("<length>")}}, in addition to the standard {{cssxref("<number>")}}.

+ +

In addition to the unprefixed support, Gecko 44.0 {{geckoRelease("44.0")}} added support for a -webkit prefixed version of the property for web compatibility reasons behind the preference layout.css.prefixes.webkit, defaulting to false. Since Gecko 49.0 {{geckoRelease("49.0")}} the preference defaults to true.

+ +

[3] Internet Explorer 5.5 or later supports a proprietary Matrix Filter which can be used to achieve a similar effect.

+ +

Internet Explorer 9.0 or earlier has no support for 3D transforms. Mixing 3D and 2D transform functions, such as -ms-transform:rotate(10deg) translateZ(0);, will prevent the entire property from being applied.

+ +

Internet Explorer does not support the global values initial and unset.

+ +

[4] Android 2.3 has a bug where input forms will "jump" when typing, if any container element has a -webkit-transform.

+ +

[5] Internet Explorer 11.0 supports the {{property_prefix("-webkit")}} prefixed variant as an alias for the default one.

+ +

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" new file mode 100644 index 0000000000..62190c37dc --- /dev/null +++ "b/files/pt-pt/web/css/usando_transforma\303\247\303\265es_css/index.html" @@ -0,0 +1,34 @@ +--- +title: CSS/Usando_transformações_CSS +slug: Web/CSS/Usando_transformações_CSS +translation_of: Web/CSS/CSS_Transforms/Using_CSS_transforms +--- +

{{ 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/width/index.html b/files/pt-pt/web/css/width/index.html new file mode 100644 index 0000000000..f865e76bed --- /dev/null +++ b/files/pt-pt/web/css/width/index.html @@ -0,0 +1,86 @@ +--- +title: width +slug: Web/CSS/width +tags: + - Referencia_CSS +translation_of: Web/CSS/width +--- +

{{ CSSRef() }}

+ +

Resumo

+ +

A propriedade width é usada para configurar a largura dada a um elemento.

+ + + +

Sintaxe

+ +
 width: [ <length> || <percentage> ] auto | inherit
+
+ +

Valores

+ + + +

Exemplos

+ +

View Live Examples

+ +
table{width: 100%;}
+
+img{width: 200px;}
+
+form{width: auto;}
+
+ +

== Notas ==

+ +

Especificações

+ + + +

Compatibilidade com navegadores

+ + + + + + + + + + + + + + + + + + + + +
NavegadorVersão mais antiga
Internet Explorer4
Netscape4
Opera3.5
+ +

Veja também

+ +

box model, {{ Cssxref("height") }}, {{ Cssxref("-moz-box-sizing") }}

+ +

Categorias

+ +

Interwiki Language Links

+ +

{{ languages( { "en": "en/CSS/width", "fr": "fr/CSS/width" } ) }}

diff --git a/files/pt-pt/web/css/z-index/index.html b/files/pt-pt/web/css/z-index/index.html new file mode 100644 index 0000000000..0ff1013362 --- /dev/null +++ b/files/pt-pt/web/css/z-index/index.html @@ -0,0 +1,41 @@ +--- +title: z-index +slug: Web/CSS/z-index +tags: + - Referencia_CSS +translation_of: Web/CSS/z-index +--- +

+{{ CSSRef() }} +

+

Resumo

+

A propriedade z-index especifica a ordem-z de um elemento e de seus herdeiros. Quando os elementos sobrepõem, a z-ordem determina qual elemento cobre o outro. +

+ +

Sintaxe

+

z-index: auto | <integer> | inherit +

+

Valores

+
auto 
O elemento é desenhado na mesma ordem-z como um elemento com z-index: 0. Isto não cria uma nova pilha de contexto. +
<integer> 
O elemento é desenhado na ordem-z dada. Isto cria também uma nova pilha de contexto, que significa que todos os descendentes também terão o desenho no mesmo z-index. Dessa forma os z-indexes dos descendentes não são comparados aos z-indexes dos elementos do lado de fora deste elemento. +
+

== Exemplos == +

+

Notas

+

Valores z-index negativos são suportados corretamente iniciando em Gecko 1.9 / Firefox 3. Versões mais antigas implementaram o comportamento do CSS 2, não o comportamento do CSS 2.1 que é compatível com outros navegadores. +

+

Especificações

+ +

== Compatibilidade com navegadores == +

+

Veja também

+

{{ Cssxref("position") }} +

Categorias +

Interwiki Language Links +

{{ languages( { "en": "en/CSS/z-index", "fr": "fr/CSS/z-index", "pl": "pl/CSS/z-index" } ) }} diff --git a/files/pt-pt/web/eventos/index.html b/files/pt-pt/web/eventos/index.html new file mode 100644 index 0000000000..e215eccadc --- /dev/null +++ b/files/pt-pt/web/eventos/index.html @@ -0,0 +1,3080 @@ +--- +title: Referência de Eventos +slug: Web/Eventos +tags: + - eventos +translation_of: Web/Events +--- +

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/como_come\303\247ar/index.html" "b/files/pt-pt/web/guide/ajax/como_come\303\247ar/index.html" new file mode 100644 index 0000000000..f067252d2d --- /dev/null +++ "b/files/pt-pt/web/guide/ajax/como_come\303\247ar/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/ajax/comunidade/index.html b/files/pt-pt/web/guide/ajax/comunidade/index.html new file mode 100644 index 0000000000..98a2936999 --- /dev/null +++ b/files/pt-pt/web/guide/ajax/comunidade/index.html @@ -0,0 +1,22 @@ +--- +title: Comunidade +slug: Web/Guide/AJAX/Comunidade +tags: + - AJAX +translation_of: Web/Guide/AJAX/Community +--- +

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/index.html b/files/pt-pt/web/guide/ajax/index.html new file mode 100644 index 0000000000..d994ea7b96 --- /dev/null +++ b/files/pt-pt/web/guide/ajax/index.html @@ -0,0 +1,131 @@ +--- +title: AJAX +slug: Web/Guide/AJAX +tags: + - AJAX + - DOM + - JSON + - JavaScript + - Referências + - XML + - XMLHttRequest +translation_of: Web/Guide/AJAX +--- +

 

+ +
Primeiros Passos + +

Uma introdução ao AJAX

+
+ +
+

JavaScript Assíncrono e XML, enquanto não uma tecnologia em si, é um termo criado em 2005 por Jesse James Garret, que descreve uma "nova" abordagem para utilizar uma série de tecnologias existentes em conjunto, incluindo HTML ou XHTML, Cascading Style Sheets, JavaScript, Document Object Model, XML, XSLT e o objeto XMLHttpRequest.
+ Quando estas tecnologias são combinadas no modelo AJAX, as aplicações da Web são capazes de efetuar atualizações incrementais e rápidas na interface do utilizador sem recarregar toda a página. Isto torna a aplicação mais rápida e mais responsiva para as ações do do utilizador.

+
+ +

Although X in Ajax stands for XML, JSON is used more than XML nowadays because of its many advantages such as being lighter and a part of JavaScript. Both JSON and XML are used for packaging information in Ajax model.

+ +
+
+

Documentação

+ +
+
Primeiros Passos
+
This article guides you through the Ajax basics and gives you two simple hands-on examples to get you started.
+
Utilizar a API XMLHttpRequest
+
The XMLHttpRequest API is the core of Ajax. This article will explain how to use some Ajax techniques, like: + +
+
API Fetch
+
The Fetch API provides an interface for fetching resources. It will seem familiar to anyone who has used {{domxref("XMLHTTPRequest")}}, but this API provides a more powerful and flexible feature set.
+
Eventos de envio do servidor
+
Traditionally, a web page has to send a request to the server to receive new data; that is, the page requests data from the server. With server-sent events, it's possible for a server to send new data to a web page at any time, by pushing messages to the web page. These incoming messages can be treated as Events + data inside the web page. See also: Using server-sent events.
+
Pure-Ajax navigation example
+
This article provides a working (minimalist) example of a pure-Ajax website composed only of three pages.
+
Enviar e Receber Dados Binário
+
The responseType property of the XMLHttpRequest object can be set to change the expected response type from the server. Possible values are the empty string (default), "arraybuffer", "blob", "document", "json", and "text". The response property will contain the entity body according to responseType, as an ArrayBuffer, Blob, Document, JSON, or string. This article will show some Ajax I/O techniques.
+
XML
+
The Extensible Markup Language (XML) is a W3C-recommended general-purpose markup language for creating special-purpose markup languages. It is a simplified subset of SGML, capable of describing many different kinds of data. Its primary purpose is to facilitate the sharing of data across different systems, particularly systems connected via the Internet.
+
JXON
+
JXON stands for lossless Javascript XML Object Notation, it is a generic name by which is defined the representation of Javascript object trees (JSON) using XML.
+
Analisar e serializar XML
+
How to parse an XML document from a string, a file or via javascript and how to serialize XML documents to strings, Javascript Object trees (JXON) or files.
+
XPath
+
XPath stands for XML Path Language, it uses a non-XML syntax that provides a flexible way of addressing (pointing to) different parts of an XML document. As well as this, it can also be used to test addressed nodes within a document to determine whether they match a pattern or not.
+
A API FileReader
+
The FileReader API lets web applications asynchronously read the contents of files (or raw data buffers) stored on the user's computer, using File or Blob objects to specify the file or data to read. File objects may be obtained from a FileList object returned as a result of a user selecting files using the <input> element, from a drag and drop operation's DataTransfer object, or from the mozGetAsFile() API on an HTMLCanvasElement.
+
HTML no XMLHttpRequest
+
The W3C XMLHttpRequest specification adds HTML parsing support to XMLHttpRequest, which originally supported only XML parsing. This feature allows Web apps to obtain an HTML resource as a parsed DOM using XMLHttpRequest.
+
Outros recursos
+
Outros recursos Ajax que poderão ser úteis.
+
+ +

Ver Todos...

+ +

Consulte também

+ +
+
Alternate Ajax Techniques
+
Most articles on Ajax have focused on using XMLHttp as the means to achieving such communication, but Ajax techniques are not limited to just XMLHttp. There are several other methods.
+
Ajax: A New Approach to Web Applications
+
Jesse James Garrett, of adaptive path, wrote this article in February 2005, introducing Ajax and its related concepts.
+
A Simpler Ajax Path
+
"As it turns out, it's pretty easy to take advantage of the XMLHttpRequest object to make a web app act more like a desktop app while still using traditional tools like web forms for collecting user input."
+
Ajax Mistakes
+
Alex Bosworth has written this article outlining some of the mistakes Ajax application developers can make.
+
Tutorial with examples.
+
 
+
XMLHttpRequest specification
+
W3C Working draft
+
+
+ + +
+ +

{{ListSubpages}}

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

{{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/gr\303\241ficos/index.html" "b/files/pt-pt/web/guide/gr\303\241ficos/index.html" new file mode 100644 index 0000000000..c18d703bc5 --- /dev/null +++ "b/files/pt-pt/web/guide/gr\303\241ficos/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/html/categorias_de_conteudo/index.html b/files/pt-pt/web/guide/html/categorias_de_conteudo/index.html new file mode 100644 index 0000000000..9a7c08ee9a --- /dev/null +++ b/files/pt-pt/web/guide/html/categorias_de_conteudo/index.html @@ -0,0 +1,175 @@ +--- +title: Categorias de conteúdo +slug: Web/Guide/HTML/Categorias_de_conteudo +tags: + - Avançado + - Guía + - HTML + - HTML5 + - Web +translation_of: Web/Guide/HTML/Content_categories +--- +

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

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/index.html b/files/pt-pt/web/guide/index.html new file mode 100644 index 0000000000..8ba5341845 --- /dev/null +++ b/files/pt-pt/web/guide/index.html @@ -0,0 +1,63 @@ +--- +title: Guias do Programador +slug: Web/Guide +tags: + - API + - Guía + - Landing + - Web +translation_of: Web/Guide +--- +

Estes artigos proporcionam informação de como começar, para o ajudar a utilizar as tecnologias da Web específicas e APIs.

+ +
+
+
+
Aprender HTML; Guias e Tutoriais
+
Linguagem de Marcacao em Hiper Texto  (HTML) e a linguaguem padrao de quase todos os navegadores. Maior parte do que voce ve na janela do seu navegador e descrito, fundamentalmente, usando HTML.
+
Aprender a estilizar HTML, utilizando CSS
+
Folhas de Estilo em Cascata (CSS) e uma linguaguem baseada em folhas de estilos usada para definir a apresentacao do documento escrito com HTML.
+
Apresentacao de videos e audios
+
Nos conseguimos apresentar videos e audios na web de diversas maneiras, desde ficheiros 'estaticos' a fluxos de adaptacoes em directo. Este artigo e precebido como o ponto inicial para a exploracao de varios mecanismos de apresentacao baseados na comunicao i compatiilidade com os navegadores populares.
+
Manipulacao de videos e audios
+
A beleza da web e que voce pode combinar tecnologias para criar novos formularios. Tendo audios e videos nativos no navegador significa que nos podemos usar este fluxo de dados com tecnologias como {{htmelement('canvas')}}, WebGL ou API de Áudio da Web para modificar o audio e o video directamente, por exemplo adicionando efeitos como ressonancia/compressao ao audio, ou filtros como escala de cinza/sepia aos videos. Este artigo providencia as referencias para explicar o que voce precisa.
+
Guia do programador de eventos
+
Eventos referem se a duas coisas: o design padrao usado para manter a sincronizacao de varios incidentes que ocorrem durante a execucao da pagina web; i a nomenclatura, caracterizacao, i uso de varios i diversos tipos de ocorrencias.
+
AJAX
+
AJAX is a term that defines a group of technologies allowing web applications to make quick, incremental updates to the user interface without reloading the entire browser page. This makes the application faster and more responsive to user actions.
+
Gráficos na Web
+
Modern web sites and applications often need to present graphics of varying sophistication.
+
Guide to web APIs
+
A list of all web APIs and what they do.
+
JavaScript
+
JavaScript is the powerful scripting language used to create applications for the Web.
+
Localizations and character encodings
+
Browsers process text as Unicode internally. However, a way of representing characters in terms of bytes (character encoding) is used for transferring text over the network to the browser. The HTML specification recommends the use of the UTF-8 encoding (which can represent all of Unicode), and regardless of the encoding used requires Web content to declare that encoding.
+
Mobile web development
+
This article provides an overview of some of the main techniques needed to design web sites that work well on mobile devices. If you're looking for information on Mozilla's Firefox OS project, see the Firefox OS page. Or you might be interested in details about Firefox para Android.
+
+
+ +
+
+
Progressive web apps
+
Progressive web apps (PWAs) use modern web APIs along with traditional progressive enhancement strategy to create cross-platform web applications. These apps work everywhere and provide several features that give them the same user experience advantages as native apps. This set of guides tells you all you need to know about PWAs.
+
Optimization and performance
+
When building modern web apps and sites, it's important to make your content work quickly and efficiently. This lets it perform effectively for both powerful desktop systems and weaker handheld devices.
+
Parsing and serializing XML
+
The web platform provides different methods of parsing and serializing XML, each with its own pros and cons.
+
The Web Open Font Format (WOFF)
+
WOFF (Web Open Font Format) is a font file format that is free for anyone to use on the web.
+
Using FormData objects
+
The FormData object lets you compile a set of key/value pairs to send using XMLHttpRequest. It's primarily intended for sending form data, but can be used independently from forms in order to transmit keyed data. The transmission is in the same format that the form's submit() method would use to send the data if the form's encoding type were set to "multipart/form-data".
+
Glossary
+
Defines numerous technical terms related to the Web and Internet.
+
+
+
+ +

Consultar também

+ + diff --git a/files/pt-pt/web/html/aplicar_cor_elementos_html_utilizando_css/index.html b/files/pt-pt/web/html/aplicar_cor_elementos_html_utilizando_css/index.html new file mode 100644 index 0000000000..2aaefab31d --- /dev/null +++ b/files/pt-pt/web/html/aplicar_cor_elementos_html_utilizando_css/index.html @@ -0,0 +1,581 @@ +--- +title: Aplicar cor aos elementos de HTML utilizando CSS +slug: Web/HTML/Aplicar_cor_elementos_HTML_utilizando_CSS +tags: + - CSS + - Cores de CSS + - Cores de HTML + - Estilo de HTML + - Estilos de HTML + - Guía + - HTML + - Principiante + - cor +translation_of: Web/HTML/Applying_color +--- +
{{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 new file mode 100644 index 0000000000..84ea814756 --- /dev/null +++ b/files/pt-pt/web/html/atributos/index.html @@ -0,0 +1,659 @@ +--- +title: Lista de atributos HTML +slug: Web/HTML/Atributos +tags: + - HTML + - Referencia + - Web + - atributo +translation_of: Web/HTML/Attributes +--- +

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 new file mode 100644 index 0000000000..fe8307f0c0 --- /dev/null +++ b/files/pt-pt/web/html/atributos/rel/index.html @@ -0,0 +1,418 @@ +--- +title: 'HTML attribute: rel' +slug: Web/HTML/Atributos/rel +translation_of: Web/HTML/Attributes/rel +--- +

{{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 new file mode 100644 index 0000000000..2b4a86e833 --- /dev/null +++ b/files/pt-pt/web/html/atributos_globais/index.html @@ -0,0 +1,480 @@ +--- +title: Atributos globais +slug: Web/HTML/Atributos_globais +tags: + - HTML + - Precisa Compatibilidade Navegador + - Referencia + - Web + - atributo +translation_of: Web/HTML/Global_attributes +--- +
{{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/cors_settings_attributes/index.html b/files/pt-pt/web/html/cors_settings_attributes/index.html new file mode 100644 index 0000000000..42f32f77e8 --- /dev/null +++ b/files/pt-pt/web/html/cors_settings_attributes/index.html @@ -0,0 +1,87 @@ +--- +title: 'Atributo CORS: Solicitar acesso CORS para o conteúdo' +slug: Web/HTML/CORS_settings_attributes +tags: + - Avançado + - CORS + - HTML + - Precisa de Exemplo + - Referencia + - Segurança +translation_of: Web/HTML/Attributes/crossorigin +--- +

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/elemento/audio/index.html b/files/pt-pt/web/html/elemento/audio/index.html new file mode 100644 index 0000000000..f8b7c3229b --- /dev/null +++ b/files/pt-pt/web/html/elemento/audio/index.html @@ -0,0 +1,47 @@ +--- +title: Audio +slug: Web/HTML/Elemento/Audio +translation_of: Web/HTML/Element/audio +--- +

{{ 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/elemento/fieldset/index.html b/files/pt-pt/web/html/elemento/fieldset/index.html new file mode 100644 index 0000000000..44fd353489 --- /dev/null +++ b/files/pt-pt/web/html/elemento/fieldset/index.html @@ -0,0 +1,177 @@ +--- +title: '
: 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/elemento/figcaption/index.html b/files/pt-pt/web/html/elemento/figcaption/index.html new file mode 100644 index 0000000000..e40a044136 --- /dev/null +++ b/files/pt-pt/web/html/elemento/figcaption/index.html @@ -0,0 +1,101 @@ +--- +title: figcaption +slug: Web/HTML/Elemento/figcaption +translation_of: Web/HTML/Element/figcaption +--- +

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/elemento/head/index.html b/files/pt-pt/web/html/elemento/head/index.html new file mode 100644 index 0000000000..8285b2f2af --- /dev/null +++ b/files/pt-pt/web/html/elemento/head/index.html @@ -0,0 +1,108 @@ +--- +title: ' : 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/elemento/index.html b/files/pt-pt/web/html/elemento/index.html new file mode 100644 index 0000000000..c47907bce9 --- /dev/null +++ b/files/pt-pt/web/html/elemento/index.html @@ -0,0 +1,107 @@ +--- +title: Referência dos elementos HTML +slug: Web/HTML/Elemento +tags: + - Elemento + - HTML + - 'I10n:priority' + - Referencia + - Web + - básico +translation_of: Web/HTML/Element +--- +
{{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/elemento/nav/index.html b/files/pt-pt/web/html/elemento/nav/index.html new file mode 100644 index 0000000000..3dfc714e23 --- /dev/null +++ b/files/pt-pt/web/html/elemento/nav/index.html @@ -0,0 +1,99 @@ +--- +title: