From 074785cea106179cb3305637055ab0a009ca74f2 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:42:52 -0500 Subject: initial commit --- .../web/accessibility/aria/aria_guides/index.html | 27 + .../accessibility/aria/aria_techniques/index.html | 194 + .../usando_o_atributo_aria-labelledby/index.html | 158 + .../usando_o_atributo_aria-required/index.html | 83 + .../usando_o_slider_role/index.html | 125 + .../index.html | 87 + .../using_the_aria-label_attribute/index.html | 64 + .../utilizando_o_alert_role/index.html | 145 + .../accessibility/aria/aria_test_cases/index.html | 4701 ++++++++++++++++++++ .../web/accessibility/aria/forms/alerts/index.html | 141 + .../forms/dicas_b\303\241sicas_de_form/index.html" | 118 + .../pt-br/web/accessibility/aria/forms/index.html | 21 + .../aria/forms/multipart_labels/index.html | 47 + .../index.html | 35 + files/pt-br/web/accessibility/aria/index.html | 148 + .../pt-br/web/accessibility/aria/roles/index.html | 78 + .../aria/web_applications_and_aria_faq/index.html | 320 ++ .../web/accessibility/aria/widgets/index.html | 10 + .../aria/widgets/vis\303\243o_geral/index.html" | 72 + .../web/accessibility/at-apis/gecko/index.html | 10 + .../accessibility/at-apis/gecko/roles/index.html | 255 ++ files/pt-br/web/accessibility/at-apis/index.html | 176 + files/pt-br/web/accessibility/xforms/index.html | 198 + .../web/accessibility/xforms/upload/index.html | 45 + .../index.html | 100 + .../index.html | 234 + .../acessibilidade/desenvolvimento_web/index.html | 54 + .../web/acessibilidade/entendendo_wcag/index.html | 57 + .../entendendo_wcag/keyboard/index.html | 87 + files/pt-br/web/acessibilidade/index.html | 52 + .../problemas_com_jaws_no_firefox/index.html | 11 + files/pt-br/web/api/abortsignal/aborted/index.html | 62 + files/pt-br/web/api/abortsignal/index.html | 101 + files/pt-br/web/api/abstractworker/index.html | 103 + .../web/api/abstractworker/onerror/index.html | 104 + .../pt-br/web/api/ambient_light_events/index.html | 116 + .../web/api/angle_instanced_arrays/index.html | 88 + files/pt-br/web/api/animation/cancel/index.html | 120 + .../pt-br/web/api/animation/currenttime/index.html | 112 + files/pt-br/web/api/animation/index.html | 171 + files/pt-br/web/api/animation/playstate/index.html | 152 + .../api/animationevent/animationevent/index.html | 134 + .../api/animationevent/animationname/index.html | 102 + .../web/api/animationevent/elapsedtime/index.html | 103 + files/pt-br/web/api/animationevent/index.html | 194 + .../animationevent/initanimationevent/index.html | 134 + .../api/animationevent/pseudoelement/index.html | 102 + files/pt-br/web/api/api_de_desempenho/index.html | 138 + .../web/api/api_push/best_practices/index.html | 73 + files/pt-br/web/api/api_push/index.html | 172 + files/pt-br/web/api/api_web_audio/index.html | 480 ++ .../api_web_audio/sintetizador_simples/index.html | 579 +++ files/pt-br/web/api/attr/index.html | 132 + files/pt-br/web/api/attr/localname/index.html | 133 + .../web/api/audiocontext/currenttime/index.html | 114 + files/pt-br/web/api/audiocontext/index.html | 258 ++ files/pt-br/web/api/audionode/index.html | 191 + .../pt-br/web/api/background_tasks_api/index.html | 509 +++ .../web/api/batterymanager/charging/index.html | 33 + .../web/api/batterymanager/chargingtime/index.html | 34 + .../api/batterymanager/dischargingtime/index.html | 34 + files/pt-br/web/api/batterymanager/index.html | 140 + .../pt-br/web/api/batterymanager/level/index.html | 34 + .../api/batterymanager/onchargingchange/index.html | 35 + .../batterymanager/onchargingtimechange/index.html | 35 + .../ondischargintimechange/index.html | 35 + .../api/batterymanager/onlevelchange/index.html | 35 + files/pt-br/web/api/biquadfilternode/index.html | 186 + files/pt-br/web/api/blob/blob/index.html | 65 + files/pt-br/web/api/blob/index.html | 130 + files/pt-br/web/api/blob/size/index.html | 60 + files/pt-br/web/api/blob/slice/index.html | 115 + files/pt-br/web/api/blob/type/index.html | 68 + files/pt-br/web/api/body/index.html | 97 + files/pt-br/web/api/body/json/index.html | 89 + files/pt-br/web/api/broadcastchannel/index.html | 81 + files/pt-br/web/api/cache/index.html | 282 ++ .../web/api/cameracontrol/autofocus/index.html | 61 + files/pt-br/web/api/cameracontrol/index.html | 108 + .../api/canvasrenderingcontext2d/arc/index.html | 138 + .../api/canvasrenderingcontext2d/arcto/index.html | 147 + .../canvasrenderingcontext2d/beginpath/index.html | 184 + .../canvasrenderingcontext2d/clearrect/index.html | 195 + .../api/canvasrenderingcontext2d/clip/index.html | 195 + .../canvasrenderingcontext2d/closepath/index.html | 170 + .../api/canvasrenderingcontext2d/fill/index.html | 196 + .../canvasrenderingcontext2d/fillrect/index.html | 179 + .../canvasrenderingcontext2d/fillstyle/index.html | 213 + .../web/api/canvasrenderingcontext2d/index.html | 450 ++ .../api/canvasrenderingcontext2d/lineto/index.html | 176 + .../api/canvasrenderingcontext2d/moveto/index.html | 176 + .../quadraticcurveto/index.html | 182 + .../api/canvasrenderingcontext2d/rect/index.html | 177 + .../api/canvasrenderingcontext2d/stroke/index.html | 187 + .../canvasrenderingcontext2d/strokerect/index.html | 177 + files/pt-br/web/api/characterdata/index.html | 94 + files/pt-br/web/api/childnode/after/index.html | 187 + files/pt-br/web/api/childnode/index.html | 78 + files/pt-br/web/api/childnode/remove/index.html | 100 + files/pt-br/web/api/clipboardevent/index.html | 59 + .../pt-br/web/api/closeevent/closeevent/index.html | 71 + files/pt-br/web/api/closeevent/index.html | 239 + files/pt-br/web/api/console/assert/index.html | 148 + files/pt-br/web/api/console/clear/index.html | 38 + files/pt-br/web/api/console/count/index.html | 168 + files/pt-br/web/api/console/dir/index.html | 108 + files/pt-br/web/api/console/error/index.html | 160 + files/pt-br/web/api/console/index.html | 242 + files/pt-br/web/api/console/info/index.html | 154 + files/pt-br/web/api/console/log/index.html | 119 + files/pt-br/web/api/console/table/index.html | 143 + files/pt-br/web/api/console/time/index.html | 103 + files/pt-br/web/api/console/timeend/index.html | 90 + files/pt-br/web/api/console/timestamp/index.html | 106 + files/pt-br/web/api/console/warn/index.html | 139 + files/pt-br/web/api/console_api/index.html | 68 + files/pt-br/web/api/crypto/index.html | 72 + files/pt-br/web/api/crypto/subtle/index.html | 51 + files/pt-br/web/api/cryptokey/algorithm/index.html | 112 + .../pt-br/web/api/cryptokey/extractable/index.html | 110 + files/pt-br/web/api/cryptokey/index.html | 120 + files/pt-br/web/api/cryptokey/type/index.html | 117 + files/pt-br/web/api/cryptokey/usages/index.html | 123 + files/pt-br/web/api/css/index.html | 136 + files/pt-br/web/api/css_object_model/index.html | 133 + .../pt-br/web/api/customelementregistry/index.html | 93 + files/pt-br/web/api/datatransfer/index.html | 383 ++ files/pt-br/web/api/deviceacceleration/index.html | 42 + files/pt-br/web/api/devicerotationrate/index.html | 92 + files/pt-br/web/api/devicestorage.get/index.html | 58 + .../web/api/devicestorage.onchange/index.html | 30 + .../web/api/document/activeelement/index.html | 164 + files/pt-br/web/api/document/alinkcolor/index.html | 36 + files/pt-br/web/api/document/anchors/index.html | 107 + files/pt-br/web/api/document/bgcolor/index.html | 35 + files/pt-br/web/api/document/body/index.html | 44 + .../pt-br/web/api/document/characterset/index.html | 65 + files/pt-br/web/api/document/close/index.html | 27 + files/pt-br/web/api/document/compatmode/index.html | 42 + .../pt-br/web/api/document/contenttype/index.html | 46 + .../web/api/document/createelement/index.html | 82 + .../web/api/document/createelementns/index.html | 90 + .../web/api/document/currentscript/index.html | 99 + .../pt-br/web/api/document/defaultview/index.html | 28 + files/pt-br/web/api/document/designmode/index.html | 104 + files/pt-br/web/api/document/doctype/index.html | 59 + files/pt-br/web/api/document/document/index.html | 87 + .../web/api/document/documentelement/index.html | 43 + .../pt-br/web/api/document/documenturi/index.html | 53 + .../web/api/document/elementfrompoint/index.html | 132 + .../web/api/document/elementoregistrado/index.html | 132 + .../pt-br/web/api/document/execcommand/index.html | 174 + files/pt-br/web/api/document/fullscreen/index.html | 83 + .../web/api/document/getelementbyid/index.html | 133 + .../api/document/getelementsbyclassname/index.html | 104 + .../web/api/document/getelementsbyname/index.html | 90 + .../api/document/getelementsbytagname/index.html | 113 + .../pt-br/web/api/document/getselection/index.html | 8 + files/pt-br/web/api/document/hasfocus/index.html | 146 + files/pt-br/web/api/document/head/index.html | 102 + files/pt-br/web/api/document/height/index.html | 44 + files/pt-br/web/api/document/images/index.html | 38 + .../web/api/document/implementation/index.html | 52 + files/pt-br/web/api/document/importnode/index.html | 84 + files/pt-br/web/api/document/index.html | 402 ++ .../web/api/document/keydown_event/index.html | 178 + .../web/api/document/keypress_event/index.html | 170 + .../pt-br/web/api/document/keyup_event/index.html | 151 + files/pt-br/web/api/document/location/index.html | 108 + files/pt-br/web/api/document/origin/index.html | 60 + .../web/api/document/queryselector/index.html | 107 + .../web/api/document/queryselectorall/index.html | 110 + files/pt-br/web/api/document/readystate/index.html | 102 + files/pt-br/web/api/document/referrer/index.html | 33 + files/pt-br/web/api/document/scripts/index.html | 84 + files/pt-br/web/api/document/url/index.html | 19 + files/pt-br/web/api/document/write/index.html | 108 + files/pt-br/web/api/document/writeln/index.html | 43 + files/pt-br/web/api/documentfragment/index.html | 234 + files/pt-br/web/api/domexception/index.html | 150 + .../domimplementation/createdocument/index.html | 83 + files/pt-br/web/api/domimplementation/index.html | 81 + files/pt-br/web/api/domstring/index.html | 52 + files/pt-br/web/api/domstringlist/index.html | 43 + files/pt-br/web/api/domstringmap/index.html | 141 + files/pt-br/web/api/element/accesskey/index.html | 18 + .../web/api/element/addeventlistener/index.html | 322 ++ files/pt-br/web/api/element/animate/index.html | 202 + files/pt-br/web/api/element/attributes/index.html | 166 + files/pt-br/web/api/element/classlist/index.html | 171 + files/pt-br/web/api/element/classname/index.html | 123 + files/pt-br/web/api/element/click_event/index.html | 276 ++ files/pt-br/web/api/element/closest/index.html | 127 + .../pt-br/web/api/element/getattribute/index.html | 76 + .../api/element/getboundingclientrect/index.html | 84 + .../api/element/getelementsbyclassname/index.html | 108 + files/pt-br/web/api/element/id/index.html | 119 + files/pt-br/web/api/element/index.html | 529 +++ files/pt-br/web/api/element/innerhtml/index.html | 148 + .../web/api/element/insertadjacenthtml/index.html | 138 + files/pt-br/web/api/element/matches/index.html | 165 + .../web/api/element/mousedown_event/index.html | 235 + .../web/api/element/mouseenter_event/index.html | 314 ++ .../web/api/element/mouseover_event/index.html | 262 ++ files/pt-br/web/api/element/name/index.html | 79 + files/pt-br/web/api/element/outerhtml/index.html | 144 + .../pt-br/web/api/element/queryselector/index.html | 94 + .../web/api/element/queryselectorall/index.html | 118 + .../web/api/element/removeattribute/index.html | 36 + .../web/api/element/scrollintoview/index.html | 89 + files/pt-br/web/api/element/scrollleft/index.html | 83 + files/pt-br/web/api/element/scrolltop/index.html | 69 + files/pt-br/web/api/element/scrollwidth/index.html | 116 + .../pt-br/web/api/element/setattribute/index.html | 58 + .../web/api/element/setattributens/index.html | 33 + files/pt-br/web/api/element/tagname/index.html | 119 + .../web/api/element/touchstart_event/index.html | 174 + files/pt-br/web/api/encoding_api/index.html | 55 + .../comparativo_entre_event_targets/index.html | 167 + files/pt-br/web/api/event/currenttarget/index.html | 129 + .../web/api/event/defaultprevented/index.html | 79 + files/pt-br/web/api/event/event/index.html | 69 + files/pt-br/web/api/event/index.html | 146 + files/pt-br/web/api/event/initevent/index.html | 137 + files/pt-br/web/api/event/istrusted/index.html | 57 + .../pt-br/web/api/event/preventdefault/index.html | 113 + files/pt-br/web/api/event/srcelement/index.html | 74 + .../api/event/stopimmediatepropagation/index.html | 99 + .../pt-br/web/api/event/stoppropagation/index.html | 93 + files/pt-br/web/api/event/target/index.html | 69 + files/pt-br/web/api/event/type/index.html | 60 + files/pt-br/web/api/eventlistener/index.html | 48 + .../web/api/eventsource/eventsource/index.html | 157 + files/pt-br/web/api/eventsource/index.html | 175 + files/pt-br/web/api/eventsource/onerror/index.html | 121 + .../web/api/eventtarget/dispatchevent/index.html | 43 + .../web/api/eventtarget/eventtarget/index.html | 70 + files/pt-br/web/api/eventtarget/index.html | 124 + .../api/eventtarget/removeeventlistener/index.html | 138 + .../web/api/fetch_api/basic_concepts/index.html | 66 + files/pt-br/web/api/fetch_api/index.html | 85 + .../pt-br/web/api/fetch_api/using_fetch/index.html | 311 ++ .../fetch_api/uso_de_busca_cross-global/index.html | 35 + files/pt-br/web/api/file/index.html | 146 + .../using_files_from_web_applications/index.html | 351 ++ files/pt-br/web/api/filelist/index.html | 134 + .../pt-br/web/api/filereader/filereader/index.html | 54 + files/pt-br/web/api/filereader/index.html | 162 + files/pt-br/web/api/filereader/onload/index.html | 29 + .../api/filereader/readasarraybuffer/index.html | 107 + .../api/filereader/readasbinarystring/index.html | 120 + .../web/api/filereader/readasdataurl/index.html | 111 + .../pt-br/web/api/filereader/readastext/index.html | 104 + files/pt-br/web/api/formdata/append/index.html | 177 + files/pt-br/web/api/formdata/delete/index.html | 138 + files/pt-br/web/api/formdata/entries/index.html | 77 + files/pt-br/web/api/formdata/formdata/index.html | 184 + files/pt-br/web/api/formdata/get/index.html | 142 + files/pt-br/web/api/formdata/getall/index.html | 74 + files/pt-br/web/api/formdata/has/index.html | 81 + files/pt-br/web/api/formdata/index.html | 170 + files/pt-br/web/api/formdata/set/index.html | 150 + files/pt-br/web/api/fullscreenoptions/index.html | 29 + files/pt-br/web/api/gamepad_api/index.html | 90 + .../web/api/geolocation/clearwatch/index.html | 84 + .../api/geolocation/getcurrentposition/index.html | 127 + files/pt-br/web/api/geolocation/index.html | 75 + .../web/api/geolocation/watchposition/index.html | 140 + .../api/geolocationcoordinates/altitude/index.html | 45 + .../web/api/geolocationcoordinates/index.html | 141 + .../web/api/geolocationposition/coords/index.html | 116 + files/pt-br/web/api/geolocationposition/index.html | 61 + .../web/api/geolocationpositionerror/index.html | 128 + files/pt-br/web/api/globaleventhandlers/index.html | 536 +++ .../web/api/globaleventhandlers/onabort/index.html | 44 + .../web/api/globaleventhandlers/onblur/index.html | 94 + .../api/globaleventhandlers/onchange/index.html | 46 + .../web/api/globaleventhandlers/onclick/index.html | 83 + .../globaleventhandlers/oncontextmenu/index.html | 48 + .../web/api/globaleventhandlers/onerror/index.html | 97 + .../web/api/globaleventhandlers/onfocus/index.html | 36 + .../web/api/globaleventhandlers/onkeyup/index.html | 61 + .../web/api/globaleventhandlers/onload/index.html | 74 + .../onlostpointercapture/index.html | 70 + .../api/globaleventhandlers/onscroll/index.html | 94 + files/pt-br/web/api/history/index.html | 89 + files/pt-br/web/api/history_api/exemplo/index.html | 418 ++ files/pt-br/web/api/history_api/index.html | 257 ++ .../api/htmlcanvaselement/getcontext/index.html | 292 ++ .../web/api/htmlcanvaselement/height/index.html | 79 + files/pt-br/web/api/htmlcanvaselement/index.html | 264 ++ .../web/api/htmlcanvaselement/todataurl/index.html | 157 + files/pt-br/web/api/htmlcollection/index.html | 68 + .../getdistributednodes/index.html | 100 + files/pt-br/web/api/htmlcontentelement/index.html | 116 + .../web/api/htmlcontentelement/seletor/index.html | 98 + files/pt-br/web/api/htmldivelement/index.html | 133 + files/pt-br/web/api/htmlelement/blur/index.html | 89 + files/pt-br/web/api/htmlelement/click/index.html | 115 + .../web/api/htmlelement/contenteditable/index.html | 102 + .../web/api/htmlelement/contextmenu/index.html | 44 + files/pt-br/web/api/htmlelement/dataset/index.html | 97 + files/pt-br/web/api/htmlelement/focus/index.html | 62 + files/pt-br/web/api/htmlelement/index.html | 410 ++ files/pt-br/web/api/htmlelement/lang/index.html | 51 + .../web/api/htmlelement/offsetheight/index.html | 126 + .../web/api/htmlelement/offsetleft/index.html | 142 + .../web/api/htmlelement/offsetparent/index.html | 40 + .../pt-br/web/api/htmlelement/offsettop/index.html | 62 + .../web/api/htmlelement/offsetwidth/index.html | 65 + files/pt-br/web/api/htmlinputelement/index.html | 643 +++ .../web/api/htmlinputelement/select/index.html | 52 + .../htmlinputelement/setselectionrange/index.html | 173 + files/pt-br/web/api/htmloptionelement/index.html | 129 + .../web/api/htmloptionelement/option/index.html | 101 + .../api/htmlselectelement/checkvalidity/index.html | 98 + files/pt-br/web/api/htmlselectelement/index.html | 290 ++ files/pt-br/web/api/htmlshadowelement/index.html | 67 + files/pt-br/web/api/htmlspanelement/index.html | 72 + files/pt-br/web/api/idbcursor/index.html | 181 + files/pt-br/web/api/idbfactory/index.html | 210 + files/pt-br/web/api/imagecapture/index.html | 116 + files/pt-br/web/api/index.html | 32 + .../basic_concepts_behind_indexeddb/index.html | 249 ++ files/pt-br/web/api/indexeddb_api/index.html | 167 + .../api/indexeddb_api/usando_indexeddb/index.html | 1281 ++++++ files/pt-br/web/api/keyboardevent/index.html | 439 ++ files/pt-br/web/api/location/assign/index.html | 120 + files/pt-br/web/api/location/index.html | 184 + files/pt-br/web/api/location/reload/index.html | 114 + files/pt-br/web/api/location/search/index.html | 55 + files/pt-br/web/api/mediadevices/index.html | 251 ++ files/pt-br/web/api/mediastreamtrack/index.html | 181 + files/pt-br/web/api/messagechannel/index.html | 152 + files/pt-br/web/api/messageport/index.html | 117 + .../web/api/messageport/postmessage/index.html | 81 + files/pt-br/web/api/mouseevent/clientx/index.html | 149 + files/pt-br/web/api/mouseevent/clienty/index.html | 91 + files/pt-br/web/api/mouseevent/index.html | 336 ++ files/pt-br/web/api/mutationobserver/index.html | 221 + .../pt-br/web/api/navigation_timing_api/index.html | 153 + files/pt-br/web/api/navigator/battery/index.html | 40 + .../web/api/navigator/cookieenabled/index.html | 49 + .../web/api/navigator/devicememory/index.html | 39 + .../pt-br/web/api/navigator/geolocation/index.html | 46 + .../web/api/navigator/getusermedia/index.html | 184 + files/pt-br/web/api/navigator/index.html | 119 + files/pt-br/web/api/navigator/share/index.html | 87 + files/pt-br/web/api/navigatorid/index.html | 120 + .../pt-br/web/api/navigatorid/platform/index.html | 63 + .../pt-br/web/api/navigatorid/useragent/index.html | 89 + files/pt-br/web/api/navigatorlanguage/index.html | 148 + .../web/api/navigatorlanguage/language/index.html | 131 + files/pt-br/web/api/navigatoronline/index.html | 134 + .../web/api/navigatoronline/online/index.html | 91 + .../online_and_offline_events/index.html | 99 + files/pt-br/web/api/navigatorplugins/index.html | 69 + .../api/navigatorplugins/javaenabled/index.html | 54 + files/pt-br/web/api/node/appendchild/index.html | 56 + files/pt-br/web/api/node/baseuri/index.html | 82 + files/pt-br/web/api/node/childnodes/index.html | 66 + files/pt-br/web/api/node/clonenode/index.html | 175 + files/pt-br/web/api/node/contains/index.html | 98 + .../index.html" | 55 + files/pt-br/web/api/node/firstchild/index.html | 66 + files/pt-br/web/api/node/index.html | 303 ++ files/pt-br/web/api/node/innertext/index.html | 86 + files/pt-br/web/api/node/insertbefore/index.html | 152 + files/pt-br/web/api/node/isconnected/index.html | 118 + files/pt-br/web/api/node/lastchild/index.html | 34 + files/pt-br/web/api/node/nextsibling/index.html | 66 + files/pt-br/web/api/node/parentnode/index.html | 116 + .../pt-br/web/api/node/previoussibling/index.html | 46 + files/pt-br/web/api/node/removechild/index.html | 72 + files/pt-br/web/api/node/replacechild/index.html | 69 + files/pt-br/web/api/node/textcontent/index.html | 138 + files/pt-br/web/api/nodefilter/index.html | 163 + files/pt-br/web/api/nodelist/index.html | 155 + files/pt-br/web/api/notificacoes/index.html | 217 + files/pt-br/web/api/notificationaction/index.html | 79 + files/pt-br/web/api/offlineaudiocontext/index.html | 150 + files/pt-br/web/api/page_visibility_api/index.html | 209 + .../api/parentnode/childelementcount/index.html | 98 + files/pt-br/web/api/parentnode/children/index.html | 131 + files/pt-br/web/api/parentnode/index.html | 163 + .../web/api/parentnode/queryselector/index.html | 101 + files/pt-br/web/api/path2d/index.html | 82 + files/pt-br/web/api/performance/index.html | 138 + files/pt-br/web/api/performance/now/index.html | 160 + files/pt-br/web/api/performance/tojson/index.html | 61 + files/pt-br/web/api/positionoptions/index.html | 109 + .../pt-br/web/api/processinginstruction/index.html | 39 + files/pt-br/web/api/pushmanager/index.html | 187 + .../api/randomsource/getrandomvalues/index.html | 116 + files/pt-br/web/api/randomsource/index.html | 108 + files/pt-br/web/api/request/index.html | 167 + files/pt-br/web/api/request/request/index.html | 155 + files/pt-br/web/api/response/index.html | 130 + files/pt-br/web/api/rtccertificate/index.html | 47 + files/pt-br/web/api/rtcdatachannel/index.html | 130 + files/pt-br/web/api/rtcicetransport/index.html | 91 + .../rtcpeerconnection/connectionstate/index.html | 64 + files/pt-br/web/api/rtcpeerconnection/index.html | 360 ++ .../web/api/sele\303\247\303\243o/index.html" | 206 + files/pt-br/web/api/sensor/index.html | 89 + files/pt-br/web/api/server-sent_events/index.html | 79 + .../using_server-sent_events/index.html | 189 + files/pt-br/web/api/service_worker_api/index.html | 322 ++ .../using_service_workers/index.html | 522 +++ .../web/api/serviceworkercontainer/index.html | 175 + .../api/serviceworkercontainer/register/index.html | 140 + .../serviceworkerglobalscope/clients/index.html | 63 + .../web/api/serviceworkerglobalscope/index.html | 152 + files/pt-br/web/api/sharedworker/index.html | 188 + files/pt-br/web/api/sharedworker/port/index.html | 111 + files/pt-br/web/api/speechgrammar/index.html | 79 + files/pt-br/web/api/speechsynthesis/index.html | 194 + .../web/api/speechsynthesisutterance/index.html | 177 + .../api/speechsynthesisutterance/voice/index.html | 130 + files/pt-br/web/api/storage/clear/index.html | 131 + files/pt-br/web/api/storage/getitem/index.html | 79 + files/pt-br/web/api/storage/index.html | 119 + files/pt-br/web/api/storage/key/index.html | 72 + files/pt-br/web/api/storage/length/index.html | 130 + files/pt-br/web/api/storage/removeitem/index.html | 124 + files/pt-br/web/api/storage/setitem/index.html | 131 + files/pt-br/web/api/storagemanager/index.html | 53 + .../pt-br/web/api/streams_api/concepts/index.html | 121 + files/pt-br/web/api/streams_api/index.html | 157 + .../web/api/subtlecrypto/derivekey/index.html | 270 ++ .../web/api/subtlecrypto/generatekey/index.html | 197 + .../web/api/subtlecrypto/importkey/index.html | 169 + files/pt-br/web/api/subtlecrypto/index.html | 83 + files/pt-br/web/api/svgaelement/index.html | 74 + .../api/svgaelement/svgalement.target/index.html | 105 + .../web/api/svganimatetransformelement/index.html | 48 + files/pt-br/web/api/url/createobjecturl/index.html | 42 + files/pt-br/web/api/url/index.html | 113 + files/pt-br/web/api/url/revokeobjecturl/index.html | 107 + files/pt-br/web/api/url/searchparams/index.html | 45 + files/pt-br/web/api/urlsearchparams/get/index.html | 109 + files/pt-br/web/api/urlsearchparams/index.html | 177 + .../web/api/urlsearchparams/values/index.html | 112 + files/pt-br/web/api/validitystate/index.html | 85 + files/pt-br/web/api/web_animations_api/index.html | 86 + .../usando_a_web_animations_api/index.html | 358 ++ files/pt-br/web/api/web_crypto_api/index.html | 132 + .../pt-br/web/api/web_storage_api_pt_br/index.html | 139 + .../using_the_web_storage_api/index.html | 267 ++ files/pt-br/web/api/web_workers_api/index.html | 213 + files/pt-br/web/api/webgl_api/index.html | 278 ++ .../index.html | 226 + .../tutorial/getting_started_with_webgl/index.html | 71 + files/pt-br/web/api/webgl_api/tutorial/index.html | 39 + files/pt-br/web/api/webrtc_api/index.html | 197 + .../pt-br/web/api/webrtc_api/protocols/index.html | 70 + .../simples_rtcdatachannel_amostra/index.html | 272 ++ files/pt-br/web/api/websocket/index.html | 323 ++ files/pt-br/web/api/webvr_api/index.html | 151 + .../api/webvr_api/using_the_webvr_api/index.html | 440 ++ files/pt-br/web/api/window/alert/index.html | 47 + .../web/api/window/applicationcache/index.html | 33 + files/pt-br/web/api/window/closed/index.html | 59 + files/pt-br/web/api/window/confirm/index.html | 49 + files/pt-br/web/api/window/crypto/index.html | 128 + files/pt-br/web/api/window/document/index.html | 56 + files/pt-br/web/api/window/event/index.html | 72 + files/pt-br/web/api/window/fullscreen/index.html | 44 + files/pt-br/web/api/window/getselection/index.html | 129 + files/pt-br/web/api/window/history/index.html | 52 + files/pt-br/web/api/window/index.html | 381 ++ files/pt-br/web/api/window/innerheight/index.html | 137 + files/pt-br/web/api/window/length/index.html | 52 + files/pt-br/web/api/window/location/index.html | 272 ++ files/pt-br/web/api/window/matchmedia/index.html | 106 + files/pt-br/web/api/window/navigator/index.html | 54 + .../pt-br/web/api/window/ondevicelight/index.html | 99 + files/pt-br/web/api/window/onscroll/index.html | 98 + files/pt-br/web/api/window/opendialog/index.html | 90 + files/pt-br/web/api/window/performance/index.html | 33 + .../pt-br/web/api/window/popstate_event/index.html | 144 + files/pt-br/web/api/window/print/index.html | 56 + files/pt-br/web/api/window/prompt/index.html | 66 + .../api/window/requestanimationframe/index.html | 106 + .../web/api/window/requestidlecallback/index.html | 70 + files/pt-br/web/api/window/resize_event/index.html | 190 + files/pt-br/web/api/window/scroll/index.html | 57 + files/pt-br/web/api/window/scrollby/index.html | 53 + .../pt-br/web/api/window/scrollbypages/index.html | 41 + files/pt-br/web/api/window/scrollto/index.html | 56 + files/pt-br/web/api/window/scrolly/index.html | 76 + .../pt-br/web/api/window/sessionstorage/index.html | 143 + files/pt-br/web/api/window/setcursor/index.html | 28 + files/pt-br/web/api/window/setimmediate/index.html | 107 + files/pt-br/web/api/window/url/index.html | 100 + .../web/api/window/window.localstorage/index.html | 123 + files/pt-br/web/api/windowbase64/atob/index.html | 72 + files/pt-br/web/api/windowbase64/index.html | 120 + files/pt-br/web/api/windoweventhandlers/index.html | 189 + .../windoweventhandlers/onhashchange/index.html | 158 + .../api/windoweventhandlers/onpopstate/index.html | 61 + .../api/windoweventhandlers/onstorage/index.html | 101 + .../api/windoworworkerglobalscope/fetch/index.html | 305 ++ .../web/api/windoworworkerglobalscope/index.html | 189 + .../setinterval/index.html | 629 +++ .../web/api/windowtimers/cleartimeout/index.html | 100 + files/pt-br/web/api/windowtimers/index.html | 116 + files/pt-br/web/api/worker/index.html | 166 + files/pt-br/web/api/xmldocument/async/index.html | 37 + files/pt-br/web/api/xmldocument/index.html | 61 + .../pt-br/web/api/xmlhttprequest/abort/index.html | 118 + files/pt-br/web/api/xmlhttprequest/index.html | 724 +++ .../xmlhttprequest/onreadystatechange/index.html | 120 + files/pt-br/web/api/xmlhttprequest/open/index.html | 72 + .../web/api/xmlhttprequest/readystate/index.html | 154 + .../requisicoes_sincronas_e_assincronas/index.html | 234 + files/pt-br/web/api/xmlhttprequest/send/index.html | 129 + .../api/xmlhttprequest/setrequestheader/index.html | 77 + .../web/api/xmlhttprequest/timeout/index.html | 51 + .../usando_xmlhttprequest/index.html | 688 +++ files/pt-br/web/css/--_star_/index.html | 149 + files/pt-br/web/css/-moz-binding/index.html | 57 + .../web/css/-moz-border-bottom-colors/index.html | 85 + .../web/css/-moz-border-left-colors/index.html | 85 + .../web/css/-moz-border-right-colors/index.html | 85 + .../web/css/-moz-border-top-colors/index.html | 85 + .../web/css/-moz-box-ordinal-group/index.html | 59 + files/pt-br/web/css/-moz-cell/index.html | 8 + .../web/css/-moz-context-properties/index.html | 79 + .../web/css/-webkit-overflow-scrolling/index.html | 105 + .../pt-br/web/css/-webkit-text-security/index.html | 49 + files/pt-br/web/css/@charset/index.html | 114 + files/pt-br/web/css/@font-face/index.html | 189 + files/pt-br/web/css/@import/index.html | 121 + files/pt-br/web/css/@keyframes/index.html | 222 + files/pt-br/web/css/@media/aspect-ratio/index.html | 128 + files/pt-br/web/css/@media/display-mode/index.html | 151 + files/pt-br/web/css/@media/index.html | 446 ++ .../web/css/@media/prefers-color-scheme/index.html | 104 + files/pt-br/web/css/@page/index.html | 109 + files/pt-br/web/css/_colon_active/index.html | 159 + files/pt-br/web/css/_colon_blank/index.html | 57 + files/pt-br/web/css/_colon_checked/index.html | 239 + files/pt-br/web/css/_colon_disabled/index.html | 128 + files/pt-br/web/css/_colon_empty/index.html | 96 + files/pt-br/web/css/_colon_enabled/index.html | 103 + files/pt-br/web/css/_colon_first-child/index.html | 139 + .../pt-br/web/css/_colon_first-of-type/index.html | 156 + files/pt-br/web/css/_colon_focus-within/index.html | 88 + files/pt-br/web/css/_colon_focus/index.html | 124 + files/pt-br/web/css/_colon_fullscreen/index.html | 87 + files/pt-br/web/css/_colon_hover/index.html | 185 + files/pt-br/web/css/_colon_invalid/index.html | 139 + files/pt-br/web/css/_colon_last-child/index.html | 121 + files/pt-br/web/css/_colon_last-of-type/index.html | 126 + files/pt-br/web/css/_colon_link/index.html | 105 + files/pt-br/web/css/_colon_not/index.html | 75 + files/pt-br/web/css/_colon_nth-child/index.html | 192 + .../pt-br/web/css/_colon_nth-last-child/index.html | 218 + files/pt-br/web/css/_colon_nth-of-type/index.html | 146 + files/pt-br/web/css/_colon_only-child/index.html | 197 + files/pt-br/web/css/_colon_only-of-type/index.html | 95 + files/pt-br/web/css/_colon_optional/index.html | 85 + files/pt-br/web/css/_colon_out-of-range/index.html | 111 + files/pt-br/web/css/_colon_read-write/index.html | 113 + files/pt-br/web/css/_colon_required/index.html | 85 + files/pt-br/web/css/_colon_root/index.html | 98 + files/pt-br/web/css/_colon_target/index.html | 208 + files/pt-br/web/css/_colon_valid/index.html | 74 + files/pt-br/web/css/_colon_visited/index.html | 154 + .../web/css/_doublecolon_-ms-tooltip/index.html | 23 + files/pt-br/web/css/_doublecolon_after/index.html | 241 + .../pt-br/web/css/_doublecolon_backdrop/index.html | 131 + files/pt-br/web/css/_doublecolon_before/index.html | 299 ++ .../web/css/_doublecolon_first-letter/index.html | 190 + .../web/css/_doublecolon_first-line/index.html | 115 + .../web/css/_doublecolon_selection/index.html | 129 + files/pt-br/web/css/align-content/index.html | 294 ++ files/pt-br/web/css/align-items/index.html | 286 ++ files/pt-br/web/css/align-self/index.html | 175 + files/pt-br/web/css/animation-delay/index.html | 145 + files/pt-br/web/css/animation-fill-mode/index.html | 183 + files/pt-br/web/css/animation/index.html | 353 ++ files/pt-br/web/css/at-rule/index.html | 33 + files/pt-br/web/css/attr()/index.html | 217 + files/pt-br/web/css/backdrop-filter/index.html | 140 + files/pt-br/web/css/backface-visibility/index.html | 257 ++ .../pt-br/web/css/background-attachment/index.html | 214 + .../pt-br/web/css/background-blend-mode/index.html | 153 + files/pt-br/web/css/background-clip/index.html | 247 + files/pt-br/web/css/background-color/index.html | 157 + files/pt-br/web/css/background-origin/index.html | 107 + files/pt-br/web/css/background-position/index.html | 178 + files/pt-br/web/css/background-size/index.html | 255 ++ files/pt-br/web/css/background/index.html | 129 + files/pt-br/web/css/blend-mode/index.html | 389 ++ files/pt-br/web/css/block-size/index.html | 104 + files/pt-br/web/css/border-left-color/index.html | 109 + files/pt-br/web/css/border-left/index.html | 155 + files/pt-br/web/css/border-radius/index.html | 332 ++ files/pt-br/web/css/box-shadow/index.html | 265 ++ files/pt-br/web/css/box-sizing/index.html | 71 + files/pt-br/web/css/box_model/index.html | 62 + files/pt-br/web/css/break-after/index.html | 187 + files/pt-br/web/css/calc()/index.html | 164 + files/pt-br/web/css/class_selectors/index.html | 106 + files/pt-br/web/css/clear/index.html | 239 + files/pt-br/web/css/color/index.html | 168 + files/pt-br/web/css/color_value/index.html | 1521 +++++++ "files/pt-br/web/css/coment\303\241rio/index.html" | 49 + files/pt-br/web/css/contain/index.html | 134 + files/pt-br/web/css/content/index.html | 322 ++ .../detecting_css_animation_support/index.html | 99 + files/pt-br/web/css/css_animations/index.html | 136 + files/pt-br/web/css/css_animations/tips/index.html | 105 + .../usando_anima\303\247\303\265es_css/index.html" | 332 ++ .../web/css/css_background_and_borders/index.html | 154 + .../using_css_multiple_backgrounds/index.html | 57 + .../web/css/css_basic_user_interface/index.html | 74 + files/pt-br/web/css/css_box_model/index.html | 170 + .../css/css_box_model/margin_collapsing/index.html | 74 + .../web/css/css_colors/seletor_de_cores/index.html | 3241 ++++++++++++++ files/pt-br/web/css/css_columns/index.html | 114 + files/pt-br/web/css/css_display/index.html | 110 + .../aligning_items_in_a_flex_container/index.html | 209 + .../conceitos_basicos_do_flexbox/index.html | 239 + .../web/css/css_flexible_box_layout/index.html | 111 + .../ordering_flex_items/index.html | 131 + .../typical_use_cases_of_flexbox/index.html | 135 + .../basic_concepts_of_grid_layout/index.html | 728 +++ files/pt-br/web/css/css_grid_layout/index.html | 191 + .../relationship_of_grid_layout/index.html | 640 +++ .../index.html | 47 + files/pt-br/web/css/css_images/index.html | 152 + .../web/css/css_lists_and_counters/index.html | 135 + .../using_css_counters/index.html | 115 + files/pt-br/web/css/css_positioning/index.html | 65 + files/pt-br/web/css/css_reference/index.html | 75 + files/pt-br/web/css/css_tipos/index.html | 64 + files/pt-br/web/css/css_transforms/index.html | 145 + .../css_transforms/using_css_transforms/index.html | 222 + files/pt-br/web/css/css_transitions/index.html | 61 + .../using_css_transitions/index.html | 1075 +++++ files/pt-br/web/css/cursor/index.html | 529 +++ .../pt-br/web/css/descendant_combinator/index.html | 108 + files/pt-br/web/css/display-box/index.html | 112 + files/pt-br/web/css/display-inside/index.html | 121 + files/pt-br/web/css/display-internal/index.html | 69 + files/pt-br/web/css/display-legacy/index.html | 102 + files/pt-br/web/css/display-listitem/index.html | 63 + files/pt-br/web/css/display-outside/index.html | 77 + files/pt-br/web/css/display/index.html | 355 ++ files/pt-br/web/css/element()/index.html | 101 + .../pt-br/web/css/elemento_substituido/index.html | 40 + files/pt-br/web/css/env()/index.html | 134 + .../web/css/filter-function/grayscale()/index.html | 39 + files/pt-br/web/css/filter-function/index.html | 68 + .../web/css/filter-function/opacity()/index.html | 40 + .../web/css/filter-function/sepia()/index.html | 35 + files/pt-br/web/css/flex-direction/index.html | 153 + files/pt-br/web/css/flex-flow/index.html | 89 + files/pt-br/web/css/flex-wrap/index.html | 162 + files/pt-br/web/css/flex/index.html | 267 ++ files/pt-br/web/css/float/index.html | 290 ++ files/pt-br/web/css/font-family/index.html | 238 + .../pt-br/web/css/font-feature-settings/index.html | 182 + files/pt-br/web/css/font-kerning/index.html | 166 + files/pt-br/web/css/font-size/index.html | 234 + .../web/css/font-variation-settings/index.html | 145 + files/pt-br/web/css/font-weight/index.html | 284 ++ .../web/css/general_sibling_combinator/index.html | 117 + .../cascading_and_inheritance/index.html | 127 + .../getting_started/como_css_funciona/index.html | 125 + files/pt-br/web/css/getting_started/index.html | 97 + .../web/css/getting_started/javascript/index.html | 139 + .../pt-br/web/css/getting_started/lists/index.html | 271 ++ .../getting_started/oque_é_css/index.html | 111 + .../css/getting_started/porque_usar_css/index.html | 105 + .../web/css/getting_started/seletores/index.html | 429 ++ files/pt-br/web/css/grid-auto-flow/index.html | 207 + .../pt-br/web/css/grid-template-columns/index.html | 193 + files/pt-br/web/css/grid-template-rows/index.html | 204 + files/pt-br/web/css/grid/index.html | 187 + files/pt-br/web/css/height/index.html | 192 + files/pt-br/web/css/hifens/index.html | 902 ++++ files/pt-br/web/css/id_selectors/index.html | 124 + files/pt-br/web/css/image-set()/index.html | 78 + files/pt-br/web/css/imagem/index.html | 157 + files/pt-br/web/css/index.html | 99 + files/pt-br/web/css/inheritance/index.html | 53 + files/pt-br/web/css/initial/index.html | 80 + files/pt-br/web/css/inline-size/index.html | 93 + files/pt-br/web/css/isolation/index.html | 154 + .../breadcrumb_navigation/index.html | 57 + files/pt-br/web/css/layout_cookbook/index.html | 85 + .../css/layout_cookbook/media_objects/index.html | 80 + files/pt-br/web/css/letter-spacing/index.html | 118 + files/pt-br/web/css/line-break/index.html | 64 + files/pt-br/web/css/margin-bottom/index.html | 135 + files/pt-br/web/css/margin-top/index.html | 145 + files/pt-br/web/css/margin/index.html | 172 + files/pt-br/web/css/max-width/index.html | 200 + files/pt-br/web/css/media_queries/index.html | 118 + .../pt-br/web/css/microsoft_extensions/index.html | 114 + files/pt-br/web/css/min-height/index.html | 181 + files/pt-br/web/css/mix-blend-mode/index.html | 164 + files/pt-br/web/css/modelo_layout/index.html | 25 + files/pt-br/web/css/modelo_visual/index.html | 227 + files/pt-br/web/css/number/index.html | 92 + files/pt-br/web/css/object-fit/index.html | 206 + files/pt-br/web/css/offset/index.html | 158 + files/pt-br/web/css/opacity/index.html | 212 + files/pt-br/web/css/outline/index.html | 135 + files/pt-br/web/css/overflow/index.html | 166 + files/pt-br/web/css/padding-left/index.html | 147 + files/pt-br/web/css/padding/index.html | 189 + files/pt-br/web/css/page-break-before/index.html | 142 + files/pt-br/web/css/pointer-events/index.html | 178 + files/pt-br/web/css/position/index.html | 319 ++ .../index.html | 76 + files/pt-br/web/css/pseudo-classes/index.html | 143 + files/pt-br/web/css/pseudo-elementos/index.html | 104 + files/pt-br/web/css/radial-gradient()/index.html | 209 + .../web/css/repeating-linear-gradient()/index.html | 153 + files/pt-br/web/css/ruby-align/index.html | 239 + files/pt-br/web/css/scroll-behavior/index.html | 172 + files/pt-br/web/css/scrollbar-color/index.html | 119 + .../pt-br/web/css/seletor_de_atributos/index.html | 158 + files/pt-br/web/css/seletor_universal/index.html | 105 + files/pt-br/web/css/seletores_css/index.html | 150 + .../pt-br/web/css/shorthand_properties/index.html | 140 + files/pt-br/web/css/sintaxe/index.html | 70 + files/pt-br/web/css/sintexe_valor/index.html | 436 ++ files/pt-br/web/css/specificity/index.html | 121 + files/pt-br/web/css/text-align/index.html | 337 ++ .../pt-br/web/css/text-decoration-style/index.html | 197 + files/pt-br/web/css/text-decoration/index.html | 205 + files/pt-br/web/css/text-overflow/index.html | 374 ++ files/pt-br/web/css/text-rendering/index.html | 189 + files/pt-br/web/css/text-shadow/index.html | 193 + files/pt-br/web/css/text-transform/index.html | 307 ++ files/pt-br/web/css/time/index.html | 89 + .../css/tools/border-image_generator/index.html | 2627 +++++++++++ .../css/tools/border-radius_generator/index.html | 1593 +++++++ files/pt-br/web/css/tools/index.html | 30 + files/pt-br/web/css/touch-action/index.html | 137 + files/pt-br/web/css/transform-function/index.html | 227 + .../web/css/transform-function/matrix()/index.html | 111 + .../transform-function/perspective()/index.html | 123 + .../web/css/transform-function/rotate()/index.html | 85 + .../css/transform-function/rotate3d()/index.html | 127 + .../web/css/transform-function/scale()/index.html | 125 + .../css/transform-function/translate()/index.html | 152 + files/pt-br/web/css/transform-style/index.html | 74 + files/pt-br/web/css/transform/index.html | 283 ++ files/pt-br/web/css/transition-delay/index.html | 357 ++ .../web/css/transition-timing-function/index.html | 666 +++ files/pt-br/web/css/transition/index.html | 130 + files/pt-br/web/css/type_selectors/index.html | 78 + .../web/css/using_css_custom_properties/index.html | 346 ++ files/pt-br/web/css/valor_atual/index.html | 34 + files/pt-br/web/css/valor_computado/index.html | 56 + files/pt-br/web/css/valor_espeficifco/index.html | 44 + files/pt-br/web/css/valor_inicial/index.html | 30 + files/pt-br/web/css/valor_resolvido/index.html | 40 + files/pt-br/web/css/valor_usado/index.html | 114 + files/pt-br/web/css/var()/index.html | 146 + files/pt-br/web/css/vertical-align/index.html | 300 ++ files/pt-br/web/css/visibility/index.html | 168 + files/pt-br/web/css/white-space/index.html | 140 + files/pt-br/web/css/width/index.html | 411 ++ files/pt-br/web/css/will-change/index.html | 178 + files/pt-br/web/css/word-break/index.html | 132 + files/pt-br/web/css/word-wrap/index.html | 117 + files/pt-br/web/css/writing-mode/index.html | 365 ++ .../web/demos_of_open_web_technologies/index.html | 241 + files/pt-br/web/events/abort/index.html | 69 + files/pt-br/web/events/beforeunload/index.html | 106 + files/pt-br/web/events/blur/index.html | 154 + files/pt-br/web/events/domcontentloaded/index.html | 177 + files/pt-br/web/events/focus/index.html | 137 + files/pt-br/web/events/focusin/index.html | 125 + files/pt-br/web/events/focusout/index.html | 125 + files/pt-br/web/events/index.html | 2647 +++++++++++ files/pt-br/web/events/input/index.html | 248 ++ files/pt-br/web/events/load/index.html | 89 + files/pt-br/web/events/readystatechange/index.html | 83 + .../web/guide/ajax/getting_started/index.html | 290 ++ files/pt-br/web/guide/ajax/index.html | 92 + files/pt-br/web/guide/api/camera/index.html | 220 + files/pt-br/web/guide/api/index.html | 26 + .../web/guide/css/css_media_queries/index.html | 639 +++ .../index.html" | 20 + .../guide/css/scaling_background_images/index.html | 108 + .../web/guide/css/understanding_z_index/index.html | 48 + .../events/criando_e_disparando_eventos/index.html | 145 + .../web/guide/events/event_handlers/index.html | 164 + files/pt-br/web/guide/events/index.html | 36 + .../web/guide/events/mutation_events/index.html | 62 + .../overview_of_events_and_handlers/index.html | 132 + .../pt-br/web/guide/events/touch_events/index.html | 353 ++ "files/pt-br/web/guide/gr\303\241ficos/index.html" | 49 + .../canvas_tutorial/advanced_animations/index.html | 386 ++ .../applying_styles_and_colors/index.html | 725 +++ .../canvas_tutorial/basic_animations/index.html | 331 ++ .../canvas_tutorial/compositing/exemplo/index.html | 294 ++ .../html/canvas_tutorial/compositing/index.html | 112 + .../canvas_tutorial/conclus\303\243o/index.html" | 49 + .../html/canvas_tutorial/drawing_shapes/index.html | 581 +++ .../html/canvas_tutorial/drawing_text/index.html | 169 + .../web/guide/html/canvas_tutorial/index.html | 56 + .../canvas_tutorial/otimizando_canvas/index.html | 115 + .../html/canvas_tutorial/using_images/index.html | 333 ++ .../canvas_tutorial/utilizacao_basica/index.html | 153 + .../guide/html/categorias_de_conteudo/index.html | 148 + .../web/guide/html/content_editable/index.html | 57 + .../guide/html/forms/form_validation/index.html | 813 ++++ .../how_to_build_custom_form_widgets/index.html | 786 ++++ .../forms/how_to_structure_an_html_form/index.html | 304 ++ files/pt-br/web/guide/html/forms/index.html | 79 + .../forms/meu_primeiro_formulario_html/index.html | 270 ++ .../guide/html/forms/os_widgets_nativos/index.html | 701 +++ .../sending_and_retrieving_form_data/index.html | 251 ++ .../guide/html/using_data_attributes/index.html | 72 + files/pt-br/web/guide/index.html | 68 + .../introducao_ao_desenvolvimento_web/index.html | 97 + files/pt-br/web/guide/mobile/index.html | 72 + files/pt-br/web/guide/performance/index.html | 14 + files/pt-br/web/guide/printing/index.html | 118 + files/pt-br/web/html/applying_color/index.html | 488 ++ .../web/html/canvas/a_basic_ray-caster/index.html | 76 + files/pt-br/web/html/canvas/index.html | 134 + .../index.html | 68 + .../web/html/cors_imagens_habilitadas/index.html | 113 + .../index.html" | 135 + files/pt-br/web/html/element/a/index.html | 486 ++ files/pt-br/web/html/element/abbr/index.html | 155 + files/pt-br/web/html/element/acronym/index.html | 109 + files/pt-br/web/html/element/address/index.html | 163 + files/pt-br/web/html/element/applet/index.html | 133 + files/pt-br/web/html/element/area/index.html | 196 + files/pt-br/web/html/element/article/index.html | 124 + files/pt-br/web/html/element/aside/index.html | 129 + files/pt-br/web/html/element/audio/index.html | 301 ++ files/pt-br/web/html/element/b/index.html | 120 + files/pt-br/web/html/element/base/index.html | 138 + files/pt-br/web/html/element/bdi/index.html | 118 + files/pt-br/web/html/element/bdo/index.html | 106 + files/pt-br/web/html/element/big/index.html | 80 + files/pt-br/web/html/element/blink/index.html | 102 + files/pt-br/web/html/element/blockquote/index.html | 153 + files/pt-br/web/html/element/body/index.html | 232 + files/pt-br/web/html/element/br/index.html | 153 + files/pt-br/web/html/element/button/index.html | 321 ++ files/pt-br/web/html/element/canvas/index.html | 130 + files/pt-br/web/html/element/caption/index.html | 196 + files/pt-br/web/html/element/center/index.html | 69 + files/pt-br/web/html/element/cite/index.html | 149 + files/pt-br/web/html/element/code/index.html | 108 + files/pt-br/web/html/element/col/index.html | 230 + files/pt-br/web/html/element/command/index.html | 129 + .../web/html/element/conte\303\272do/index.html" | 101 + files/pt-br/web/html/element/data/index.html | 104 + files/pt-br/web/html/element/datalist/index.html | 121 + files/pt-br/web/html/element/dd/index.html | 112 + files/pt-br/web/html/element/del/index.html | 88 + files/pt-br/web/html/element/details/index.html | 114 + files/pt-br/web/html/element/dfn/index.html | 141 + files/pt-br/web/html/element/dialog/index.html | 167 + files/pt-br/web/html/element/dir/index.html | 64 + files/pt-br/web/html/element/div/index.html | 121 + files/pt-br/web/html/element/dl/index.html | 180 + files/pt-br/web/html/element/dt/index.html | 111 + files/pt-br/web/html/element/em/index.html | 117 + files/pt-br/web/html/element/embed/index.html | 128 + files/pt-br/web/html/element/fieldset/index.html | 407 ++ files/pt-br/web/html/element/figcaption/index.html | 90 + files/pt-br/web/html/element/figura/index.html | 193 + files/pt-br/web/html/element/footer/index.html | 114 + files/pt-br/web/html/element/form/index.html | 215 + files/pt-br/web/html/element/head/index.html | 153 + files/pt-br/web/html/element/header/index.html | 119 + .../web/html/element/heading_elements/index.html | 168 + files/pt-br/web/html/element/hgroup/index.html | 125 + files/pt-br/web/html/element/hr/index.html | 149 + files/pt-br/web/html/element/html/index.html | 139 + files/pt-br/web/html/element/i/index.html | 158 + files/pt-br/web/html/element/iframe/index.html | 178 + files/pt-br/web/html/element/img/index.html | 307 ++ files/pt-br/web/html/element/index.html | 105 + .../pt-br/web/html/element/input/button/index.html | 353 ++ .../web/html/element/input/checkbox/index.html | 299 ++ files/pt-br/web/html/element/input/data/index.html | 430 ++ files/pt-br/web/html/element/input/index.html | 1360 ++++++ .../web/html/element/input/password/index.html | 232 + .../pt-br/web/html/element/input/range/index.html | 390 ++ files/pt-br/web/html/element/input/time/index.html | 458 ++ files/pt-br/web/html/element/ins/index.html | 87 + files/pt-br/web/html/element/label/index.html | 143 + files/pt-br/web/html/element/legend/index.html | 126 + files/pt-br/web/html/element/li/index.html | 177 + files/pt-br/web/html/element/link/index.html | 330 ++ files/pt-br/web/html/element/main/index.html | 152 + files/pt-br/web/html/element/map/index.html | 136 + files/pt-br/web/html/element/mark/index.html | 137 + files/pt-br/web/html/element/marquee/index.html | 102 + files/pt-br/web/html/element/meta/index.html | 538 +++ files/pt-br/web/html/element/meter/index.html | 92 + files/pt-br/web/html/element/nav/index.html | 133 + files/pt-br/web/html/element/nobr/index.html | 26 + files/pt-br/web/html/element/noscript/index.html | 128 + files/pt-br/web/html/element/ol/index.html | 261 ++ files/pt-br/web/html/element/optgroup/index.html | 131 + files/pt-br/web/html/element/option/index.html | 122 + files/pt-br/web/html/element/output/index.html | 123 + files/pt-br/web/html/element/p/index.html | 152 + files/pt-br/web/html/element/picture/index.html | 148 + files/pt-br/web/html/element/pre/index.html | 191 + files/pt-br/web/html/element/progress/index.html | 83 + files/pt-br/web/html/element/q/index.html | 116 + files/pt-br/web/html/element/rt/index.html | 96 + files/pt-br/web/html/element/ruby/index.html | 124 + files/pt-br/web/html/element/s/index.html | 127 + files/pt-br/web/html/element/script/index.html | 297 ++ files/pt-br/web/html/element/section/index.html | 168 + files/pt-br/web/html/element/select/index.html | 180 + files/pt-br/web/html/element/source/index.html | 135 + files/pt-br/web/html/element/span/index.html | 106 + files/pt-br/web/html/element/strong/index.html | 170 + files/pt-br/web/html/element/style/index.html | 177 + files/pt-br/web/html/element/summary/index.html | 110 + files/pt-br/web/html/element/table/index.html | 447 ++ files/pt-br/web/html/element/template/index.html | 198 + files/pt-br/web/html/element/textarea/index.html | 262 ++ files/pt-br/web/html/element/tfoot/index.html | 203 + files/pt-br/web/html/element/th/index.html | 234 + files/pt-br/web/html/element/time/index.html | 145 + files/pt-br/web/html/element/title/index.html | 93 + files/pt-br/web/html/element/track/index.html | 162 + files/pt-br/web/html/element/ul/index.html | 186 + files/pt-br/web/html/element/var/index.html | 59 + files/pt-br/web/html/element/video/index.html | 348 ++ files/pt-br/web/html/element/wbr/index.html | 106 + .../web/html/elementos_block-level/index.html | 126 + files/pt-br/web/html/favicon/index.html | 32 + .../web/html/formatos_midia_suportados/index.html | 525 +++ .../html/global_attributes/accesskey/index.html | 141 + .../global_attributes/autocapitalize/index.html | 49 + .../web/html/global_attributes/class/index.html | 108 + .../global_attributes/contenteditable/index.html | 77 + .../html/global_attributes/data-_star_/index.html | 116 + .../web/html/global_attributes/hidden/index.html | 111 + .../pt-br/web/html/global_attributes/id/index.html | 115 + files/pt-br/web/html/global_attributes/index.html | 479 ++ .../web/html/global_attributes/itemprop/index.html | 513 +++ .../web/html/global_attributes/lang/index.html | 89 + .../web/html/global_attributes/tabindex/index.html | 127 + .../web/html/global_attributes/title/index.html | 139 + files/pt-br/web/html/html5/index.html | 299 ++ .../html/html5/introduction_to_html5/index.html | 23 + files/pt-br/web/html/index.html | 118 + files/pt-br/web/html/inline_elemente/index.html | 29 + files/pt-br/web/html/microformatos/index.html | 444 ++ .../index.html | 23 + files/pt-br/web/html/preloading_content/index.html | 239 + .../html/quirks_mode_and_standards_mode/index.html | 55 + files/pt-br/web/html/referenciahtml/index.html | 25 + .../html/using_html5_audio_and_video/index.html | 239 + .../html/using_the_application_cache/index.html | 392 ++ files/pt-br/web/http/authentication/index.html | 126 + .../identifying_resources_on_the_web/index.html | 183 + files/pt-br/web/http/basico_sobre_http/index.html | 61 + .../complete_list_of_mime_types/index.html | 336 ++ .../http/basico_sobre_http/mime_types/index.html | 314 ++ .../pt-br/web/http/compress\303\243o/index.html" | 72 + .../pt-br/web/http/content_negotiation/index.html | 156 + .../list_of_default_accept_values/index.html | 264 ++ .../pt-br/web/http/controle_acesso_cors/index.html | 553 +++ files/pt-br/web/http/cookies/index.html | 213 + .../http/cors/errors/corsdidnotsucceed/index.html | 33 + .../cors/errors/corsmissingalloworigin/index.html | 55 + .../errors/corsnotsupportingcredentials/index.html | 34 + .../http/cors/errors/corsrequestnothttp/index.html | 43 + files/pt-br/web/http/cors/errors/index.html | 76 + files/pt-br/web/http/csp/index.html | 135 + files/pt-br/web/http/feature_policy/index.html | 172 + .../feature_policy/using_feature_policy/index.html | 156 + .../index.html" | 94 + .../web/http/headers/accept-ch-lifetime/index.html | 54 + files/pt-br/web/http/headers/accept-ch/index.html | 60 + .../web/http/headers/accept-charset/index.html | 96 + .../web/http/headers/accept-encoding/index.html | 119 + .../web/http/headers/accept-language/index.html | 97 + .../pt-br/web/http/headers/accept-patch/index.html | 89 + .../web/http/headers/accept-ranges/index.html | 84 + files/pt-br/web/http/headers/accept/index.html | 100 + .../access-control-allow-credentials/index.html | 101 + .../access-control-allow-headers/index.html | 127 + .../access-control-allow-methods/index.html | 83 + .../headers/access-control-allow-origin/index.html | 91 + .../access-control-expose-headers/index.html | 106 + .../http/headers/access-control-max-age/index.html | 82 + .../access-control-request-headers/index.html | 66 + .../access-control-request-method/index.html | 72 + files/pt-br/web/http/headers/age/index.html | 71 + files/pt-br/web/http/headers/allow/index.html | 67 + files/pt-br/web/http/headers/alt-svc/index.html | 71 + .../web/http/headers/authorization/index.html | 94 + .../web/http/headers/cache-control/index.html | 174 + .../web/http/headers/clear-site-data/index.html | 116 + .../web/http/headers/conex\303\243o/index.html" | 54 + .../http/headers/content-disposition/index.html | 140 + .../web/http/headers/content-encoding/index.html | 108 + .../web/http/headers/content-language/index.html | 104 + .../web/http/headers/content-length/index.html | 64 + .../web/http/headers/content-location/index.html | 156 + .../web/http/headers/content-range/index.html | 89 + .../content-security-policy-report-only/index.html | 154 + .../headers/content-security-policy/index.html | 261 ++ .../pt-br/web/http/headers/content-type/index.html | 117 + files/pt-br/web/http/headers/cookie/index.html | 75 + files/pt-br/web/http/headers/cookie2/index.html | 60 + .../cross-origin-resource-policy/index.html | 76 + files/pt-br/web/http/headers/date/index.html | 105 + .../web/http/headers/device-memory/index.html | 84 + files/pt-br/web/http/headers/digest/index.html | 90 + files/pt-br/web/http/headers/dnt/index.html | 88 + files/pt-br/web/http/headers/dpr/index.html | 63 + files/pt-br/web/http/headers/early-data/index.html | 63 + files/pt-br/web/http/headers/etag/index.html | 107 + files/pt-br/web/http/headers/expect-ct/index.html | 110 + files/pt-br/web/http/headers/expect/index.html | 96 + files/pt-br/web/http/headers/expires/index.html | 77 + .../web/http/headers/feature-policy/index.html | 163 + files/pt-br/web/http/headers/forwarded/index.html | 118 + files/pt-br/web/http/headers/from/index.html | 74 + files/pt-br/web/http/headers/host/index.html | 72 + files/pt-br/web/http/headers/if-match/index.html | 94 + .../web/http/headers/if-modified-since/index.html | 89 + .../web/http/headers/if-none-match/index.html | 96 + files/pt-br/web/http/headers/if-range/index.html | 104 + .../http/headers/if-unmodified-since/index.html | 95 + files/pt-br/web/http/headers/index.html | 370 ++ files/pt-br/web/http/headers/keep-alive/index.html | 90 + .../web/http/headers/large-allocation/index.html | 94 + .../web/http/headers/last-modified/index.html | 87 + files/pt-br/web/http/headers/link/index.html | 77 + .../headers/localiza\303\247\303\243o/index.html" | 82 + files/pt-br/web/http/headers/nel/index.html | 52 + files/pt-br/web/http/headers/origin/index.html | 87 + files/pt-br/web/http/headers/pragma/index.html | 81 + .../web/http/headers/proxy-authenticate/index.html | 85 + .../http/headers/proxy-authorization/index.html | 83 + .../headers/public-key-pins-report-only/index.html | 89 + .../web/http/headers/public-key-pins/index.html | 95 + files/pt-br/web/http/headers/range/index.html | 94 + files/pt-br/web/http/headers/referer/index.html | 88 + .../web/http/headers/referrer-policy/index.html | 257 ++ .../pt-br/web/http/headers/retry-after/index.html | 80 + files/pt-br/web/http/headers/save-data/index.html | 104 + .../web/http/headers/sec-fetch-site/index.html | 85 + .../web/http/headers/server-timing/index.html | 87 + files/pt-br/web/http/headers/server/index.html | 66 + files/pt-br/web/http/headers/set-cookie/index.html | 167 + .../http/headers/set-cookie/samesite/index.html | 114 + .../pt-br/web/http/headers/set-cookie2/index.html | 75 + files/pt-br/web/http/headers/sourcemap/index.html | 65 + .../headers/strict-transport-security/index.html | 122 + files/pt-br/web/http/headers/te/index.html | 88 + .../http/headers/timing-allow-origin/index.html | 83 + files/pt-br/web/http/headers/tk/index.html | 100 + files/pt-br/web/http/headers/trailer/index.html | 105 + .../web/http/headers/transfer-encoding/index.html | 112 + .../headers/upgrade-insecure-requests/index.html | 72 + files/pt-br/web/http/headers/user-agent/index.html | 147 + files/pt-br/web/http/headers/vary/index.html | 87 + files/pt-br/web/http/headers/via/index.html | 80 + .../pt-br/web/http/headers/want-digest/index.html | 129 + files/pt-br/web/http/headers/warning/index.html | 146 + .../web/http/headers/www-authenticate/index.html | 93 + .../http/headers/x-content-type-options/index.html | 83 + .../http/headers/x-dns-prefetch-control/index.html | 101 + .../web/http/headers/x-forwarded-for/index.html | 81 + .../web/http/headers/x-forwarded-host/index.html | 70 + .../web/http/headers/x-forwarded-proto/index.html | 74 + .../web/http/headers/x-frame-options/index.html | 160 + .../web/http/headers/x-xss-protection/index.html | 97 + files/pt-br/web/http/http/index.html | 157 + files/pt-br/web/http/index.html | 73 + files/pt-br/web/http/mensagens/index.html | 146 + files/pt-br/web/http/methods/connect/index.html | 86 + files/pt-br/web/http/methods/delete/index.html | 99 + files/pt-br/web/http/methods/get/index.html | 78 + files/pt-br/web/http/methods/head/index.html | 78 + files/pt-br/web/http/methods/index.html | 87 + files/pt-br/web/http/methods/options/index.html | 122 + files/pt-br/web/http/methods/patch/index.html | 99 + files/pt-br/web/http/methods/post/index.html | 122 + files/pt-br/web/http/methods/put/index.html | 100 + files/pt-br/web/http/methods/trace/index.html | 75 + files/pt-br/web/http/overview/index.html | 201 + files/pt-br/web/http/redirecionamento/index.html | 260 ++ .../web/http/server-side_access_control/index.html | 212 + files/pt-br/web/http/session/index.html | 161 + files/pt-br/web/http/status/100/index.html | 42 + files/pt-br/web/http/status/101/index.html | 46 + files/pt-br/web/http/status/103/index.html | 50 + files/pt-br/web/http/status/200/index.html | 52 + files/pt-br/web/http/status/201/index.html | 41 + files/pt-br/web/http/status/202/index.html | 37 + files/pt-br/web/http/status/203/index.html | 37 + files/pt-br/web/http/status/204/index.html | 49 + files/pt-br/web/http/status/205/index.html | 39 + files/pt-br/web/http/status/206/index.html | 85 + files/pt-br/web/http/status/300/index.html | 43 + files/pt-br/web/http/status/301/index.html | 61 + files/pt-br/web/http/status/302/index.html | 51 + files/pt-br/web/http/status/303/index.html | 46 + files/pt-br/web/http/status/304/index.html | 57 + files/pt-br/web/http/status/307/index.html | 48 + files/pt-br/web/http/status/308/index.html | 50 + files/pt-br/web/http/status/400/index.html | 46 + files/pt-br/web/http/status/401/index.html | 59 + files/pt-br/web/http/status/402/index.html | 54 + files/pt-br/web/http/status/403/index.html | 47 + files/pt-br/web/http/status/404/index.html | 56 + files/pt-br/web/http/status/405/index.html | 35 + files/pt-br/web/http/status/406/index.html | 62 + files/pt-br/web/http/status/407/index.html | 58 + files/pt-br/web/http/status/408/index.html | 47 + files/pt-br/web/http/status/409/index.html | 35 + files/pt-br/web/http/status/410/index.html | 47 + files/pt-br/web/http/status/411/index.html | 43 + files/pt-br/web/http/status/412/index.html | 52 + files/pt-br/web/http/status/413/index.html | 34 + files/pt-br/web/http/status/414/index.html | 46 + files/pt-br/web/http/status/415/index.html | 45 + files/pt-br/web/http/status/416/index.html | 53 + files/pt-br/web/http/status/417/index.html | 35 + files/pt-br/web/http/status/418/index.html | 41 + files/pt-br/web/http/status/422/index.html | 33 + files/pt-br/web/http/status/425/index.html | 35 + files/pt-br/web/http/status/426/index.html | 48 + files/pt-br/web/http/status/428/index.html | 39 + files/pt-br/web/http/status/429/index.html | 48 + files/pt-br/web/http/status/431/index.html | 54 + files/pt-br/web/http/status/451/index.html | 65 + files/pt-br/web/http/status/500/index.html | 37 + files/pt-br/web/http/status/501/index.html | 46 + files/pt-br/web/http/status/502/index.html | 51 + files/pt-br/web/http/status/503/index.html | 50 + files/pt-br/web/http/status/504/index.html | 43 + files/pt-br/web/http/status/505/index.html | 33 + files/pt-br/web/http/status/506/index.html | 35 + files/pt-br/web/http/status/507/index.html | 33 + files/pt-br/web/http/status/508/index.html | 35 + files/pt-br/web/http/status/510/index.html | 33 + files/pt-br/web/http/status/511/index.html | 42 + files/pt-br/web/http/status/index.html | 192 + files/pt-br/web/index.html | 53 + .../a_re-introduction_to_javascript/index.html | 878 ++++ .../web/javascript/about_javascript/index.html | 63 + .../web/javascript/data_structures/index.html | 287 ++ .../index.html | 280 ++ .../equality_comparisons_and_sameness/index.html | 432 ++ files/pt-br/web/javascript/eventloop/index.html | 161 + .../pt-br/web/javascript/guide/closures/index.html | 336 ++ .../cole\303\247\303\265es_chaveadas/index.html" | 149 + .../guide/declara\303\247\303\265es/index.html" | 429 ++ .../guide/detalhes_do_modelo_do_objeto/index.html | 705 +++ .../guide/expressions_and_operators/index.html | 944 ++++ .../javascript/guide/formatando_texto/index.html | 250 ++ .../guide/fun\303\247\303\265es/index.html" | 640 +++ .../web/javascript/guide/igualdade/index.html | 258 ++ files/pt-br/web/javascript/guide/index.html | 127 + .../guide/indexed_collections/index.html | 452 ++ .../inheritance_and_the_prototype_chain/index.html | 193 + .../web/javascript/guide/introduction/index.html | 153 + .../guide/iteratores_e_geradores/index.html | 161 + .../javascript/guide/keyed_collections/index.html | 156 + .../javascript/guide/lacos_e_iteracoes/index.html | 333 ++ .../javascript/guide/meta_programming/index.html | 263 ++ .../javascript/guide/m\303\263dulos/index.html" | 454 ++ .../javascript/guide/numeros_e_datas/index.html | 374 ++ .../guide/regular_expressions/index.html | 637 +++ .../javascript/guide/sintaxe_e_tipos/index.html | 583 +++ .../guide/trabalhando_com_objetos/index.html | 494 ++ .../javascript/guide/usando_promises/index.html | 269 ++ .../values,_variables,_and_literals/index.html | 601 +++ files/pt-br/web/javascript/index.html | 110 + .../index.html | 351 ++ .../javascript_technologies_overview/index.html | 89 + .../web/javascript/language_resources/index.html | 136 + .../web/javascript/memory_management/index.html | 197 + .../javascript/new_in_javascript/1.1/index.html | 71 + .../javascript/new_in_javascript/1.6/index.html | 33 + .../javascript/new_in_javascript/1.7/index.html | 50 + .../javascript/new_in_javascript/1.8.5/index.html | 130 + .../ecmascript_5_support_in_mozilla/index.html | 53 + .../web/javascript/new_in_javascript/index.html | 80 + .../web/javascript/reference/about/index.html | 52 + .../reference/classes/constructor/index.html | 174 + .../reference/classes/extends/index.html | 106 + .../web/javascript/reference/classes/index.html | 364 ++ .../javascript/reference/classes/static/index.html | 131 + .../deprecated_and_obsolete_features/index.html | 294 ++ .../index.html | 61 + .../errors/cant_access_property/index.html | 60 + .../index.html" | 38 + .../index.html | 52 + .../for-each-in_loops_are_deprecated/index.html | 169 + .../reference/errors/illegal_character/index.html | 77 + .../web/javascript/reference/errors/index.html | 14 + .../errors/invalid_array_length/index.html | 78 + .../invalid_assignment_left-hand_side/index.html | 50 + .../errors/invalid_const_assignment/index.html | 91 + .../reference/errors/invalid_date/index.html | 55 + .../reference/errors/json_bad_parse/index.html | 105 + .../missing_colon_after_property_id/index.html | 72 + .../missing_curly_after_function_body/index.html | 67 + .../errors/missing_formal_parameter/index.html | 80 + .../missing_semicolon_before_statement/index.html | 63 + .../errors/negative_repetition_count/index.html | 45 + .../reference/errors/no_variable_name/index.html | 79 + .../reference/errors/not_a_codepoint/index.html | 56 + .../reference/errors/not_a_function/index.html | 123 + .../errors/n\303\243o_definido/index.html" | 66 + .../index.html" | 116 + .../reference/errors/precision_range/index.html | 101 + .../errors/property_access_denied/index.html | 42 + .../reference/errors/read-only/index.html | 81 + .../errors/redeclared_parameter/index.html | 60 + .../reference/errors/stmt_after_return/index.html | 74 + .../reference/errors/too_much_recursion/index.html | 66 + .../reference/errors/undeclared_var/index.html | 62 + .../reference/errors/undefined_prop/index.html | 67 + .../reference/errors/unexpected_token/index.html | 51 + .../reference/errors/unexpected_type/index.html | 67 + .../errors/unterminated_string_literal/index.html | 63 + .../reference/functions/arguments/index.html | 258 ++ .../reference/functions/arrow_functions/index.html | 384 ++ .../functions/definicoes_metodos/index.html | 200 + .../javascript/reference/functions/get/index.html | 217 + .../web/javascript/reference/functions/index.html | 480 ++ .../functions/parametros_predefinidos/index.html | 210 + .../reference/functions/rest_parameters/index.html | 178 + .../javascript/reference/functions/set/index.html | 210 + .../global_objects/array/@@iterator/index.html | 122 + .../global_objects/array/@@unscopables/index.html | 75 + .../global_objects/array/concat/index.html | 159 + .../global_objects/array/contains/index.html | 106 + .../global_objects/array/copywithin/index.html | 203 + .../global_objects/array/entries/index.html | 117 + .../global_objects/array/every/index.html | 176 + .../reference/global_objects/array/fill/index.html | 125 + .../global_objects/array/filtro/index.html | 227 + .../reference/global_objects/array/find/index.html | 157 + .../global_objects/array/findindex/index.html | 127 + .../reference/global_objects/array/flat/index.html | 121 + .../global_objects/array/flatmap/index.html | 126 + .../global_objects/array/foreach/index.html | 212 + .../reference/global_objects/array/from/index.html | 205 + .../reference/global_objects/array/index.html | 511 +++ .../global_objects/array/indexof/index.html | 186 + .../global_objects/array/isarray/index.html | 141 + .../reference/global_objects/array/join/index.html | 108 + .../reference/global_objects/array/keys/index.html | 115 + .../global_objects/array/lastindexof/index.html | 184 + .../global_objects/array/length/index.html | 128 + .../reference/global_objects/array/map/index.html | 255 ++ .../global_objects/array/observe/index.html | 128 + .../reference/global_objects/array/of/index.html | 108 + .../reference/global_objects/array/pop/index.html | 81 + .../global_objects/array/prototype/index.html | 206 + .../reference/global_objects/array/push/index.html | 184 + .../global_objects/array/reduce/index.html | 513 +++ .../global_objects/array/reduceright/index.html | 258 ++ .../global_objects/array/reverse/index.html | 121 + .../global_objects/array/shift/index.html | 104 + .../global_objects/array/slice/index.html | 224 + .../reference/global_objects/array/some/index.html | 134 + .../reference/global_objects/array/sort/index.html | 232 + .../global_objects/array/splice/index.html | 173 + .../global_objects/array/tolocalestring/index.html | 140 + .../global_objects/array/tosource/index.html | 113 + .../global_objects/array/tostring/index.html | 115 + .../global_objects/array/unobserve/index.html | 129 + .../global_objects/array/unshift/index.html | 90 + .../global_objects/array/values/index.html | 121 + .../global_objects/arraybuffer/index.html | 148 + .../global_objects/asyncfunction/index.html | 173 + .../global_objects/atomics/add/index.html | 132 + .../reference/global_objects/atomics/index.html | 155 + .../reference/global_objects/bigint/index.html | 240 + .../global_objects/bigint/prototype/index.html | 61 + .../reference/global_objects/boolean/index.html | 194 + .../global_objects/boolean/prototype/index.html | 111 + .../global_objects/boolean/tosource/index.html | 96 + .../global_objects/boolean/tostring/index.html | 128 + .../global_objects/boolean/valueof/index.html | 115 + .../reference/global_objects/dataview/index.html | 168 + .../global_objects/date/@@toprimitive/index.html | 77 + .../global_objects/date/getdate/index.html | 127 + .../global_objects/date/getday/index.html | 127 + .../global_objects/date/getfullyear/index.html | 127 + .../global_objects/date/gethours/index.html | 126 + .../global_objects/date/getmilliseconds/index.html | 117 + .../global_objects/date/getminutes/index.html | 121 + .../global_objects/date/getmonth/index.html | 121 + .../global_objects/date/getseconds/index.html | 121 + .../global_objects/date/gettime/index.html | 137 + .../date/gettimezoneoffset/index.html | 107 + .../global_objects/date/getutcdate/index.html | 118 + .../global_objects/date/getutcday/index.html | 117 + .../global_objects/date/getutcfullyear/index.html | 81 + .../global_objects/date/getutchours/index.html | 63 + .../date/getutcmilliseconds/index.html | 77 + .../global_objects/date/getutcminutes/index.html | 62 + .../global_objects/date/getutcmonth/index.html | 77 + .../global_objects/date/getutcseconds/index.html | 75 + .../global_objects/date/getyear/index.html | 169 + .../reference/global_objects/date/index.html | 271 ++ .../reference/global_objects/date/now/index.html | 126 + .../reference/global_objects/date/parse/index.html | 214 + .../global_objects/date/setdate/index.html | 80 + .../global_objects/date/setfullyear/index.html | 80 + .../global_objects/date/sethours/index.html | 85 + .../global_objects/date/setmilliseconds/index.html | 74 + .../global_objects/date/setminutes/index.html | 84 + .../global_objects/date/setmonth/index.html | 87 + .../global_objects/date/setseconds/index.html | 82 + .../global_objects/date/settime/index.html | 95 + .../global_objects/date/setutcdate/index.html | 74 + .../global_objects/date/setutcfullyear/index.html | 80 + .../global_objects/date/setutchours/index.html | 82 + .../date/setutcmilliseconds/index.html | 74 + .../global_objects/date/setutcminutes/index.html | 80 + .../global_objects/date/setutcmonth/index.html | 78 + .../global_objects/date/setutcseconds/index.html | 78 + .../global_objects/date/setyear/index.html | 79 + .../global_objects/date/todatestring/index.html | 127 + .../global_objects/date/togmtstring/index.html | 70 + .../global_objects/date/toisostring/index.html | 97 + .../global_objects/date/tojson/index.html | 75 + .../date/tolocaledatestring/index.html | 239 + .../global_objects/date/tolocalestring/index.html | 202 + .../date/tolocaletimestring/index.html | 180 + .../global_objects/date/tosource/index.html | 53 + .../global_objects/date/tostring/index.html | 114 + .../global_objects/date/totimestring/index.html | 72 + .../global_objects/date/toutcstring/index.html | 113 + .../reference/global_objects/date/utc/index.html | 145 + .../global_objects/date/valueof/index.html | 69 + .../reference/global_objects/decodeuri/index.html | 99 + .../global_objects/decodeuricomponent/index.html | 118 + .../reference/global_objects/encodeuri/index.html | 122 + .../global_objects/encodeuricomponent/index.html | 159 + .../reference/global_objects/error/index.html | 229 + .../global_objects/error/tosource/index.html | 58 + .../global_objects/error/tostring/index.html | 100 + .../reference/global_objects/escape/index.html | 127 + .../reference/global_objects/eval/index.html | 255 ++ .../reference/global_objects/evalerror/index.html | 163 + .../global_objects/float32array/index.html | 200 + .../global_objects/float64array/index.html | 160 + .../global_objects/function/apply/index.html | 249 ++ .../global_objects/function/arguments/index.html | 130 + .../global_objects/function/arity/index.html | 78 + .../global_objects/function/bind/index.html | 309 ++ .../global_objects/function/call/index.html | 194 + .../global_objects/function/caller/index.html | 129 + .../global_objects/function/displayname/index.html | 80 + .../reference/global_objects/function/index.html | 234 + .../global_objects/function/isgenerator/index.html | 55 + .../global_objects/function/length/index.html | 134 + .../global_objects/function/name/index.html | 222 + .../global_objects/function/prototype/index.html | 94 + .../global_objects/function/tosource/index.html | 57 + .../global_objects/function/tostring/index.html | 239 + .../reference/global_objects/generator/index.html | 178 + .../reference/global_objects/globalthis/index.html | 80 + .../javascript/reference/global_objects/index.html | 174 + .../reference/global_objects/infinity/index.html | 114 + .../reference/global_objects/int16array/index.html | 208 + .../global_objects/internalerror/index.html | 92 + .../global_objects/intl/datetimeformat/index.html | 188 + .../reference/global_objects/intl/index.html | 168 + .../global_objects/intl/numberformat/index.html | 242 + .../intl/numberformat/prototype/index.html | 125 + .../intl/relativetimeformat/index.html | 171 + .../reference/global_objects/isfinite/index.html | 128 + .../reference/global_objects/isnan/index.html | 109 + .../reference/global_objects/iterador/index.html | 184 + .../reference/global_objects/json/index.html | 241 + .../reference/global_objects/json/parse/index.html | 123 + .../global_objects/json/stringify/index.html | 253 ++ .../reference/global_objects/map/clear/index.html | 119 + .../reference/global_objects/map/delete/index.html | 120 + .../global_objects/map/entries/index.html | 120 + .../global_objects/map/foreach/index.html | 146 + .../reference/global_objects/map/get/index.html | 76 + .../reference/global_objects/map/has/index.html | 78 + .../reference/global_objects/map/index.html | 225 + .../reference/global_objects/map/keys/index.html | 115 + .../global_objects/map/prototype/index.html | 135 + .../reference/global_objects/map/set/index.html | 137 + .../reference/global_objects/map/size/index.html | 110 + .../reference/global_objects/map/values/index.html | 74 + .../reference/global_objects/math/abs/index.html | 142 + .../reference/global_objects/math/acos/index.html | 139 + .../reference/global_objects/math/acosh/index.html | 100 + .../reference/global_objects/math/asin/index.html | 103 + .../reference/global_objects/math/asinh/index.html | 97 + .../reference/global_objects/math/atan/index.html | 104 + .../reference/global_objects/math/atan2/index.html | 150 + .../reference/global_objects/math/atanh/index.html | 99 + .../reference/global_objects/math/cbrt/index.html | 97 + .../reference/global_objects/math/ceil/index.html | 210 + .../reference/global_objects/math/clz32/index.html | 179 + .../reference/global_objects/math/cos/index.html | 102 + .../reference/global_objects/math/cosh/index.html | 88 + .../reference/global_objects/math/e/index.html | 86 + .../reference/global_objects/math/exp/index.html | 109 + .../reference/global_objects/math/expm1/index.html | 80 + .../reference/global_objects/math/floor/index.html | 199 + .../reference/global_objects/math/hypot/index.html | 115 + .../reference/global_objects/math/index.html | 208 + .../reference/global_objects/math/ln10/index.html | 121 + .../reference/global_objects/math/ln2/index.html | 80 + .../reference/global_objects/math/log/index.html | 148 + .../reference/global_objects/math/log10/index.html | 137 + .../global_objects/math/log10e/index.html | 82 + .../reference/global_objects/math/log1p/index.html | 105 + .../reference/global_objects/math/log2/index.html | 91 + .../reference/global_objects/math/log2e/index.html | 82 + .../reference/global_objects/math/max/index.html | 155 + .../reference/global_objects/math/min/index.html | 147 + .../reference/global_objects/math/pi/index.html | 82 + .../reference/global_objects/math/pow/index.html | 147 + .../global_objects/math/random/index.html | 102 + .../reference/global_objects/math/round/index.html | 234 + .../reference/global_objects/math/sign/index.html | 117 + .../reference/global_objects/math/sin/index.html | 92 + .../reference/global_objects/math/sinh/index.html | 96 + .../reference/global_objects/math/sqrt/index.html | 87 + .../global_objects/math/sqrt1_2/index.html | 81 + .../reference/global_objects/math/sqrt2/index.html | 81 + .../reference/global_objects/math/tan/index.html | 111 + .../reference/global_objects/math/tanh/index.html | 88 + .../reference/global_objects/math/trunc/index.html | 144 + .../reference/global_objects/nan/index.html | 125 + .../reference/global_objects/null/index.html | 125 + .../global_objects/number/epsilon/index.html | 69 + .../reference/global_objects/number/index.html | 221 + .../global_objects/number/isfinite/index.html | 86 + .../global_objects/number/isinteger/index.html | 136 + .../global_objects/number/isnan/index.html | 131 + .../global_objects/number/issafeinteger/index.html | 104 + .../number/max_safe_integer/index.html | 83 + .../global_objects/number/max_value/index.html | 65 + .../number/min_safe_integer/index.html | 66 + .../global_objects/number/min_value/index.html | 69 + .../reference/global_objects/number/nan/index.html | 105 + .../number/negative_infinity/index.html | 84 + .../global_objects/number/parsefloat/index.html | 116 + .../global_objects/number/parseint/index.html | 85 + .../number/positive_infinity/index.html | 92 + .../global_objects/number/prototype/index.html | 139 + .../global_objects/number/toexponential/index.html | 149 + .../global_objects/number/tofixed/index.html | 99 + .../number/tolocalestring/index.html | 176 + .../global_objects/number/toprecision/index.html | 104 + .../global_objects/number/tosource/index.html | 48 + .../global_objects/number/tostring/index.html | 143 + .../global_objects/number/valueof/index.html | 80 + .../object/__definegetter__/index.html | 102 + .../object/__definesetter__/index.html | 117 + .../object/__lookupgetter__/index.html | 84 + .../object/__lookupsetter__/index.html | 92 + .../global_objects/object/assign/index.html | 223 + .../global_objects/object/constructor/index.html | 192 + .../global_objects/object/count/index.html | 46 + .../global_objects/object/create/index.html | 260 ++ .../object/defineproperties/index.html | 233 + .../object/defineproperty/index.html | 478 ++ .../global_objects/object/entries/index.html | 110 + .../global_objects/object/freeze/index.html | 205 + .../global_objects/object/fromentries/index.html | 107 + .../object/getownpropertydescriptor/index.html | 127 + .../object/getownpropertydescriptors/index.html | 104 + .../object/getownpropertynames/index.html | 211 + .../object/getownpropertysymbols/index.html | 79 + .../object/getprototypeof/index.html | 124 + .../object/hasownproperty/index.html | 193 + .../reference/global_objects/object/index.html | 180 + .../reference/global_objects/object/is/index.html | 177 + .../global_objects/object/isextensible/index.html | 107 + .../global_objects/object/isfrozen/index.html | 172 + .../global_objects/object/isprototypeof/index.html | 124 + .../global_objects/object/issealed/index.html | 134 + .../global_objects/object/keys/index.html | 190 + .../global_objects/object/observe/index.html | 161 + .../object/preventextensions/index.html | 131 + .../object/propertyisenumerable/index.html | 128 + .../global_objects/object/proto/index.html | 203 + .../global_objects/object/prototype/index.html | 226 + .../global_objects/object/seal/index.html | 173 + .../object/setprototypeof/index.html | 249 ++ .../object/tolocalestring/index.html | 115 + .../global_objects/object/tosource/index.html | 136 + .../global_objects/object/tostring/index.html | 163 + .../global_objects/object/valueof/index.html | 110 + .../global_objects/object/values/index.html | 139 + .../reference/global_objects/parsefloat/index.html | 171 + .../reference/global_objects/parseint/index.html | 224 + .../global_objects/promise/all/index.html | 245 + .../global_objects/promise/allsettled/index.html | 64 + .../global_objects/promise/catch/index.html | 138 + .../global_objects/promise/finally/index.html | 100 + .../reference/global_objects/promise/index.html | 174 + .../global_objects/promise/prototype/index.html | 113 + .../global_objects/promise/race/index.html | 149 + .../global_objects/promise/reject/index.html | 76 + .../global_objects/promise/resolve/index.html | 144 + .../global_objects/promise/then/index.html | 181 + .../reference/global_objects/proxy/index.html | 396 ++ .../global_objects/referenceerror/index.html | 171 + .../global_objects/reflect/apply/index.html | 143 + .../global_objects/reflect/construct/index.html | 151 + .../reflect/defineproperty/index.html | 97 + .../reference/global_objects/reflect/index.html | 166 + .../global_objects/reflect/set/index.html | 146 + .../global_objects/regexp/compile/index.html | 84 + .../global_objects/regexp/exec/index.html | 230 + .../global_objects/regexp/ignorecase/index.html | 70 + .../reference/global_objects/regexp/index.html | 636 +++ .../global_objects/regexp/sticky/index.html | 95 + .../global_objects/regexp/test/index.html | 152 + .../reference/global_objects/set/add/index.html | 131 + .../reference/global_objects/set/clear/index.html | 110 + .../reference/global_objects/set/delete/index.html | 123 + .../global_objects/set/entries/index.html | 109 + .../reference/global_objects/set/has/index.html | 86 + .../reference/global_objects/set/index.html | 259 ++ .../global_objects/set/prototype/index.html | 84 + .../reference/global_objects/set/values/index.html | 72 + .../global_objects/string/@@iterator/index.html | 84 + .../global_objects/string/anchor/index.html | 76 + .../reference/global_objects/string/big/index.html | 76 + .../global_objects/string/blink/index.html | 71 + .../global_objects/string/bold/index.html | 68 + .../global_objects/string/charat/index.html | 290 ++ .../global_objects/string/charcodeat/index.html | 213 + .../global_objects/string/codepointat/index.html | 143 + .../global_objects/string/concat/index.html | 138 + .../global_objects/string/endswith/index.html | 103 + .../global_objects/string/fixed/index.html | 66 + .../global_objects/string/fontcolor/index.html | 84 + .../global_objects/string/fontsize/index.html | 83 + .../global_objects/string/fromcharcode/index.html | 142 + .../global_objects/string/fromcodepoint/index.html | 213 + .../global_objects/string/includes/index.html | 108 + .../reference/global_objects/string/index.html | 338 ++ .../global_objects/string/indexof/index.html | 158 + .../global_objects/string/italics/index.html | 68 + .../global_objects/string/lastindexof/index.html | 162 + .../global_objects/string/length/index.html | 142 + .../global_objects/string/link/index.html | 75 + .../global_objects/string/localecompare/index.html | 163 + .../global_objects/string/match/index.html | 232 + .../global_objects/string/matchall/index.html | 146 + .../global_objects/string/normalize/index.html | 220 + .../global_objects/string/padend/index.html | 103 + .../global_objects/string/padstart/index.html | 107 + .../global_objects/string/prototype/index.html | 176 + .../reference/global_objects/string/raw/index.html | 120 + .../global_objects/string/repeat/index.html | 294 ++ .../global_objects/string/replace/index.html | 352 ++ .../global_objects/string/replaceall/index.html | 178 + .../global_objects/string/search/index.html | 153 + .../global_objects/string/slice/index.html | 233 + .../global_objects/string/small/index.html | 72 + .../global_objects/string/split/index.html | 282 ++ .../global_objects/string/startswith/index.html | 96 + .../global_objects/string/strike/index.html | 68 + .../reference/global_objects/string/sub/index.html | 123 + .../global_objects/string/substr/index.html | 140 + .../global_objects/string/substring/index.html | 229 + .../reference/global_objects/string/sup/index.html | 69 + .../string/tolocalelowercase/index.html | 92 + .../string/tolocaleuppercase/index.html | 95 + .../global_objects/string/tolowercase/index.html | 126 + .../global_objects/string/tosource/index.html | 102 + .../global_objects/string/tostring/index.html | 125 + .../global_objects/string/touppercase/index.html | 135 + .../global_objects/string/trim/index.html | 137 + .../global_objects/string/trimend/index.html | 82 + .../global_objects/string/trimstart/index.html | 118 + .../global_objects/string/valueof/index.html | 84 + .../global_objects/symbol/asynciterator/index.html | 75 + .../global_objects/symbol/description/index.html | 61 + .../global_objects/symbol/hasinstance/index.html | 114 + .../reference/global_objects/symbol/index.html | 301 ++ .../symbol/isconcatspreadable/index.html | 93 + .../global_objects/symbol/iterator/index.html | 107 + .../global_objects/symbol/match/index.html | 65 + .../global_objects/symbol/matchall/index.html | 72 + .../global_objects/symbol/replace/index.html | 60 + .../global_objects/symbol/search/index.html | 60 + .../global_objects/symbol/species/index.html | 63 + .../global_objects/symbol/split/index.html | 60 + .../global_objects/symbol/toprimitive/index.html | 75 + .../global_objects/symbol/tostringtag/index.html | 92 + .../global_objects/symbol/unscopables/index.html | 83 + .../reference/global_objects/typedarray/index.html | 364 ++ .../global_objects/typedarray/sort/index.html | 126 + .../reference/global_objects/typeerror/index.html | 168 + .../reference/global_objects/undefined/index.html | 175 + .../reference/global_objects/unescape/index.html | 136 + .../reference/global_objects/uneval/index.html | 106 + .../global_objects/weakmap/delete/index.html | 73 + .../global_objects/weakmap/get/index.html | 74 + .../global_objects/weakmap/has/index.html | 77 + .../reference/global_objects/weakmap/index.html | 130 + .../global_objects/weakmap/prototype/index.html | 117 + .../global_objects/weakmap/set/index.html | 85 + .../reference/global_objects/weakset/index.html | 199 + files/pt-br/web/javascript/reference/index.html | 64 + .../reference/iteration_protocols/index.html | 339 ++ .../reference/lexical_grammar/index.html | 683 +++ .../operators/arithmetic_operators/index.html | 328 ++ .../operators/array_comprehensions/index.html | 207 + .../reference/operators/async_function/index.html | 152 + .../atribuicao_via_desestruturacao/index.html | 445 ++ .../reference/operators/await/index.html | 152 + .../operators/bitwise_operators/index.html | 558 +++ .../reference/operators/bitwise_xor/index.html | 108 + .../reference/operators/class/index.html | 173 + .../operators/expression_closures/index.html | 72 + .../reference/operators/function/index.html | 113 + .../reference/operators/function_star_/index.html | 167 + .../operators/generator_comprehensions/index.html | 169 + .../reference/operators/grouping/index.html | 114 + .../javascript/reference/operators/in/index.html | 137 + .../web/javascript/reference/operators/index.html | 281 ++ .../operators/inicializador_objeto/index.html | 392 ++ .../reference/operators/instanceof/index.html | 194 + .../reference/operators/new.target/index.html | 98 + .../javascript/reference/operators/new/index.html | 224 + .../operators/operador_condicional/index.html | 171 + .../operador_de_coalescencia_nula/index.html | 159 + .../operators/operador_virgula/index.html | 102 + .../index.html" | 250 ++ .../operators/operadores_logicos/index.html | 342 ++ .../operators/operator_precedence/index.html | 343 ++ .../operators/optional_chaining/index.html | 192 + .../operators/pipeline_operator/index.html | 65 + .../operators/property_accessors/index.html | 189 + .../reference/operators/spread_operator/index.html | 200 + .../reference/operators/spread_syntax/index.html | 228 + .../reference/operators/super/index.html | 226 + .../javascript/reference/operators/this/index.html | 410 ++ .../reference/operators/typeof/index.html | 154 + .../javascript/reference/operators/void/index.html | 141 + .../reference/operators/yield/index.html | 181 + .../reference/operators/yield_star_/index.html | 210 + .../reference/statements/block/index.html | 180 + .../reference/statements/break/index.html | 159 + .../reference/statements/class/index.html | 85 + .../reference/statements/const/index.html | 224 + .../reference/statements/continue/index.html | 206 + .../reference/statements/debugger/index.html | 71 + .../reference/statements/default/index.html | 186 + .../reference/statements/do...while/index.html | 138 + .../reference/statements/empty/index.html | 80 + .../reference/statements/export/index.html | 223 + .../reference/statements/for-await...of/index.html | 136 + .../reference/statements/for...in/index.html | 203 + .../reference/statements/for...of/index.html | 298 ++ .../javascript/reference/statements/for/index.html | 191 + .../reference/statements/for_each...in/index.html | 126 + .../statements/funcoes_assincronas/index.html | 149 + .../reference/statements/function/index.html | 176 + .../reference/statements/function_star_/index.html | 203 + .../reference/statements/if...else/index.html | 211 + .../reference/statements/import.meta/index.html | 93 + .../reference/statements/import/index.html | 286 ++ .../web/javascript/reference/statements/index.html | 128 + .../reference/statements/label/index.html | 101 + .../javascript/reference/statements/let/index.html | 140 + .../reference/statements/return/index.html | 197 + .../reference/statements/switch/index.html | 288 ++ .../reference/statements/throw/index.html | 237 + .../reference/statements/try...catch/index.html | 249 ++ .../javascript/reference/statements/var/index.html | 238 + .../reference/statements/while/index.html | 142 + .../reference/statements/with/index.html | 183 + .../javascript/reference/strict_mode/index.html | 355 ++ .../reference/template_strings/index.html | 140 + .../suporte_ao_ecmascript_6_na_mozilla/index.html | 264 ++ files/pt-br/web/javascript/typed_arrays/index.html | 226 + files/pt-br/web/manifest/index.html | 445 ++ files/pt-br/web/mathml/element/index.html | 144 + files/pt-br/web/mathml/element/math/index.html | 299 ++ files/pt-br/web/mathml/exemplos/index.html | 20 + files/pt-br/web/mathml/index.html | 122 + .../caminho_de_renderizacao_critico/index.html | 60 + files/pt-br/web/performance/index.html | 291 ++ files/pt-br/web/progressive_web_apps/index.html | 80 + .../introdu\303\247\303\243o/index.html" | 90 + files/pt-br/web/reference/api/index.html | 61 + files/pt-br/web/reference/index.html | 29 + .../index.html" | 42 + .../index.html" | 32 + .../seguranca_tcp_ip/index.html" | 50 + files/pt-br/web/security/index.html | 13 + .../web/security/securing_your_site/index.html | 51 + .../turning_off_form_autocompletion/index.html | 58 + .../index.html | 213 + files/pt-br/web/svg/attribute/class/index.html | 195 + .../web/svg/attribute/contentstyletype/index.html | 46 + files/pt-br/web/svg/attribute/fill/index.html | 461 ++ files/pt-br/web/svg/attribute/index.html | 462 ++ files/pt-br/web/svg/attribute/keytimes/index.html | 95 + .../svg/attribute/preserveaspectratio/index.html | 420 ++ .../web/svg/attribute/stroke-dashoffset/index.html | 52 + files/pt-br/web/svg/attribute/stroke/index.html | 93 + files/pt-br/web/svg/attribute/style/index.html | 75 + files/pt-br/web/svg/attribute/version/index.html | 58 + files/pt-br/web/svg/attribute/viewbox/index.html | 200 + files/pt-br/web/svg/attribute/width/index.html | 68 + .../pt-br/web/svg/compatibility_sources/index.html | 19 + files/pt-br/web/svg/content_type/index.html | 378 ++ files/pt-br/web/svg/element/a/index.html | 146 + files/pt-br/web/svg/element/altglyph/index.html | 113 + files/pt-br/web/svg/element/altglyphdef/index.html | 42 + .../pt-br/web/svg/element/altglyphitem/index.html | 43 + files/pt-br/web/svg/element/animate/index.html | 102 + .../pt-br/web/svg/element/animatecolor/index.html | 59 + .../pt-br/web/svg/element/animatemotion/index.html | 56 + .../web/svg/element/animatetransform/index.html | 67 + files/pt-br/web/svg/element/circle/index.html | 118 + .../pt-br/web/svg/element/color-profile/index.html | 95 + files/pt-br/web/svg/element/defs/index.html | 116 + files/pt-br/web/svg/element/desc/index.html | 94 + files/pt-br/web/svg/element/ellipse/index.html | 110 + files/pt-br/web/svg/element/filter/index.html | 124 + files/pt-br/web/svg/element/g/index.html | 61 + files/pt-br/web/svg/element/glyph/index.html | 87 + files/pt-br/web/svg/element/glyphref/index.html | 103 + files/pt-br/web/svg/element/hkern/index.html | 48 + files/pt-br/web/svg/element/image/index.html | 102 + files/pt-br/web/svg/element/index.html | 289 ++ files/pt-br/web/svg/element/line/index.html | 118 + .../web/svg/element/lineargradient/index.html | 113 + files/pt-br/web/svg/element/marker/index.html | 103 + files/pt-br/web/svg/element/mask/index.html | 55 + files/pt-br/web/svg/element/metadata/index.html | 87 + .../pt-br/web/svg/element/missing-glyph/index.html | 51 + files/pt-br/web/svg/element/mpath/index.html | 78 + files/pt-br/web/svg/element/path/index.html | 129 + files/pt-br/web/svg/element/pattern/index.html | 53 + files/pt-br/web/svg/element/polygon/index.html | 105 + files/pt-br/web/svg/element/polyline/index.html | 105 + .../web/svg/element/radialgradient/index.html | 114 + files/pt-br/web/svg/element/rect/index.html | 117 + files/pt-br/web/svg/element/script/index.html | 129 + files/pt-br/web/svg/element/set/index.html | 48 + files/pt-br/web/svg/element/stop/index.html | 124 + files/pt-br/web/svg/element/style/index.html | 117 + files/pt-br/web/svg/element/svg/index.html | 125 + files/pt-br/web/svg/element/switch/index.html | 99 + files/pt-br/web/svg/element/symbol/index.html | 121 + files/pt-br/web/svg/element/text/index.html | 122 + files/pt-br/web/svg/element/textpath/index.html | 76 + files/pt-br/web/svg/element/title/index.html | 123 + files/pt-br/web/svg/element/tref/index.html | 123 + files/pt-br/web/svg/element/tspan/index.html | 112 + files/pt-br/web/svg/element/use/index.html | 156 + files/pt-br/web/svg/element/view/index.html | 107 + files/pt-br/web/svg/element/vkern/index.html | 50 + files/pt-br/web/svg/index.html | 111 + .../web/svg/intensivo_de_namespaces/index.html | 186 + files/pt-br/web/svg/tutorial/index.html | 49 + .../pt-br/web/svg/tutorial/introduction/index.html | 39 + files/pt-br/web/tutoriais/index.html | 253 ++ files/pt-br/web/web_components/index.html | 223 + .../usando_custom_elements/index.html | 289 ++ files/pt-br/web/xslt/index.html | 58 + 1789 files changed, 277481 insertions(+) create mode 100644 files/pt-br/web/accessibility/aria/aria_guides/index.html create mode 100644 files/pt-br/web/accessibility/aria/aria_techniques/index.html create mode 100644 files/pt-br/web/accessibility/aria/aria_techniques/usando_o_atributo_aria-labelledby/index.html create mode 100644 files/pt-br/web/accessibility/aria/aria_techniques/usando_o_atributo_aria-required/index.html create mode 100644 files/pt-br/web/accessibility/aria/aria_techniques/usando_o_slider_role/index.html create mode 100644 files/pt-br/web/accessibility/aria/aria_techniques/using_the_aria-describedby_attribute/index.html create mode 100644 files/pt-br/web/accessibility/aria/aria_techniques/using_the_aria-label_attribute/index.html create mode 100644 files/pt-br/web/accessibility/aria/aria_techniques/utilizando_o_alert_role/index.html create mode 100644 files/pt-br/web/accessibility/aria/aria_test_cases/index.html create mode 100644 files/pt-br/web/accessibility/aria/forms/alerts/index.html create mode 100644 "files/pt-br/web/accessibility/aria/forms/dicas_b\303\241sicas_de_form/index.html" create mode 100644 files/pt-br/web/accessibility/aria/forms/index.html create mode 100644 files/pt-br/web/accessibility/aria/forms/multipart_labels/index.html create mode 100644 files/pt-br/web/accessibility/aria/guia_para_implementar_o_leitor_de_tela_aria/index.html create mode 100644 files/pt-br/web/accessibility/aria/index.html create mode 100644 files/pt-br/web/accessibility/aria/roles/index.html create mode 100644 files/pt-br/web/accessibility/aria/web_applications_and_aria_faq/index.html create mode 100644 files/pt-br/web/accessibility/aria/widgets/index.html create mode 100644 "files/pt-br/web/accessibility/aria/widgets/vis\303\243o_geral/index.html" create mode 100644 files/pt-br/web/accessibility/at-apis/gecko/index.html create mode 100644 files/pt-br/web/accessibility/at-apis/gecko/roles/index.html create mode 100644 files/pt-br/web/accessibility/at-apis/index.html create mode 100644 files/pt-br/web/accessibility/xforms/index.html create mode 100644 files/pt-br/web/accessibility/xforms/upload/index.html create mode 100644 files/pt-br/web/acessibilidade/accessibilidade_para_plataforma_movel/index.html create mode 100644 files/pt-br/web/acessibilidade/an_overview_of_accessible_web_applications_and_widgets/index.html create mode 100644 files/pt-br/web/acessibilidade/desenvolvimento_web/index.html create mode 100644 files/pt-br/web/acessibilidade/entendendo_wcag/index.html create mode 100644 files/pt-br/web/acessibilidade/entendendo_wcag/keyboard/index.html create mode 100644 files/pt-br/web/acessibilidade/index.html create mode 100644 files/pt-br/web/acessibilidade/problemas_com_jaws_no_firefox/index.html create mode 100644 files/pt-br/web/api/abortsignal/aborted/index.html create mode 100644 files/pt-br/web/api/abortsignal/index.html create mode 100644 files/pt-br/web/api/abstractworker/index.html create mode 100644 files/pt-br/web/api/abstractworker/onerror/index.html create mode 100644 files/pt-br/web/api/ambient_light_events/index.html create mode 100644 files/pt-br/web/api/angle_instanced_arrays/index.html create mode 100644 files/pt-br/web/api/animation/cancel/index.html create mode 100644 files/pt-br/web/api/animation/currenttime/index.html create mode 100644 files/pt-br/web/api/animation/index.html create mode 100644 files/pt-br/web/api/animation/playstate/index.html create mode 100644 files/pt-br/web/api/animationevent/animationevent/index.html create mode 100644 files/pt-br/web/api/animationevent/animationname/index.html create mode 100644 files/pt-br/web/api/animationevent/elapsedtime/index.html create mode 100644 files/pt-br/web/api/animationevent/index.html create mode 100644 files/pt-br/web/api/animationevent/initanimationevent/index.html create mode 100644 files/pt-br/web/api/animationevent/pseudoelement/index.html create mode 100644 files/pt-br/web/api/api_de_desempenho/index.html create mode 100644 files/pt-br/web/api/api_push/best_practices/index.html create mode 100644 files/pt-br/web/api/api_push/index.html create mode 100644 files/pt-br/web/api/api_web_audio/index.html create mode 100644 files/pt-br/web/api/api_web_audio/sintetizador_simples/index.html create mode 100644 files/pt-br/web/api/attr/index.html create mode 100644 files/pt-br/web/api/attr/localname/index.html create mode 100644 files/pt-br/web/api/audiocontext/currenttime/index.html create mode 100644 files/pt-br/web/api/audiocontext/index.html create mode 100644 files/pt-br/web/api/audionode/index.html create mode 100644 files/pt-br/web/api/background_tasks_api/index.html create mode 100644 files/pt-br/web/api/batterymanager/charging/index.html create mode 100644 files/pt-br/web/api/batterymanager/chargingtime/index.html create mode 100644 files/pt-br/web/api/batterymanager/dischargingtime/index.html create mode 100644 files/pt-br/web/api/batterymanager/index.html create mode 100644 files/pt-br/web/api/batterymanager/level/index.html create mode 100644 files/pt-br/web/api/batterymanager/onchargingchange/index.html create mode 100644 files/pt-br/web/api/batterymanager/onchargingtimechange/index.html create mode 100644 files/pt-br/web/api/batterymanager/ondischargintimechange/index.html create mode 100644 files/pt-br/web/api/batterymanager/onlevelchange/index.html create mode 100644 files/pt-br/web/api/biquadfilternode/index.html create mode 100644 files/pt-br/web/api/blob/blob/index.html create mode 100644 files/pt-br/web/api/blob/index.html create mode 100644 files/pt-br/web/api/blob/size/index.html create mode 100644 files/pt-br/web/api/blob/slice/index.html create mode 100644 files/pt-br/web/api/blob/type/index.html create mode 100644 files/pt-br/web/api/body/index.html create mode 100644 files/pt-br/web/api/body/json/index.html create mode 100644 files/pt-br/web/api/broadcastchannel/index.html create mode 100644 files/pt-br/web/api/cache/index.html create mode 100644 files/pt-br/web/api/cameracontrol/autofocus/index.html create mode 100644 files/pt-br/web/api/cameracontrol/index.html create mode 100644 files/pt-br/web/api/canvasrenderingcontext2d/arc/index.html create mode 100644 files/pt-br/web/api/canvasrenderingcontext2d/arcto/index.html create mode 100644 files/pt-br/web/api/canvasrenderingcontext2d/beginpath/index.html create mode 100644 files/pt-br/web/api/canvasrenderingcontext2d/clearrect/index.html create mode 100644 files/pt-br/web/api/canvasrenderingcontext2d/clip/index.html create mode 100644 files/pt-br/web/api/canvasrenderingcontext2d/closepath/index.html create mode 100644 files/pt-br/web/api/canvasrenderingcontext2d/fill/index.html create mode 100644 files/pt-br/web/api/canvasrenderingcontext2d/fillrect/index.html create mode 100644 files/pt-br/web/api/canvasrenderingcontext2d/fillstyle/index.html create mode 100644 files/pt-br/web/api/canvasrenderingcontext2d/index.html create mode 100644 files/pt-br/web/api/canvasrenderingcontext2d/lineto/index.html create mode 100644 files/pt-br/web/api/canvasrenderingcontext2d/moveto/index.html create mode 100644 files/pt-br/web/api/canvasrenderingcontext2d/quadraticcurveto/index.html create mode 100644 files/pt-br/web/api/canvasrenderingcontext2d/rect/index.html create mode 100644 files/pt-br/web/api/canvasrenderingcontext2d/stroke/index.html create mode 100644 files/pt-br/web/api/canvasrenderingcontext2d/strokerect/index.html create mode 100644 files/pt-br/web/api/characterdata/index.html create mode 100644 files/pt-br/web/api/childnode/after/index.html create mode 100644 files/pt-br/web/api/childnode/index.html create mode 100644 files/pt-br/web/api/childnode/remove/index.html create mode 100644 files/pt-br/web/api/clipboardevent/index.html create mode 100644 files/pt-br/web/api/closeevent/closeevent/index.html create mode 100644 files/pt-br/web/api/closeevent/index.html create mode 100644 files/pt-br/web/api/console/assert/index.html create mode 100644 files/pt-br/web/api/console/clear/index.html create mode 100644 files/pt-br/web/api/console/count/index.html create mode 100644 files/pt-br/web/api/console/dir/index.html create mode 100644 files/pt-br/web/api/console/error/index.html create mode 100644 files/pt-br/web/api/console/index.html create mode 100644 files/pt-br/web/api/console/info/index.html create mode 100644 files/pt-br/web/api/console/log/index.html create mode 100644 files/pt-br/web/api/console/table/index.html create mode 100644 files/pt-br/web/api/console/time/index.html create mode 100644 files/pt-br/web/api/console/timeend/index.html create mode 100644 files/pt-br/web/api/console/timestamp/index.html create mode 100644 files/pt-br/web/api/console/warn/index.html create mode 100644 files/pt-br/web/api/console_api/index.html create mode 100644 files/pt-br/web/api/crypto/index.html create mode 100644 files/pt-br/web/api/crypto/subtle/index.html create mode 100644 files/pt-br/web/api/cryptokey/algorithm/index.html create mode 100644 files/pt-br/web/api/cryptokey/extractable/index.html create mode 100644 files/pt-br/web/api/cryptokey/index.html create mode 100644 files/pt-br/web/api/cryptokey/type/index.html create mode 100644 files/pt-br/web/api/cryptokey/usages/index.html create mode 100644 files/pt-br/web/api/css/index.html create mode 100644 files/pt-br/web/api/css_object_model/index.html create mode 100644 files/pt-br/web/api/customelementregistry/index.html create mode 100644 files/pt-br/web/api/datatransfer/index.html create mode 100644 files/pt-br/web/api/deviceacceleration/index.html create mode 100644 files/pt-br/web/api/devicerotationrate/index.html create mode 100644 files/pt-br/web/api/devicestorage.get/index.html create mode 100644 files/pt-br/web/api/devicestorage.onchange/index.html create mode 100644 files/pt-br/web/api/document/activeelement/index.html create mode 100644 files/pt-br/web/api/document/alinkcolor/index.html create mode 100644 files/pt-br/web/api/document/anchors/index.html create mode 100644 files/pt-br/web/api/document/bgcolor/index.html create mode 100644 files/pt-br/web/api/document/body/index.html create mode 100644 files/pt-br/web/api/document/characterset/index.html create mode 100644 files/pt-br/web/api/document/close/index.html create mode 100644 files/pt-br/web/api/document/compatmode/index.html create mode 100644 files/pt-br/web/api/document/contenttype/index.html create mode 100644 files/pt-br/web/api/document/createelement/index.html create mode 100644 files/pt-br/web/api/document/createelementns/index.html create mode 100644 files/pt-br/web/api/document/currentscript/index.html create mode 100644 files/pt-br/web/api/document/defaultview/index.html create mode 100644 files/pt-br/web/api/document/designmode/index.html create mode 100644 files/pt-br/web/api/document/doctype/index.html create mode 100644 files/pt-br/web/api/document/document/index.html create mode 100644 files/pt-br/web/api/document/documentelement/index.html create mode 100644 files/pt-br/web/api/document/documenturi/index.html create mode 100644 files/pt-br/web/api/document/elementfrompoint/index.html create mode 100644 files/pt-br/web/api/document/elementoregistrado/index.html create mode 100644 files/pt-br/web/api/document/execcommand/index.html create mode 100644 files/pt-br/web/api/document/fullscreen/index.html create mode 100644 files/pt-br/web/api/document/getelementbyid/index.html create mode 100644 files/pt-br/web/api/document/getelementsbyclassname/index.html create mode 100644 files/pt-br/web/api/document/getelementsbyname/index.html create mode 100644 files/pt-br/web/api/document/getelementsbytagname/index.html create mode 100644 files/pt-br/web/api/document/getselection/index.html create mode 100644 files/pt-br/web/api/document/hasfocus/index.html create mode 100644 files/pt-br/web/api/document/head/index.html create mode 100644 files/pt-br/web/api/document/height/index.html create mode 100644 files/pt-br/web/api/document/images/index.html create mode 100644 files/pt-br/web/api/document/implementation/index.html create mode 100644 files/pt-br/web/api/document/importnode/index.html create mode 100644 files/pt-br/web/api/document/index.html create mode 100644 files/pt-br/web/api/document/keydown_event/index.html create mode 100644 files/pt-br/web/api/document/keypress_event/index.html create mode 100644 files/pt-br/web/api/document/keyup_event/index.html create mode 100644 files/pt-br/web/api/document/location/index.html create mode 100644 files/pt-br/web/api/document/origin/index.html create mode 100644 files/pt-br/web/api/document/queryselector/index.html create mode 100644 files/pt-br/web/api/document/queryselectorall/index.html create mode 100644 files/pt-br/web/api/document/readystate/index.html create mode 100644 files/pt-br/web/api/document/referrer/index.html create mode 100644 files/pt-br/web/api/document/scripts/index.html create mode 100644 files/pt-br/web/api/document/url/index.html create mode 100644 files/pt-br/web/api/document/write/index.html create mode 100644 files/pt-br/web/api/document/writeln/index.html create mode 100644 files/pt-br/web/api/documentfragment/index.html create mode 100644 files/pt-br/web/api/domexception/index.html create mode 100644 files/pt-br/web/api/domimplementation/createdocument/index.html create mode 100644 files/pt-br/web/api/domimplementation/index.html create mode 100644 files/pt-br/web/api/domstring/index.html create mode 100644 files/pt-br/web/api/domstringlist/index.html create mode 100644 files/pt-br/web/api/domstringmap/index.html create mode 100644 files/pt-br/web/api/element/accesskey/index.html create mode 100644 files/pt-br/web/api/element/addeventlistener/index.html create mode 100644 files/pt-br/web/api/element/animate/index.html create mode 100644 files/pt-br/web/api/element/attributes/index.html create mode 100644 files/pt-br/web/api/element/classlist/index.html create mode 100644 files/pt-br/web/api/element/classname/index.html create mode 100644 files/pt-br/web/api/element/click_event/index.html create mode 100644 files/pt-br/web/api/element/closest/index.html create mode 100644 files/pt-br/web/api/element/getattribute/index.html create mode 100644 files/pt-br/web/api/element/getboundingclientrect/index.html create mode 100644 files/pt-br/web/api/element/getelementsbyclassname/index.html create mode 100644 files/pt-br/web/api/element/id/index.html create mode 100644 files/pt-br/web/api/element/index.html create mode 100644 files/pt-br/web/api/element/innerhtml/index.html create mode 100644 files/pt-br/web/api/element/insertadjacenthtml/index.html create mode 100644 files/pt-br/web/api/element/matches/index.html create mode 100644 files/pt-br/web/api/element/mousedown_event/index.html create mode 100644 files/pt-br/web/api/element/mouseenter_event/index.html create mode 100644 files/pt-br/web/api/element/mouseover_event/index.html create mode 100644 files/pt-br/web/api/element/name/index.html create mode 100644 files/pt-br/web/api/element/outerhtml/index.html create mode 100644 files/pt-br/web/api/element/queryselector/index.html create mode 100644 files/pt-br/web/api/element/queryselectorall/index.html create mode 100644 files/pt-br/web/api/element/removeattribute/index.html create mode 100644 files/pt-br/web/api/element/scrollintoview/index.html create mode 100644 files/pt-br/web/api/element/scrollleft/index.html create mode 100644 files/pt-br/web/api/element/scrolltop/index.html create mode 100644 files/pt-br/web/api/element/scrollwidth/index.html create mode 100644 files/pt-br/web/api/element/setattribute/index.html create mode 100644 files/pt-br/web/api/element/setattributens/index.html create mode 100644 files/pt-br/web/api/element/tagname/index.html create mode 100644 files/pt-br/web/api/element/touchstart_event/index.html create mode 100644 files/pt-br/web/api/encoding_api/index.html create mode 100644 files/pt-br/web/api/event/comparativo_entre_event_targets/index.html create mode 100644 files/pt-br/web/api/event/currenttarget/index.html create mode 100644 files/pt-br/web/api/event/defaultprevented/index.html create mode 100644 files/pt-br/web/api/event/event/index.html create mode 100644 files/pt-br/web/api/event/index.html create mode 100644 files/pt-br/web/api/event/initevent/index.html create mode 100644 files/pt-br/web/api/event/istrusted/index.html create mode 100644 files/pt-br/web/api/event/preventdefault/index.html create mode 100644 files/pt-br/web/api/event/srcelement/index.html create mode 100644 files/pt-br/web/api/event/stopimmediatepropagation/index.html create mode 100644 files/pt-br/web/api/event/stoppropagation/index.html create mode 100644 files/pt-br/web/api/event/target/index.html create mode 100644 files/pt-br/web/api/event/type/index.html create mode 100644 files/pt-br/web/api/eventlistener/index.html create mode 100644 files/pt-br/web/api/eventsource/eventsource/index.html create mode 100644 files/pt-br/web/api/eventsource/index.html create mode 100644 files/pt-br/web/api/eventsource/onerror/index.html create mode 100644 files/pt-br/web/api/eventtarget/dispatchevent/index.html create mode 100644 files/pt-br/web/api/eventtarget/eventtarget/index.html create mode 100644 files/pt-br/web/api/eventtarget/index.html create mode 100644 files/pt-br/web/api/eventtarget/removeeventlistener/index.html create mode 100644 files/pt-br/web/api/fetch_api/basic_concepts/index.html create mode 100644 files/pt-br/web/api/fetch_api/index.html create mode 100644 files/pt-br/web/api/fetch_api/using_fetch/index.html create mode 100644 files/pt-br/web/api/fetch_api/uso_de_busca_cross-global/index.html create mode 100644 files/pt-br/web/api/file/index.html create mode 100644 files/pt-br/web/api/file/using_files_from_web_applications/index.html create mode 100644 files/pt-br/web/api/filelist/index.html create mode 100644 files/pt-br/web/api/filereader/filereader/index.html create mode 100644 files/pt-br/web/api/filereader/index.html create mode 100644 files/pt-br/web/api/filereader/onload/index.html create mode 100644 files/pt-br/web/api/filereader/readasarraybuffer/index.html create mode 100644 files/pt-br/web/api/filereader/readasbinarystring/index.html create mode 100644 files/pt-br/web/api/filereader/readasdataurl/index.html create mode 100644 files/pt-br/web/api/filereader/readastext/index.html create mode 100644 files/pt-br/web/api/formdata/append/index.html create mode 100644 files/pt-br/web/api/formdata/delete/index.html create mode 100644 files/pt-br/web/api/formdata/entries/index.html create mode 100644 files/pt-br/web/api/formdata/formdata/index.html create mode 100644 files/pt-br/web/api/formdata/get/index.html create mode 100644 files/pt-br/web/api/formdata/getall/index.html create mode 100644 files/pt-br/web/api/formdata/has/index.html create mode 100644 files/pt-br/web/api/formdata/index.html create mode 100644 files/pt-br/web/api/formdata/set/index.html create mode 100644 files/pt-br/web/api/fullscreenoptions/index.html create mode 100644 files/pt-br/web/api/gamepad_api/index.html create mode 100644 files/pt-br/web/api/geolocation/clearwatch/index.html create mode 100644 files/pt-br/web/api/geolocation/getcurrentposition/index.html create mode 100644 files/pt-br/web/api/geolocation/index.html create mode 100644 files/pt-br/web/api/geolocation/watchposition/index.html create mode 100644 files/pt-br/web/api/geolocationcoordinates/altitude/index.html create mode 100644 files/pt-br/web/api/geolocationcoordinates/index.html create mode 100644 files/pt-br/web/api/geolocationposition/coords/index.html create mode 100644 files/pt-br/web/api/geolocationposition/index.html create mode 100644 files/pt-br/web/api/geolocationpositionerror/index.html create mode 100644 files/pt-br/web/api/globaleventhandlers/index.html create mode 100644 files/pt-br/web/api/globaleventhandlers/onabort/index.html create mode 100644 files/pt-br/web/api/globaleventhandlers/onblur/index.html create mode 100644 files/pt-br/web/api/globaleventhandlers/onchange/index.html create mode 100644 files/pt-br/web/api/globaleventhandlers/onclick/index.html create mode 100644 files/pt-br/web/api/globaleventhandlers/oncontextmenu/index.html create mode 100644 files/pt-br/web/api/globaleventhandlers/onerror/index.html create mode 100644 files/pt-br/web/api/globaleventhandlers/onfocus/index.html create mode 100644 files/pt-br/web/api/globaleventhandlers/onkeyup/index.html create mode 100644 files/pt-br/web/api/globaleventhandlers/onload/index.html create mode 100644 files/pt-br/web/api/globaleventhandlers/onlostpointercapture/index.html create mode 100644 files/pt-br/web/api/globaleventhandlers/onscroll/index.html create mode 100644 files/pt-br/web/api/history/index.html create mode 100644 files/pt-br/web/api/history_api/exemplo/index.html create mode 100644 files/pt-br/web/api/history_api/index.html create mode 100644 files/pt-br/web/api/htmlcanvaselement/getcontext/index.html create mode 100644 files/pt-br/web/api/htmlcanvaselement/height/index.html create mode 100644 files/pt-br/web/api/htmlcanvaselement/index.html create mode 100644 files/pt-br/web/api/htmlcanvaselement/todataurl/index.html create mode 100644 files/pt-br/web/api/htmlcollection/index.html create mode 100644 files/pt-br/web/api/htmlcontentelement/getdistributednodes/index.html create mode 100644 files/pt-br/web/api/htmlcontentelement/index.html create mode 100644 files/pt-br/web/api/htmlcontentelement/seletor/index.html create mode 100644 files/pt-br/web/api/htmldivelement/index.html create mode 100644 files/pt-br/web/api/htmlelement/blur/index.html create mode 100644 files/pt-br/web/api/htmlelement/click/index.html create mode 100644 files/pt-br/web/api/htmlelement/contenteditable/index.html create mode 100644 files/pt-br/web/api/htmlelement/contextmenu/index.html create mode 100644 files/pt-br/web/api/htmlelement/dataset/index.html create mode 100644 files/pt-br/web/api/htmlelement/focus/index.html create mode 100644 files/pt-br/web/api/htmlelement/index.html create mode 100644 files/pt-br/web/api/htmlelement/lang/index.html create mode 100644 files/pt-br/web/api/htmlelement/offsetheight/index.html create mode 100644 files/pt-br/web/api/htmlelement/offsetleft/index.html create mode 100644 files/pt-br/web/api/htmlelement/offsetparent/index.html create mode 100644 files/pt-br/web/api/htmlelement/offsettop/index.html create mode 100644 files/pt-br/web/api/htmlelement/offsetwidth/index.html create mode 100644 files/pt-br/web/api/htmlinputelement/index.html create mode 100644 files/pt-br/web/api/htmlinputelement/select/index.html create mode 100644 files/pt-br/web/api/htmlinputelement/setselectionrange/index.html create mode 100644 files/pt-br/web/api/htmloptionelement/index.html create mode 100644 files/pt-br/web/api/htmloptionelement/option/index.html create mode 100644 files/pt-br/web/api/htmlselectelement/checkvalidity/index.html create mode 100644 files/pt-br/web/api/htmlselectelement/index.html create mode 100644 files/pt-br/web/api/htmlshadowelement/index.html create mode 100644 files/pt-br/web/api/htmlspanelement/index.html create mode 100644 files/pt-br/web/api/idbcursor/index.html create mode 100644 files/pt-br/web/api/idbfactory/index.html create mode 100644 files/pt-br/web/api/imagecapture/index.html create mode 100644 files/pt-br/web/api/index.html create mode 100644 files/pt-br/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html create mode 100644 files/pt-br/web/api/indexeddb_api/index.html create mode 100644 files/pt-br/web/api/indexeddb_api/usando_indexeddb/index.html create mode 100644 files/pt-br/web/api/keyboardevent/index.html create mode 100644 files/pt-br/web/api/location/assign/index.html create mode 100644 files/pt-br/web/api/location/index.html create mode 100644 files/pt-br/web/api/location/reload/index.html create mode 100644 files/pt-br/web/api/location/search/index.html create mode 100644 files/pt-br/web/api/mediadevices/index.html create mode 100644 files/pt-br/web/api/mediastreamtrack/index.html create mode 100644 files/pt-br/web/api/messagechannel/index.html create mode 100644 files/pt-br/web/api/messageport/index.html create mode 100644 files/pt-br/web/api/messageport/postmessage/index.html create mode 100644 files/pt-br/web/api/mouseevent/clientx/index.html create mode 100644 files/pt-br/web/api/mouseevent/clienty/index.html create mode 100644 files/pt-br/web/api/mouseevent/index.html create mode 100644 files/pt-br/web/api/mutationobserver/index.html create mode 100644 files/pt-br/web/api/navigation_timing_api/index.html create mode 100644 files/pt-br/web/api/navigator/battery/index.html create mode 100644 files/pt-br/web/api/navigator/cookieenabled/index.html create mode 100644 files/pt-br/web/api/navigator/devicememory/index.html create mode 100644 files/pt-br/web/api/navigator/geolocation/index.html create mode 100644 files/pt-br/web/api/navigator/getusermedia/index.html create mode 100644 files/pt-br/web/api/navigator/index.html create mode 100644 files/pt-br/web/api/navigator/share/index.html create mode 100644 files/pt-br/web/api/navigatorid/index.html create mode 100644 files/pt-br/web/api/navigatorid/platform/index.html create mode 100644 files/pt-br/web/api/navigatorid/useragent/index.html create mode 100644 files/pt-br/web/api/navigatorlanguage/index.html create mode 100644 files/pt-br/web/api/navigatorlanguage/language/index.html create mode 100644 files/pt-br/web/api/navigatoronline/index.html create mode 100644 files/pt-br/web/api/navigatoronline/online/index.html create mode 100644 files/pt-br/web/api/navigatoronline/online_and_offline_events/index.html create mode 100644 files/pt-br/web/api/navigatorplugins/index.html create mode 100644 files/pt-br/web/api/navigatorplugins/javaenabled/index.html create mode 100644 files/pt-br/web/api/node/appendchild/index.html create mode 100644 files/pt-br/web/api/node/baseuri/index.html create mode 100644 files/pt-br/web/api/node/childnodes/index.html create mode 100644 files/pt-br/web/api/node/clonenode/index.html create mode 100644 files/pt-br/web/api/node/contains/index.html create mode 100644 "files/pt-br/web/api/node/entendendo_o_uso_do_m\303\251todo_appendchild-javascript/index.html" create mode 100644 files/pt-br/web/api/node/firstchild/index.html create mode 100644 files/pt-br/web/api/node/index.html create mode 100644 files/pt-br/web/api/node/innertext/index.html create mode 100644 files/pt-br/web/api/node/insertbefore/index.html create mode 100644 files/pt-br/web/api/node/isconnected/index.html create mode 100644 files/pt-br/web/api/node/lastchild/index.html create mode 100644 files/pt-br/web/api/node/nextsibling/index.html create mode 100644 files/pt-br/web/api/node/parentnode/index.html create mode 100644 files/pt-br/web/api/node/previoussibling/index.html create mode 100644 files/pt-br/web/api/node/removechild/index.html create mode 100644 files/pt-br/web/api/node/replacechild/index.html create mode 100644 files/pt-br/web/api/node/textcontent/index.html create mode 100644 files/pt-br/web/api/nodefilter/index.html create mode 100644 files/pt-br/web/api/nodelist/index.html create mode 100644 files/pt-br/web/api/notificacoes/index.html create mode 100644 files/pt-br/web/api/notificationaction/index.html create mode 100644 files/pt-br/web/api/offlineaudiocontext/index.html create mode 100644 files/pt-br/web/api/page_visibility_api/index.html create mode 100644 files/pt-br/web/api/parentnode/childelementcount/index.html create mode 100644 files/pt-br/web/api/parentnode/children/index.html create mode 100644 files/pt-br/web/api/parentnode/index.html create mode 100644 files/pt-br/web/api/parentnode/queryselector/index.html create mode 100644 files/pt-br/web/api/path2d/index.html create mode 100644 files/pt-br/web/api/performance/index.html create mode 100644 files/pt-br/web/api/performance/now/index.html create mode 100644 files/pt-br/web/api/performance/tojson/index.html create mode 100644 files/pt-br/web/api/positionoptions/index.html create mode 100644 files/pt-br/web/api/processinginstruction/index.html create mode 100644 files/pt-br/web/api/pushmanager/index.html create mode 100644 files/pt-br/web/api/randomsource/getrandomvalues/index.html create mode 100644 files/pt-br/web/api/randomsource/index.html create mode 100644 files/pt-br/web/api/request/index.html create mode 100644 files/pt-br/web/api/request/request/index.html create mode 100644 files/pt-br/web/api/response/index.html create mode 100644 files/pt-br/web/api/rtccertificate/index.html create mode 100644 files/pt-br/web/api/rtcdatachannel/index.html create mode 100644 files/pt-br/web/api/rtcicetransport/index.html create mode 100644 files/pt-br/web/api/rtcpeerconnection/connectionstate/index.html create mode 100644 files/pt-br/web/api/rtcpeerconnection/index.html create mode 100644 "files/pt-br/web/api/sele\303\247\303\243o/index.html" create mode 100644 files/pt-br/web/api/sensor/index.html create mode 100644 files/pt-br/web/api/server-sent_events/index.html create mode 100644 files/pt-br/web/api/server-sent_events/using_server-sent_events/index.html create mode 100644 files/pt-br/web/api/service_worker_api/index.html create mode 100644 files/pt-br/web/api/service_worker_api/using_service_workers/index.html create mode 100644 files/pt-br/web/api/serviceworkercontainer/index.html create mode 100644 files/pt-br/web/api/serviceworkercontainer/register/index.html create mode 100644 files/pt-br/web/api/serviceworkerglobalscope/clients/index.html create mode 100644 files/pt-br/web/api/serviceworkerglobalscope/index.html create mode 100644 files/pt-br/web/api/sharedworker/index.html create mode 100644 files/pt-br/web/api/sharedworker/port/index.html create mode 100644 files/pt-br/web/api/speechgrammar/index.html create mode 100644 files/pt-br/web/api/speechsynthesis/index.html create mode 100644 files/pt-br/web/api/speechsynthesisutterance/index.html create mode 100644 files/pt-br/web/api/speechsynthesisutterance/voice/index.html create mode 100644 files/pt-br/web/api/storage/clear/index.html create mode 100644 files/pt-br/web/api/storage/getitem/index.html create mode 100644 files/pt-br/web/api/storage/index.html create mode 100644 files/pt-br/web/api/storage/key/index.html create mode 100644 files/pt-br/web/api/storage/length/index.html create mode 100644 files/pt-br/web/api/storage/removeitem/index.html create mode 100644 files/pt-br/web/api/storage/setitem/index.html create mode 100644 files/pt-br/web/api/storagemanager/index.html create mode 100644 files/pt-br/web/api/streams_api/concepts/index.html create mode 100644 files/pt-br/web/api/streams_api/index.html create mode 100644 files/pt-br/web/api/subtlecrypto/derivekey/index.html create mode 100644 files/pt-br/web/api/subtlecrypto/generatekey/index.html create mode 100644 files/pt-br/web/api/subtlecrypto/importkey/index.html create mode 100644 files/pt-br/web/api/subtlecrypto/index.html create mode 100644 files/pt-br/web/api/svgaelement/index.html create mode 100644 files/pt-br/web/api/svgaelement/svgalement.target/index.html create mode 100644 files/pt-br/web/api/svganimatetransformelement/index.html create mode 100644 files/pt-br/web/api/url/createobjecturl/index.html create mode 100644 files/pt-br/web/api/url/index.html create mode 100644 files/pt-br/web/api/url/revokeobjecturl/index.html create mode 100644 files/pt-br/web/api/url/searchparams/index.html create mode 100644 files/pt-br/web/api/urlsearchparams/get/index.html create mode 100644 files/pt-br/web/api/urlsearchparams/index.html create mode 100644 files/pt-br/web/api/urlsearchparams/values/index.html create mode 100644 files/pt-br/web/api/validitystate/index.html create mode 100644 files/pt-br/web/api/web_animations_api/index.html create mode 100644 files/pt-br/web/api/web_animations_api/usando_a_web_animations_api/index.html create mode 100644 files/pt-br/web/api/web_crypto_api/index.html create mode 100644 files/pt-br/web/api/web_storage_api_pt_br/index.html create mode 100644 files/pt-br/web/api/web_storage_api_pt_br/using_the_web_storage_api/index.html create mode 100644 files/pt-br/web/api/web_workers_api/index.html create mode 100644 files/pt-br/web/api/webgl_api/index.html create mode 100644 files/pt-br/web/api/webgl_api/tutorial/adicionando_conteudo_2d_a_um_contexto_webgl/index.html create mode 100644 files/pt-br/web/api/webgl_api/tutorial/getting_started_with_webgl/index.html create mode 100644 files/pt-br/web/api/webgl_api/tutorial/index.html create mode 100644 files/pt-br/web/api/webrtc_api/index.html create mode 100644 files/pt-br/web/api/webrtc_api/protocols/index.html create mode 100644 files/pt-br/web/api/webrtc_api/simples_rtcdatachannel_amostra/index.html create mode 100644 files/pt-br/web/api/websocket/index.html create mode 100644 files/pt-br/web/api/webvr_api/index.html create mode 100644 files/pt-br/web/api/webvr_api/using_the_webvr_api/index.html create mode 100644 files/pt-br/web/api/window/alert/index.html create mode 100644 files/pt-br/web/api/window/applicationcache/index.html create mode 100644 files/pt-br/web/api/window/closed/index.html create mode 100644 files/pt-br/web/api/window/confirm/index.html create mode 100644 files/pt-br/web/api/window/crypto/index.html create mode 100644 files/pt-br/web/api/window/document/index.html create mode 100644 files/pt-br/web/api/window/event/index.html create mode 100644 files/pt-br/web/api/window/fullscreen/index.html create mode 100644 files/pt-br/web/api/window/getselection/index.html create mode 100644 files/pt-br/web/api/window/history/index.html create mode 100644 files/pt-br/web/api/window/index.html create mode 100644 files/pt-br/web/api/window/innerheight/index.html create mode 100644 files/pt-br/web/api/window/length/index.html create mode 100644 files/pt-br/web/api/window/location/index.html create mode 100644 files/pt-br/web/api/window/matchmedia/index.html create mode 100644 files/pt-br/web/api/window/navigator/index.html create mode 100644 files/pt-br/web/api/window/ondevicelight/index.html create mode 100644 files/pt-br/web/api/window/onscroll/index.html create mode 100644 files/pt-br/web/api/window/opendialog/index.html create mode 100644 files/pt-br/web/api/window/performance/index.html create mode 100644 files/pt-br/web/api/window/popstate_event/index.html create mode 100644 files/pt-br/web/api/window/print/index.html create mode 100644 files/pt-br/web/api/window/prompt/index.html create mode 100644 files/pt-br/web/api/window/requestanimationframe/index.html create mode 100644 files/pt-br/web/api/window/requestidlecallback/index.html create mode 100644 files/pt-br/web/api/window/resize_event/index.html create mode 100644 files/pt-br/web/api/window/scroll/index.html create mode 100644 files/pt-br/web/api/window/scrollby/index.html create mode 100644 files/pt-br/web/api/window/scrollbypages/index.html create mode 100644 files/pt-br/web/api/window/scrollto/index.html create mode 100644 files/pt-br/web/api/window/scrolly/index.html create mode 100644 files/pt-br/web/api/window/sessionstorage/index.html create mode 100644 files/pt-br/web/api/window/setcursor/index.html create mode 100644 files/pt-br/web/api/window/setimmediate/index.html create mode 100644 files/pt-br/web/api/window/url/index.html create mode 100644 files/pt-br/web/api/window/window.localstorage/index.html create mode 100644 files/pt-br/web/api/windowbase64/atob/index.html create mode 100644 files/pt-br/web/api/windowbase64/index.html create mode 100644 files/pt-br/web/api/windoweventhandlers/index.html create mode 100644 files/pt-br/web/api/windoweventhandlers/onhashchange/index.html create mode 100644 files/pt-br/web/api/windoweventhandlers/onpopstate/index.html create mode 100644 files/pt-br/web/api/windoweventhandlers/onstorage/index.html create mode 100644 files/pt-br/web/api/windoworworkerglobalscope/fetch/index.html create mode 100644 files/pt-br/web/api/windoworworkerglobalscope/index.html create mode 100644 files/pt-br/web/api/windoworworkerglobalscope/setinterval/index.html create mode 100644 files/pt-br/web/api/windowtimers/cleartimeout/index.html create mode 100644 files/pt-br/web/api/windowtimers/index.html create mode 100644 files/pt-br/web/api/worker/index.html create mode 100644 files/pt-br/web/api/xmldocument/async/index.html create mode 100644 files/pt-br/web/api/xmldocument/index.html create mode 100644 files/pt-br/web/api/xmlhttprequest/abort/index.html create mode 100644 files/pt-br/web/api/xmlhttprequest/index.html create mode 100644 files/pt-br/web/api/xmlhttprequest/onreadystatechange/index.html create mode 100644 files/pt-br/web/api/xmlhttprequest/open/index.html create mode 100644 files/pt-br/web/api/xmlhttprequest/readystate/index.html create mode 100644 files/pt-br/web/api/xmlhttprequest/requisicoes_sincronas_e_assincronas/index.html create mode 100644 files/pt-br/web/api/xmlhttprequest/send/index.html create mode 100644 files/pt-br/web/api/xmlhttprequest/setrequestheader/index.html create mode 100644 files/pt-br/web/api/xmlhttprequest/timeout/index.html create mode 100644 files/pt-br/web/api/xmlhttprequest/usando_xmlhttprequest/index.html create mode 100644 files/pt-br/web/css/--_star_/index.html create mode 100644 files/pt-br/web/css/-moz-binding/index.html create mode 100644 files/pt-br/web/css/-moz-border-bottom-colors/index.html create mode 100644 files/pt-br/web/css/-moz-border-left-colors/index.html create mode 100644 files/pt-br/web/css/-moz-border-right-colors/index.html create mode 100644 files/pt-br/web/css/-moz-border-top-colors/index.html create mode 100644 files/pt-br/web/css/-moz-box-ordinal-group/index.html create mode 100644 files/pt-br/web/css/-moz-cell/index.html create mode 100644 files/pt-br/web/css/-moz-context-properties/index.html create mode 100644 files/pt-br/web/css/-webkit-overflow-scrolling/index.html create mode 100644 files/pt-br/web/css/-webkit-text-security/index.html create mode 100644 files/pt-br/web/css/@charset/index.html create mode 100644 files/pt-br/web/css/@font-face/index.html create mode 100644 files/pt-br/web/css/@import/index.html create mode 100644 files/pt-br/web/css/@keyframes/index.html create mode 100644 files/pt-br/web/css/@media/aspect-ratio/index.html create mode 100644 files/pt-br/web/css/@media/display-mode/index.html create mode 100644 files/pt-br/web/css/@media/index.html create mode 100644 files/pt-br/web/css/@media/prefers-color-scheme/index.html create mode 100644 files/pt-br/web/css/@page/index.html create mode 100644 files/pt-br/web/css/_colon_active/index.html create mode 100644 files/pt-br/web/css/_colon_blank/index.html create mode 100644 files/pt-br/web/css/_colon_checked/index.html create mode 100644 files/pt-br/web/css/_colon_disabled/index.html create mode 100644 files/pt-br/web/css/_colon_empty/index.html create mode 100644 files/pt-br/web/css/_colon_enabled/index.html create mode 100644 files/pt-br/web/css/_colon_first-child/index.html create mode 100644 files/pt-br/web/css/_colon_first-of-type/index.html create mode 100644 files/pt-br/web/css/_colon_focus-within/index.html create mode 100644 files/pt-br/web/css/_colon_focus/index.html create mode 100644 files/pt-br/web/css/_colon_fullscreen/index.html create mode 100644 files/pt-br/web/css/_colon_hover/index.html create mode 100644 files/pt-br/web/css/_colon_invalid/index.html create mode 100644 files/pt-br/web/css/_colon_last-child/index.html create mode 100644 files/pt-br/web/css/_colon_last-of-type/index.html create mode 100644 files/pt-br/web/css/_colon_link/index.html create mode 100644 files/pt-br/web/css/_colon_not/index.html create mode 100644 files/pt-br/web/css/_colon_nth-child/index.html create mode 100644 files/pt-br/web/css/_colon_nth-last-child/index.html create mode 100644 files/pt-br/web/css/_colon_nth-of-type/index.html create mode 100644 files/pt-br/web/css/_colon_only-child/index.html create mode 100644 files/pt-br/web/css/_colon_only-of-type/index.html create mode 100644 files/pt-br/web/css/_colon_optional/index.html create mode 100644 files/pt-br/web/css/_colon_out-of-range/index.html create mode 100644 files/pt-br/web/css/_colon_read-write/index.html create mode 100644 files/pt-br/web/css/_colon_required/index.html create mode 100644 files/pt-br/web/css/_colon_root/index.html create mode 100644 files/pt-br/web/css/_colon_target/index.html create mode 100644 files/pt-br/web/css/_colon_valid/index.html create mode 100644 files/pt-br/web/css/_colon_visited/index.html create mode 100644 files/pt-br/web/css/_doublecolon_-ms-tooltip/index.html create mode 100644 files/pt-br/web/css/_doublecolon_after/index.html create mode 100644 files/pt-br/web/css/_doublecolon_backdrop/index.html create mode 100644 files/pt-br/web/css/_doublecolon_before/index.html create mode 100644 files/pt-br/web/css/_doublecolon_first-letter/index.html create mode 100644 files/pt-br/web/css/_doublecolon_first-line/index.html create mode 100644 files/pt-br/web/css/_doublecolon_selection/index.html create mode 100644 files/pt-br/web/css/align-content/index.html create mode 100644 files/pt-br/web/css/align-items/index.html create mode 100644 files/pt-br/web/css/align-self/index.html create mode 100644 files/pt-br/web/css/animation-delay/index.html create mode 100644 files/pt-br/web/css/animation-fill-mode/index.html create mode 100644 files/pt-br/web/css/animation/index.html create mode 100644 files/pt-br/web/css/at-rule/index.html create mode 100644 files/pt-br/web/css/attr()/index.html create mode 100644 files/pt-br/web/css/backdrop-filter/index.html create mode 100644 files/pt-br/web/css/backface-visibility/index.html create mode 100644 files/pt-br/web/css/background-attachment/index.html create mode 100644 files/pt-br/web/css/background-blend-mode/index.html create mode 100644 files/pt-br/web/css/background-clip/index.html create mode 100644 files/pt-br/web/css/background-color/index.html create mode 100644 files/pt-br/web/css/background-origin/index.html create mode 100644 files/pt-br/web/css/background-position/index.html create mode 100644 files/pt-br/web/css/background-size/index.html create mode 100644 files/pt-br/web/css/background/index.html create mode 100644 files/pt-br/web/css/blend-mode/index.html create mode 100644 files/pt-br/web/css/block-size/index.html create mode 100644 files/pt-br/web/css/border-left-color/index.html create mode 100644 files/pt-br/web/css/border-left/index.html create mode 100644 files/pt-br/web/css/border-radius/index.html create mode 100644 files/pt-br/web/css/box-shadow/index.html create mode 100644 files/pt-br/web/css/box-sizing/index.html create mode 100644 files/pt-br/web/css/box_model/index.html create mode 100644 files/pt-br/web/css/break-after/index.html create mode 100644 files/pt-br/web/css/calc()/index.html create mode 100644 files/pt-br/web/css/class_selectors/index.html create mode 100644 files/pt-br/web/css/clear/index.html create mode 100644 files/pt-br/web/css/color/index.html create mode 100644 files/pt-br/web/css/color_value/index.html create mode 100644 "files/pt-br/web/css/coment\303\241rio/index.html" create mode 100644 files/pt-br/web/css/contain/index.html create mode 100644 files/pt-br/web/css/content/index.html create mode 100644 files/pt-br/web/css/css_animations/detecting_css_animation_support/index.html create mode 100644 files/pt-br/web/css/css_animations/index.html create mode 100644 files/pt-br/web/css/css_animations/tips/index.html create mode 100644 "files/pt-br/web/css/css_animations/usando_anima\303\247\303\265es_css/index.html" create mode 100644 files/pt-br/web/css/css_background_and_borders/index.html create mode 100644 files/pt-br/web/css/css_background_and_borders/using_css_multiple_backgrounds/index.html create mode 100644 files/pt-br/web/css/css_basic_user_interface/index.html create mode 100644 files/pt-br/web/css/css_box_model/index.html create mode 100644 files/pt-br/web/css/css_box_model/margin_collapsing/index.html create mode 100644 files/pt-br/web/css/css_colors/seletor_de_cores/index.html create mode 100644 files/pt-br/web/css/css_columns/index.html create mode 100644 files/pt-br/web/css/css_display/index.html create mode 100644 files/pt-br/web/css/css_flexible_box_layout/aligning_items_in_a_flex_container/index.html create mode 100644 files/pt-br/web/css/css_flexible_box_layout/conceitos_basicos_do_flexbox/index.html create mode 100644 files/pt-br/web/css/css_flexible_box_layout/index.html create mode 100644 files/pt-br/web/css/css_flexible_box_layout/ordering_flex_items/index.html create mode 100644 files/pt-br/web/css/css_flexible_box_layout/typical_use_cases_of_flexbox/index.html create mode 100644 files/pt-br/web/css/css_grid_layout/basic_concepts_of_grid_layout/index.html create mode 100644 files/pt-br/web/css/css_grid_layout/index.html create mode 100644 files/pt-br/web/css/css_grid_layout/relationship_of_grid_layout/index.html create mode 100644 files/pt-br/web/css/css_images/implementando_sprites_de_imagens_em_css/index.html create mode 100644 files/pt-br/web/css/css_images/index.html create mode 100644 files/pt-br/web/css/css_lists_and_counters/index.html create mode 100644 files/pt-br/web/css/css_lists_and_counters/using_css_counters/index.html create mode 100644 files/pt-br/web/css/css_positioning/index.html create mode 100644 files/pt-br/web/css/css_reference/index.html create mode 100644 files/pt-br/web/css/css_tipos/index.html create mode 100644 files/pt-br/web/css/css_transforms/index.html create mode 100644 files/pt-br/web/css/css_transforms/using_css_transforms/index.html create mode 100644 files/pt-br/web/css/css_transitions/index.html create mode 100644 files/pt-br/web/css/css_transitions/using_css_transitions/index.html create mode 100644 files/pt-br/web/css/cursor/index.html create mode 100644 files/pt-br/web/css/descendant_combinator/index.html create mode 100644 files/pt-br/web/css/display-box/index.html create mode 100644 files/pt-br/web/css/display-inside/index.html create mode 100644 files/pt-br/web/css/display-internal/index.html create mode 100644 files/pt-br/web/css/display-legacy/index.html create mode 100644 files/pt-br/web/css/display-listitem/index.html create mode 100644 files/pt-br/web/css/display-outside/index.html create mode 100644 files/pt-br/web/css/display/index.html create mode 100644 files/pt-br/web/css/element()/index.html create mode 100644 files/pt-br/web/css/elemento_substituido/index.html create mode 100644 files/pt-br/web/css/env()/index.html create mode 100644 files/pt-br/web/css/filter-function/grayscale()/index.html create mode 100644 files/pt-br/web/css/filter-function/index.html create mode 100644 files/pt-br/web/css/filter-function/opacity()/index.html create mode 100644 files/pt-br/web/css/filter-function/sepia()/index.html create mode 100644 files/pt-br/web/css/flex-direction/index.html create mode 100644 files/pt-br/web/css/flex-flow/index.html create mode 100644 files/pt-br/web/css/flex-wrap/index.html create mode 100644 files/pt-br/web/css/flex/index.html create mode 100644 files/pt-br/web/css/float/index.html create mode 100644 files/pt-br/web/css/font-family/index.html create mode 100644 files/pt-br/web/css/font-feature-settings/index.html create mode 100644 files/pt-br/web/css/font-kerning/index.html create mode 100644 files/pt-br/web/css/font-size/index.html create mode 100644 files/pt-br/web/css/font-variation-settings/index.html create mode 100644 files/pt-br/web/css/font-weight/index.html create mode 100644 files/pt-br/web/css/general_sibling_combinator/index.html create mode 100644 files/pt-br/web/css/getting_started/cascading_and_inheritance/index.html create mode 100644 files/pt-br/web/css/getting_started/como_css_funciona/index.html create mode 100644 files/pt-br/web/css/getting_started/index.html create mode 100644 files/pt-br/web/css/getting_started/javascript/index.html create mode 100644 files/pt-br/web/css/getting_started/lists/index.html create mode 100644 files/pt-br/web/css/getting_started/oque_é_css/index.html create mode 100644 files/pt-br/web/css/getting_started/porque_usar_css/index.html create mode 100644 files/pt-br/web/css/getting_started/seletores/index.html create mode 100644 files/pt-br/web/css/grid-auto-flow/index.html create mode 100644 files/pt-br/web/css/grid-template-columns/index.html create mode 100644 files/pt-br/web/css/grid-template-rows/index.html create mode 100644 files/pt-br/web/css/grid/index.html create mode 100644 files/pt-br/web/css/height/index.html create mode 100644 files/pt-br/web/css/hifens/index.html create mode 100644 files/pt-br/web/css/id_selectors/index.html create mode 100644 files/pt-br/web/css/image-set()/index.html create mode 100644 files/pt-br/web/css/imagem/index.html create mode 100644 files/pt-br/web/css/index.html create mode 100644 files/pt-br/web/css/inheritance/index.html create mode 100644 files/pt-br/web/css/initial/index.html create mode 100644 files/pt-br/web/css/inline-size/index.html create mode 100644 files/pt-br/web/css/isolation/index.html create mode 100644 files/pt-br/web/css/layout_cookbook/breadcrumb_navigation/index.html create mode 100644 files/pt-br/web/css/layout_cookbook/index.html create mode 100644 files/pt-br/web/css/layout_cookbook/media_objects/index.html create mode 100644 files/pt-br/web/css/letter-spacing/index.html create mode 100644 files/pt-br/web/css/line-break/index.html create mode 100644 files/pt-br/web/css/margin-bottom/index.html create mode 100644 files/pt-br/web/css/margin-top/index.html create mode 100644 files/pt-br/web/css/margin/index.html create mode 100644 files/pt-br/web/css/max-width/index.html create mode 100644 files/pt-br/web/css/media_queries/index.html create mode 100644 files/pt-br/web/css/microsoft_extensions/index.html create mode 100644 files/pt-br/web/css/min-height/index.html create mode 100644 files/pt-br/web/css/mix-blend-mode/index.html create mode 100644 files/pt-br/web/css/modelo_layout/index.html create mode 100644 files/pt-br/web/css/modelo_visual/index.html create mode 100644 files/pt-br/web/css/number/index.html create mode 100644 files/pt-br/web/css/object-fit/index.html create mode 100644 files/pt-br/web/css/offset/index.html create mode 100644 files/pt-br/web/css/opacity/index.html create mode 100644 files/pt-br/web/css/outline/index.html create mode 100644 files/pt-br/web/css/overflow/index.html create mode 100644 files/pt-br/web/css/padding-left/index.html create mode 100644 files/pt-br/web/css/padding/index.html create mode 100644 files/pt-br/web/css/page-break-before/index.html create mode 100644 files/pt-br/web/css/pointer-events/index.html create mode 100644 files/pt-br/web/css/position/index.html create mode 100644 files/pt-br/web/css/privacidade_e_o_seletor__colon_visited/index.html create mode 100644 files/pt-br/web/css/pseudo-classes/index.html create mode 100644 files/pt-br/web/css/pseudo-elementos/index.html create mode 100644 files/pt-br/web/css/radial-gradient()/index.html create mode 100644 files/pt-br/web/css/repeating-linear-gradient()/index.html create mode 100644 files/pt-br/web/css/ruby-align/index.html create mode 100644 files/pt-br/web/css/scroll-behavior/index.html create mode 100644 files/pt-br/web/css/scrollbar-color/index.html create mode 100644 files/pt-br/web/css/seletor_de_atributos/index.html create mode 100644 files/pt-br/web/css/seletor_universal/index.html create mode 100644 files/pt-br/web/css/seletores_css/index.html create mode 100644 files/pt-br/web/css/shorthand_properties/index.html create mode 100644 files/pt-br/web/css/sintaxe/index.html create mode 100644 files/pt-br/web/css/sintexe_valor/index.html create mode 100644 files/pt-br/web/css/specificity/index.html create mode 100644 files/pt-br/web/css/text-align/index.html create mode 100644 files/pt-br/web/css/text-decoration-style/index.html create mode 100644 files/pt-br/web/css/text-decoration/index.html create mode 100644 files/pt-br/web/css/text-overflow/index.html create mode 100644 files/pt-br/web/css/text-rendering/index.html create mode 100644 files/pt-br/web/css/text-shadow/index.html create mode 100644 files/pt-br/web/css/text-transform/index.html create mode 100644 files/pt-br/web/css/time/index.html create mode 100644 files/pt-br/web/css/tools/border-image_generator/index.html create mode 100644 files/pt-br/web/css/tools/border-radius_generator/index.html create mode 100644 files/pt-br/web/css/tools/index.html create mode 100644 files/pt-br/web/css/touch-action/index.html create mode 100644 files/pt-br/web/css/transform-function/index.html create mode 100644 files/pt-br/web/css/transform-function/matrix()/index.html create mode 100644 files/pt-br/web/css/transform-function/perspective()/index.html create mode 100644 files/pt-br/web/css/transform-function/rotate()/index.html create mode 100644 files/pt-br/web/css/transform-function/rotate3d()/index.html create mode 100644 files/pt-br/web/css/transform-function/scale()/index.html create mode 100644 files/pt-br/web/css/transform-function/translate()/index.html create mode 100644 files/pt-br/web/css/transform-style/index.html create mode 100644 files/pt-br/web/css/transform/index.html create mode 100644 files/pt-br/web/css/transition-delay/index.html create mode 100644 files/pt-br/web/css/transition-timing-function/index.html create mode 100644 files/pt-br/web/css/transition/index.html create mode 100644 files/pt-br/web/css/type_selectors/index.html create mode 100644 files/pt-br/web/css/using_css_custom_properties/index.html create mode 100644 files/pt-br/web/css/valor_atual/index.html create mode 100644 files/pt-br/web/css/valor_computado/index.html create mode 100644 files/pt-br/web/css/valor_espeficifco/index.html create mode 100644 files/pt-br/web/css/valor_inicial/index.html create mode 100644 files/pt-br/web/css/valor_resolvido/index.html create mode 100644 files/pt-br/web/css/valor_usado/index.html create mode 100644 files/pt-br/web/css/var()/index.html create mode 100644 files/pt-br/web/css/vertical-align/index.html create mode 100644 files/pt-br/web/css/visibility/index.html create mode 100644 files/pt-br/web/css/white-space/index.html create mode 100644 files/pt-br/web/css/width/index.html create mode 100644 files/pt-br/web/css/will-change/index.html create mode 100644 files/pt-br/web/css/word-break/index.html create mode 100644 files/pt-br/web/css/word-wrap/index.html create mode 100644 files/pt-br/web/css/writing-mode/index.html create mode 100644 files/pt-br/web/demos_of_open_web_technologies/index.html create mode 100644 files/pt-br/web/events/abort/index.html create mode 100644 files/pt-br/web/events/beforeunload/index.html create mode 100644 files/pt-br/web/events/blur/index.html create mode 100644 files/pt-br/web/events/domcontentloaded/index.html create mode 100644 files/pt-br/web/events/focus/index.html create mode 100644 files/pt-br/web/events/focusin/index.html create mode 100644 files/pt-br/web/events/focusout/index.html create mode 100644 files/pt-br/web/events/index.html create mode 100644 files/pt-br/web/events/input/index.html create mode 100644 files/pt-br/web/events/load/index.html create mode 100644 files/pt-br/web/events/readystatechange/index.html create mode 100644 files/pt-br/web/guide/ajax/getting_started/index.html create mode 100644 files/pt-br/web/guide/ajax/index.html create mode 100644 files/pt-br/web/guide/api/camera/index.html create mode 100644 files/pt-br/web/guide/api/index.html create mode 100644 files/pt-br/web/guide/css/css_media_queries/index.html create mode 100644 "files/pt-br/web/guide/css/css_media_queries_(consultas_de_m\303\255dia_em_css)/index.html" create mode 100644 files/pt-br/web/guide/css/scaling_background_images/index.html create mode 100644 files/pt-br/web/guide/css/understanding_z_index/index.html create mode 100644 files/pt-br/web/guide/events/criando_e_disparando_eventos/index.html create mode 100644 files/pt-br/web/guide/events/event_handlers/index.html create mode 100644 files/pt-br/web/guide/events/index.html create mode 100644 files/pt-br/web/guide/events/mutation_events/index.html create mode 100644 files/pt-br/web/guide/events/overview_of_events_and_handlers/index.html create mode 100644 files/pt-br/web/guide/events/touch_events/index.html create mode 100644 "files/pt-br/web/guide/gr\303\241ficos/index.html" create mode 100644 files/pt-br/web/guide/html/canvas_tutorial/advanced_animations/index.html create mode 100644 files/pt-br/web/guide/html/canvas_tutorial/applying_styles_and_colors/index.html create mode 100644 files/pt-br/web/guide/html/canvas_tutorial/basic_animations/index.html create mode 100644 files/pt-br/web/guide/html/canvas_tutorial/compositing/exemplo/index.html create mode 100644 files/pt-br/web/guide/html/canvas_tutorial/compositing/index.html create mode 100644 "files/pt-br/web/guide/html/canvas_tutorial/conclus\303\243o/index.html" create mode 100644 files/pt-br/web/guide/html/canvas_tutorial/drawing_shapes/index.html create mode 100644 files/pt-br/web/guide/html/canvas_tutorial/drawing_text/index.html create mode 100644 files/pt-br/web/guide/html/canvas_tutorial/index.html create mode 100644 files/pt-br/web/guide/html/canvas_tutorial/otimizando_canvas/index.html create mode 100644 files/pt-br/web/guide/html/canvas_tutorial/using_images/index.html create mode 100644 files/pt-br/web/guide/html/canvas_tutorial/utilizacao_basica/index.html create mode 100644 files/pt-br/web/guide/html/categorias_de_conteudo/index.html create mode 100644 files/pt-br/web/guide/html/content_editable/index.html create mode 100644 files/pt-br/web/guide/html/forms/form_validation/index.html create mode 100644 files/pt-br/web/guide/html/forms/how_to_build_custom_form_widgets/index.html create mode 100644 files/pt-br/web/guide/html/forms/how_to_structure_an_html_form/index.html create mode 100644 files/pt-br/web/guide/html/forms/index.html create mode 100644 files/pt-br/web/guide/html/forms/meu_primeiro_formulario_html/index.html create mode 100644 files/pt-br/web/guide/html/forms/os_widgets_nativos/index.html create mode 100644 files/pt-br/web/guide/html/forms/sending_and_retrieving_form_data/index.html create mode 100644 files/pt-br/web/guide/html/using_data_attributes/index.html create mode 100644 files/pt-br/web/guide/index.html create mode 100644 files/pt-br/web/guide/introducao_ao_desenvolvimento_web/index.html create mode 100644 files/pt-br/web/guide/mobile/index.html create mode 100644 files/pt-br/web/guide/performance/index.html create mode 100644 files/pt-br/web/guide/printing/index.html create mode 100644 files/pt-br/web/html/applying_color/index.html create mode 100644 files/pt-br/web/html/canvas/a_basic_ray-caster/index.html create mode 100644 files/pt-br/web/html/canvas/index.html create mode 100644 files/pt-br/web/html/controlando_verificacao_ortografica_em_formularios_html/index.html create mode 100644 files/pt-br/web/html/cors_imagens_habilitadas/index.html create mode 100644 "files/pt-br/web/html/dicas_para_criar_p\303\241ginas_html_de_carregamento_r\303\241pido/index.html" create mode 100644 files/pt-br/web/html/element/a/index.html create mode 100644 files/pt-br/web/html/element/abbr/index.html create mode 100644 files/pt-br/web/html/element/acronym/index.html create mode 100644 files/pt-br/web/html/element/address/index.html create mode 100644 files/pt-br/web/html/element/applet/index.html create mode 100644 files/pt-br/web/html/element/area/index.html create mode 100644 files/pt-br/web/html/element/article/index.html create mode 100644 files/pt-br/web/html/element/aside/index.html create mode 100644 files/pt-br/web/html/element/audio/index.html create mode 100644 files/pt-br/web/html/element/b/index.html create mode 100644 files/pt-br/web/html/element/base/index.html create mode 100644 files/pt-br/web/html/element/bdi/index.html create mode 100644 files/pt-br/web/html/element/bdo/index.html create mode 100644 files/pt-br/web/html/element/big/index.html create mode 100644 files/pt-br/web/html/element/blink/index.html create mode 100644 files/pt-br/web/html/element/blockquote/index.html create mode 100644 files/pt-br/web/html/element/body/index.html create mode 100644 files/pt-br/web/html/element/br/index.html create mode 100644 files/pt-br/web/html/element/button/index.html create mode 100644 files/pt-br/web/html/element/canvas/index.html create mode 100644 files/pt-br/web/html/element/caption/index.html create mode 100644 files/pt-br/web/html/element/center/index.html create mode 100644 files/pt-br/web/html/element/cite/index.html create mode 100644 files/pt-br/web/html/element/code/index.html create mode 100644 files/pt-br/web/html/element/col/index.html create mode 100644 files/pt-br/web/html/element/command/index.html create mode 100644 "files/pt-br/web/html/element/conte\303\272do/index.html" create mode 100644 files/pt-br/web/html/element/data/index.html create mode 100644 files/pt-br/web/html/element/datalist/index.html create mode 100644 files/pt-br/web/html/element/dd/index.html create mode 100644 files/pt-br/web/html/element/del/index.html create mode 100644 files/pt-br/web/html/element/details/index.html create mode 100644 files/pt-br/web/html/element/dfn/index.html create mode 100644 files/pt-br/web/html/element/dialog/index.html create mode 100644 files/pt-br/web/html/element/dir/index.html create mode 100644 files/pt-br/web/html/element/div/index.html create mode 100644 files/pt-br/web/html/element/dl/index.html create mode 100644 files/pt-br/web/html/element/dt/index.html create mode 100644 files/pt-br/web/html/element/em/index.html create mode 100644 files/pt-br/web/html/element/embed/index.html create mode 100644 files/pt-br/web/html/element/fieldset/index.html create mode 100644 files/pt-br/web/html/element/figcaption/index.html create mode 100644 files/pt-br/web/html/element/figura/index.html create mode 100644 files/pt-br/web/html/element/footer/index.html create mode 100644 files/pt-br/web/html/element/form/index.html create mode 100644 files/pt-br/web/html/element/head/index.html create mode 100644 files/pt-br/web/html/element/header/index.html create mode 100644 files/pt-br/web/html/element/heading_elements/index.html create mode 100644 files/pt-br/web/html/element/hgroup/index.html create mode 100644 files/pt-br/web/html/element/hr/index.html create mode 100644 files/pt-br/web/html/element/html/index.html create mode 100644 files/pt-br/web/html/element/i/index.html create mode 100644 files/pt-br/web/html/element/iframe/index.html create mode 100644 files/pt-br/web/html/element/img/index.html create mode 100644 files/pt-br/web/html/element/index.html create mode 100644 files/pt-br/web/html/element/input/button/index.html create mode 100644 files/pt-br/web/html/element/input/checkbox/index.html create mode 100644 files/pt-br/web/html/element/input/data/index.html create mode 100644 files/pt-br/web/html/element/input/index.html create mode 100644 files/pt-br/web/html/element/input/password/index.html create mode 100644 files/pt-br/web/html/element/input/range/index.html create mode 100644 files/pt-br/web/html/element/input/time/index.html create mode 100644 files/pt-br/web/html/element/ins/index.html create mode 100644 files/pt-br/web/html/element/label/index.html create mode 100644 files/pt-br/web/html/element/legend/index.html create mode 100644 files/pt-br/web/html/element/li/index.html create mode 100644 files/pt-br/web/html/element/link/index.html create mode 100644 files/pt-br/web/html/element/main/index.html create mode 100644 files/pt-br/web/html/element/map/index.html create mode 100644 files/pt-br/web/html/element/mark/index.html create mode 100644 files/pt-br/web/html/element/marquee/index.html create mode 100644 files/pt-br/web/html/element/meta/index.html create mode 100644 files/pt-br/web/html/element/meter/index.html create mode 100644 files/pt-br/web/html/element/nav/index.html create mode 100644 files/pt-br/web/html/element/nobr/index.html create mode 100644 files/pt-br/web/html/element/noscript/index.html create mode 100644 files/pt-br/web/html/element/ol/index.html create mode 100644 files/pt-br/web/html/element/optgroup/index.html create mode 100644 files/pt-br/web/html/element/option/index.html create mode 100644 files/pt-br/web/html/element/output/index.html create mode 100644 files/pt-br/web/html/element/p/index.html create mode 100644 files/pt-br/web/html/element/picture/index.html create mode 100644 files/pt-br/web/html/element/pre/index.html create mode 100644 files/pt-br/web/html/element/progress/index.html create mode 100644 files/pt-br/web/html/element/q/index.html create mode 100644 files/pt-br/web/html/element/rt/index.html create mode 100644 files/pt-br/web/html/element/ruby/index.html create mode 100644 files/pt-br/web/html/element/s/index.html create mode 100644 files/pt-br/web/html/element/script/index.html create mode 100644 files/pt-br/web/html/element/section/index.html create mode 100644 files/pt-br/web/html/element/select/index.html create mode 100644 files/pt-br/web/html/element/source/index.html create mode 100644 files/pt-br/web/html/element/span/index.html create mode 100644 files/pt-br/web/html/element/strong/index.html create mode 100644 files/pt-br/web/html/element/style/index.html create mode 100644 files/pt-br/web/html/element/summary/index.html create mode 100644 files/pt-br/web/html/element/table/index.html create mode 100644 files/pt-br/web/html/element/template/index.html create mode 100644 files/pt-br/web/html/element/textarea/index.html create mode 100644 files/pt-br/web/html/element/tfoot/index.html create mode 100644 files/pt-br/web/html/element/th/index.html create mode 100644 files/pt-br/web/html/element/time/index.html create mode 100644 files/pt-br/web/html/element/title/index.html create mode 100644 files/pt-br/web/html/element/track/index.html create mode 100644 files/pt-br/web/html/element/ul/index.html create mode 100644 files/pt-br/web/html/element/var/index.html create mode 100644 files/pt-br/web/html/element/video/index.html create mode 100644 files/pt-br/web/html/element/wbr/index.html create mode 100644 files/pt-br/web/html/elementos_block-level/index.html create mode 100644 files/pt-br/web/html/favicon/index.html create mode 100644 files/pt-br/web/html/formatos_midia_suportados/index.html create mode 100644 files/pt-br/web/html/global_attributes/accesskey/index.html create mode 100644 files/pt-br/web/html/global_attributes/autocapitalize/index.html create mode 100644 files/pt-br/web/html/global_attributes/class/index.html create mode 100644 files/pt-br/web/html/global_attributes/contenteditable/index.html create mode 100644 files/pt-br/web/html/global_attributes/data-_star_/index.html create mode 100644 files/pt-br/web/html/global_attributes/hidden/index.html create mode 100644 files/pt-br/web/html/global_attributes/id/index.html create mode 100644 files/pt-br/web/html/global_attributes/index.html create mode 100644 files/pt-br/web/html/global_attributes/itemprop/index.html create mode 100644 files/pt-br/web/html/global_attributes/lang/index.html create mode 100644 files/pt-br/web/html/global_attributes/tabindex/index.html create mode 100644 files/pt-br/web/html/global_attributes/title/index.html create mode 100644 files/pt-br/web/html/html5/index.html create mode 100644 files/pt-br/web/html/html5/introduction_to_html5/index.html create mode 100644 files/pt-br/web/html/index.html create mode 100644 files/pt-br/web/html/inline_elemente/index.html create mode 100644 files/pt-br/web/html/microformatos/index.html create mode 100644 files/pt-br/web/html/optimizing_your_pages_for_speculative_parsing/index.html create mode 100644 files/pt-br/web/html/preloading_content/index.html create mode 100644 files/pt-br/web/html/quirks_mode_and_standards_mode/index.html create mode 100644 files/pt-br/web/html/referenciahtml/index.html create mode 100644 files/pt-br/web/html/using_html5_audio_and_video/index.html create mode 100644 files/pt-br/web/html/using_the_application_cache/index.html create mode 100644 files/pt-br/web/http/authentication/index.html create mode 100644 files/pt-br/web/http/basico_sobre_http/identifying_resources_on_the_web/index.html create mode 100644 files/pt-br/web/http/basico_sobre_http/index.html create mode 100644 files/pt-br/web/http/basico_sobre_http/mime_types/complete_list_of_mime_types/index.html create mode 100644 files/pt-br/web/http/basico_sobre_http/mime_types/index.html create mode 100644 "files/pt-br/web/http/compress\303\243o/index.html" create mode 100644 files/pt-br/web/http/content_negotiation/index.html create mode 100644 files/pt-br/web/http/content_negotiation/list_of_default_accept_values/index.html create mode 100644 files/pt-br/web/http/controle_acesso_cors/index.html create mode 100644 files/pt-br/web/http/cookies/index.html create mode 100644 files/pt-br/web/http/cors/errors/corsdidnotsucceed/index.html create mode 100644 files/pt-br/web/http/cors/errors/corsmissingalloworigin/index.html create mode 100644 files/pt-br/web/http/cors/errors/corsnotsupportingcredentials/index.html create mode 100644 files/pt-br/web/http/cors/errors/corsrequestnothttp/index.html create mode 100644 files/pt-br/web/http/cors/errors/index.html create mode 100644 files/pt-br/web/http/csp/index.html create mode 100644 files/pt-br/web/http/feature_policy/index.html create mode 100644 files/pt-br/web/http/feature_policy/using_feature_policy/index.html create mode 100644 "files/pt-br/web/http/gerenciamento_de_conex\303\243o_em_http_1.x/index.html" create mode 100644 files/pt-br/web/http/headers/accept-ch-lifetime/index.html create mode 100644 files/pt-br/web/http/headers/accept-ch/index.html create mode 100644 files/pt-br/web/http/headers/accept-charset/index.html create mode 100644 files/pt-br/web/http/headers/accept-encoding/index.html create mode 100644 files/pt-br/web/http/headers/accept-language/index.html create mode 100644 files/pt-br/web/http/headers/accept-patch/index.html create mode 100644 files/pt-br/web/http/headers/accept-ranges/index.html create mode 100644 files/pt-br/web/http/headers/accept/index.html create mode 100644 files/pt-br/web/http/headers/access-control-allow-credentials/index.html create mode 100644 files/pt-br/web/http/headers/access-control-allow-headers/index.html create mode 100644 files/pt-br/web/http/headers/access-control-allow-methods/index.html create mode 100644 files/pt-br/web/http/headers/access-control-allow-origin/index.html create mode 100644 files/pt-br/web/http/headers/access-control-expose-headers/index.html create mode 100644 files/pt-br/web/http/headers/access-control-max-age/index.html create mode 100644 files/pt-br/web/http/headers/access-control-request-headers/index.html create mode 100644 files/pt-br/web/http/headers/access-control-request-method/index.html create mode 100644 files/pt-br/web/http/headers/age/index.html create mode 100644 files/pt-br/web/http/headers/allow/index.html create mode 100644 files/pt-br/web/http/headers/alt-svc/index.html create mode 100644 files/pt-br/web/http/headers/authorization/index.html create mode 100644 files/pt-br/web/http/headers/cache-control/index.html create mode 100644 files/pt-br/web/http/headers/clear-site-data/index.html create mode 100644 "files/pt-br/web/http/headers/conex\303\243o/index.html" create mode 100644 files/pt-br/web/http/headers/content-disposition/index.html create mode 100644 files/pt-br/web/http/headers/content-encoding/index.html create mode 100644 files/pt-br/web/http/headers/content-language/index.html create mode 100644 files/pt-br/web/http/headers/content-length/index.html create mode 100644 files/pt-br/web/http/headers/content-location/index.html create mode 100644 files/pt-br/web/http/headers/content-range/index.html create mode 100644 files/pt-br/web/http/headers/content-security-policy-report-only/index.html create mode 100644 files/pt-br/web/http/headers/content-security-policy/index.html create mode 100644 files/pt-br/web/http/headers/content-type/index.html create mode 100644 files/pt-br/web/http/headers/cookie/index.html create mode 100644 files/pt-br/web/http/headers/cookie2/index.html create mode 100644 files/pt-br/web/http/headers/cross-origin-resource-policy/index.html create mode 100644 files/pt-br/web/http/headers/date/index.html create mode 100644 files/pt-br/web/http/headers/device-memory/index.html create mode 100644 files/pt-br/web/http/headers/digest/index.html create mode 100644 files/pt-br/web/http/headers/dnt/index.html create mode 100644 files/pt-br/web/http/headers/dpr/index.html create mode 100644 files/pt-br/web/http/headers/early-data/index.html create mode 100644 files/pt-br/web/http/headers/etag/index.html create mode 100644 files/pt-br/web/http/headers/expect-ct/index.html create mode 100644 files/pt-br/web/http/headers/expect/index.html create mode 100644 files/pt-br/web/http/headers/expires/index.html create mode 100644 files/pt-br/web/http/headers/feature-policy/index.html create mode 100644 files/pt-br/web/http/headers/forwarded/index.html create mode 100644 files/pt-br/web/http/headers/from/index.html create mode 100644 files/pt-br/web/http/headers/host/index.html create mode 100644 files/pt-br/web/http/headers/if-match/index.html create mode 100644 files/pt-br/web/http/headers/if-modified-since/index.html create mode 100644 files/pt-br/web/http/headers/if-none-match/index.html create mode 100644 files/pt-br/web/http/headers/if-range/index.html create mode 100644 files/pt-br/web/http/headers/if-unmodified-since/index.html create mode 100644 files/pt-br/web/http/headers/index.html create mode 100644 files/pt-br/web/http/headers/keep-alive/index.html create mode 100644 files/pt-br/web/http/headers/large-allocation/index.html create mode 100644 files/pt-br/web/http/headers/last-modified/index.html create mode 100644 files/pt-br/web/http/headers/link/index.html create mode 100644 "files/pt-br/web/http/headers/localiza\303\247\303\243o/index.html" create mode 100644 files/pt-br/web/http/headers/nel/index.html create mode 100644 files/pt-br/web/http/headers/origin/index.html create mode 100644 files/pt-br/web/http/headers/pragma/index.html create mode 100644 files/pt-br/web/http/headers/proxy-authenticate/index.html create mode 100644 files/pt-br/web/http/headers/proxy-authorization/index.html create mode 100644 files/pt-br/web/http/headers/public-key-pins-report-only/index.html create mode 100644 files/pt-br/web/http/headers/public-key-pins/index.html create mode 100644 files/pt-br/web/http/headers/range/index.html create mode 100644 files/pt-br/web/http/headers/referer/index.html create mode 100644 files/pt-br/web/http/headers/referrer-policy/index.html create mode 100644 files/pt-br/web/http/headers/retry-after/index.html create mode 100644 files/pt-br/web/http/headers/save-data/index.html create mode 100644 files/pt-br/web/http/headers/sec-fetch-site/index.html create mode 100644 files/pt-br/web/http/headers/server-timing/index.html create mode 100644 files/pt-br/web/http/headers/server/index.html create mode 100644 files/pt-br/web/http/headers/set-cookie/index.html create mode 100644 files/pt-br/web/http/headers/set-cookie/samesite/index.html create mode 100644 files/pt-br/web/http/headers/set-cookie2/index.html create mode 100644 files/pt-br/web/http/headers/sourcemap/index.html create mode 100644 files/pt-br/web/http/headers/strict-transport-security/index.html create mode 100644 files/pt-br/web/http/headers/te/index.html create mode 100644 files/pt-br/web/http/headers/timing-allow-origin/index.html create mode 100644 files/pt-br/web/http/headers/tk/index.html create mode 100644 files/pt-br/web/http/headers/trailer/index.html create mode 100644 files/pt-br/web/http/headers/transfer-encoding/index.html create mode 100644 files/pt-br/web/http/headers/upgrade-insecure-requests/index.html create mode 100644 files/pt-br/web/http/headers/user-agent/index.html create mode 100644 files/pt-br/web/http/headers/vary/index.html create mode 100644 files/pt-br/web/http/headers/via/index.html create mode 100644 files/pt-br/web/http/headers/want-digest/index.html create mode 100644 files/pt-br/web/http/headers/warning/index.html create mode 100644 files/pt-br/web/http/headers/www-authenticate/index.html create mode 100644 files/pt-br/web/http/headers/x-content-type-options/index.html create mode 100644 files/pt-br/web/http/headers/x-dns-prefetch-control/index.html create mode 100644 files/pt-br/web/http/headers/x-forwarded-for/index.html create mode 100644 files/pt-br/web/http/headers/x-forwarded-host/index.html create mode 100644 files/pt-br/web/http/headers/x-forwarded-proto/index.html create mode 100644 files/pt-br/web/http/headers/x-frame-options/index.html create mode 100644 files/pt-br/web/http/headers/x-xss-protection/index.html create mode 100644 files/pt-br/web/http/http/index.html create mode 100644 files/pt-br/web/http/index.html create mode 100644 files/pt-br/web/http/mensagens/index.html create mode 100644 files/pt-br/web/http/methods/connect/index.html create mode 100644 files/pt-br/web/http/methods/delete/index.html create mode 100644 files/pt-br/web/http/methods/get/index.html create mode 100644 files/pt-br/web/http/methods/head/index.html create mode 100644 files/pt-br/web/http/methods/index.html create mode 100644 files/pt-br/web/http/methods/options/index.html create mode 100644 files/pt-br/web/http/methods/patch/index.html create mode 100644 files/pt-br/web/http/methods/post/index.html create mode 100644 files/pt-br/web/http/methods/put/index.html create mode 100644 files/pt-br/web/http/methods/trace/index.html create mode 100644 files/pt-br/web/http/overview/index.html create mode 100644 files/pt-br/web/http/redirecionamento/index.html create mode 100644 files/pt-br/web/http/server-side_access_control/index.html create mode 100644 files/pt-br/web/http/session/index.html create mode 100644 files/pt-br/web/http/status/100/index.html create mode 100644 files/pt-br/web/http/status/101/index.html create mode 100644 files/pt-br/web/http/status/103/index.html create mode 100644 files/pt-br/web/http/status/200/index.html create mode 100644 files/pt-br/web/http/status/201/index.html create mode 100644 files/pt-br/web/http/status/202/index.html create mode 100644 files/pt-br/web/http/status/203/index.html create mode 100644 files/pt-br/web/http/status/204/index.html create mode 100644 files/pt-br/web/http/status/205/index.html create mode 100644 files/pt-br/web/http/status/206/index.html create mode 100644 files/pt-br/web/http/status/300/index.html create mode 100644 files/pt-br/web/http/status/301/index.html create mode 100644 files/pt-br/web/http/status/302/index.html create mode 100644 files/pt-br/web/http/status/303/index.html create mode 100644 files/pt-br/web/http/status/304/index.html create mode 100644 files/pt-br/web/http/status/307/index.html create mode 100644 files/pt-br/web/http/status/308/index.html create mode 100644 files/pt-br/web/http/status/400/index.html create mode 100644 files/pt-br/web/http/status/401/index.html create mode 100644 files/pt-br/web/http/status/402/index.html create mode 100644 files/pt-br/web/http/status/403/index.html create mode 100644 files/pt-br/web/http/status/404/index.html create mode 100644 files/pt-br/web/http/status/405/index.html create mode 100644 files/pt-br/web/http/status/406/index.html create mode 100644 files/pt-br/web/http/status/407/index.html create mode 100644 files/pt-br/web/http/status/408/index.html create mode 100644 files/pt-br/web/http/status/409/index.html create mode 100644 files/pt-br/web/http/status/410/index.html create mode 100644 files/pt-br/web/http/status/411/index.html create mode 100644 files/pt-br/web/http/status/412/index.html create mode 100644 files/pt-br/web/http/status/413/index.html create mode 100644 files/pt-br/web/http/status/414/index.html create mode 100644 files/pt-br/web/http/status/415/index.html create mode 100644 files/pt-br/web/http/status/416/index.html create mode 100644 files/pt-br/web/http/status/417/index.html create mode 100644 files/pt-br/web/http/status/418/index.html create mode 100644 files/pt-br/web/http/status/422/index.html create mode 100644 files/pt-br/web/http/status/425/index.html create mode 100644 files/pt-br/web/http/status/426/index.html create mode 100644 files/pt-br/web/http/status/428/index.html create mode 100644 files/pt-br/web/http/status/429/index.html create mode 100644 files/pt-br/web/http/status/431/index.html create mode 100644 files/pt-br/web/http/status/451/index.html create mode 100644 files/pt-br/web/http/status/500/index.html create mode 100644 files/pt-br/web/http/status/501/index.html create mode 100644 files/pt-br/web/http/status/502/index.html create mode 100644 files/pt-br/web/http/status/503/index.html create mode 100644 files/pt-br/web/http/status/504/index.html create mode 100644 files/pt-br/web/http/status/505/index.html create mode 100644 files/pt-br/web/http/status/506/index.html create mode 100644 files/pt-br/web/http/status/507/index.html create mode 100644 files/pt-br/web/http/status/508/index.html create mode 100644 files/pt-br/web/http/status/510/index.html create mode 100644 files/pt-br/web/http/status/511/index.html create mode 100644 files/pt-br/web/http/status/index.html create mode 100644 files/pt-br/web/index.html create mode 100644 files/pt-br/web/javascript/a_re-introduction_to_javascript/index.html create mode 100644 files/pt-br/web/javascript/about_javascript/index.html create mode 100644 files/pt-br/web/javascript/data_structures/index.html create mode 100644 files/pt-br/web/javascript/enumerabilidade_e_posse_de_propriedades/index.html create mode 100644 files/pt-br/web/javascript/equality_comparisons_and_sameness/index.html create mode 100644 files/pt-br/web/javascript/eventloop/index.html create mode 100644 files/pt-br/web/javascript/guide/closures/index.html create mode 100644 "files/pt-br/web/javascript/guide/cole\303\247\303\265es_chaveadas/index.html" create mode 100644 "files/pt-br/web/javascript/guide/declara\303\247\303\265es/index.html" create mode 100644 files/pt-br/web/javascript/guide/detalhes_do_modelo_do_objeto/index.html create mode 100644 files/pt-br/web/javascript/guide/expressions_and_operators/index.html create mode 100644 files/pt-br/web/javascript/guide/formatando_texto/index.html create mode 100644 "files/pt-br/web/javascript/guide/fun\303\247\303\265es/index.html" create mode 100644 files/pt-br/web/javascript/guide/igualdade/index.html create mode 100644 files/pt-br/web/javascript/guide/index.html create mode 100644 files/pt-br/web/javascript/guide/indexed_collections/index.html create mode 100644 files/pt-br/web/javascript/guide/inheritance_and_the_prototype_chain/index.html create mode 100644 files/pt-br/web/javascript/guide/introduction/index.html create mode 100644 files/pt-br/web/javascript/guide/iteratores_e_geradores/index.html create mode 100644 files/pt-br/web/javascript/guide/keyed_collections/index.html create mode 100644 files/pt-br/web/javascript/guide/lacos_e_iteracoes/index.html create mode 100644 files/pt-br/web/javascript/guide/meta_programming/index.html create mode 100644 "files/pt-br/web/javascript/guide/m\303\263dulos/index.html" create mode 100644 files/pt-br/web/javascript/guide/numeros_e_datas/index.html create mode 100644 files/pt-br/web/javascript/guide/regular_expressions/index.html create mode 100644 files/pt-br/web/javascript/guide/sintaxe_e_tipos/index.html create mode 100644 files/pt-br/web/javascript/guide/trabalhando_com_objetos/index.html create mode 100644 files/pt-br/web/javascript/guide/usando_promises/index.html create mode 100644 files/pt-br/web/javascript/guide/values,_variables,_and_literals/index.html create mode 100644 files/pt-br/web/javascript/index.html create mode 100644 files/pt-br/web/javascript/introduction_to_object-oriented_javascript/index.html create mode 100644 files/pt-br/web/javascript/javascript_technologies_overview/index.html create mode 100644 files/pt-br/web/javascript/language_resources/index.html create mode 100644 files/pt-br/web/javascript/memory_management/index.html create mode 100644 files/pt-br/web/javascript/new_in_javascript/1.1/index.html create mode 100644 files/pt-br/web/javascript/new_in_javascript/1.6/index.html create mode 100644 files/pt-br/web/javascript/new_in_javascript/1.7/index.html create mode 100644 files/pt-br/web/javascript/new_in_javascript/1.8.5/index.html create mode 100644 files/pt-br/web/javascript/new_in_javascript/ecmascript_5_support_in_mozilla/index.html create mode 100644 files/pt-br/web/javascript/new_in_javascript/index.html create mode 100644 files/pt-br/web/javascript/reference/about/index.html create mode 100644 files/pt-br/web/javascript/reference/classes/constructor/index.html create mode 100644 files/pt-br/web/javascript/reference/classes/extends/index.html create mode 100644 files/pt-br/web/javascript/reference/classes/index.html create mode 100644 files/pt-br/web/javascript/reference/classes/static/index.html create mode 100644 files/pt-br/web/javascript/reference/deprecated_and_obsolete_features/index.html create mode 100644 files/pt-br/web/javascript/reference/errors/cant_access_lexical_declaration_before_init/index.html create mode 100644 files/pt-br/web/javascript/reference/errors/cant_access_property/index.html create mode 100644 "files/pt-br/web/javascript/reference/errors/fata_par\303\252nteses_ap\303\263s_lista_argumento/index.html" create mode 100644 files/pt-br/web/javascript/reference/errors/fecha_chaves_esquecida_apos_lista_propriedades/index.html create mode 100644 files/pt-br/web/javascript/reference/errors/for-each-in_loops_are_deprecated/index.html create mode 100644 files/pt-br/web/javascript/reference/errors/illegal_character/index.html create mode 100644 files/pt-br/web/javascript/reference/errors/index.html create mode 100644 files/pt-br/web/javascript/reference/errors/invalid_array_length/index.html create mode 100644 files/pt-br/web/javascript/reference/errors/invalid_assignment_left-hand_side/index.html create mode 100644 files/pt-br/web/javascript/reference/errors/invalid_const_assignment/index.html create mode 100644 files/pt-br/web/javascript/reference/errors/invalid_date/index.html create mode 100644 files/pt-br/web/javascript/reference/errors/json_bad_parse/index.html create mode 100644 files/pt-br/web/javascript/reference/errors/missing_colon_after_property_id/index.html create mode 100644 files/pt-br/web/javascript/reference/errors/missing_curly_after_function_body/index.html create mode 100644 files/pt-br/web/javascript/reference/errors/missing_formal_parameter/index.html create mode 100644 files/pt-br/web/javascript/reference/errors/missing_semicolon_before_statement/index.html create mode 100644 files/pt-br/web/javascript/reference/errors/negative_repetition_count/index.html create mode 100644 files/pt-br/web/javascript/reference/errors/no_variable_name/index.html create mode 100644 files/pt-br/web/javascript/reference/errors/not_a_codepoint/index.html create mode 100644 files/pt-br/web/javascript/reference/errors/not_a_function/index.html create mode 100644 "files/pt-br/web/javascript/reference/errors/n\303\243o_definido/index.html" create mode 100644 "files/pt-br/web/javascript/reference/errors/n\303\243onomeado_func\303\243o_declara\303\247\303\243o/index.html" create mode 100644 files/pt-br/web/javascript/reference/errors/precision_range/index.html create mode 100644 files/pt-br/web/javascript/reference/errors/property_access_denied/index.html create mode 100644 files/pt-br/web/javascript/reference/errors/read-only/index.html create mode 100644 files/pt-br/web/javascript/reference/errors/redeclared_parameter/index.html create mode 100644 files/pt-br/web/javascript/reference/errors/stmt_after_return/index.html create mode 100644 files/pt-br/web/javascript/reference/errors/too_much_recursion/index.html create mode 100644 files/pt-br/web/javascript/reference/errors/undeclared_var/index.html create mode 100644 files/pt-br/web/javascript/reference/errors/undefined_prop/index.html create mode 100644 files/pt-br/web/javascript/reference/errors/unexpected_token/index.html create mode 100644 files/pt-br/web/javascript/reference/errors/unexpected_type/index.html create mode 100644 files/pt-br/web/javascript/reference/errors/unterminated_string_literal/index.html create mode 100644 files/pt-br/web/javascript/reference/functions/arguments/index.html create mode 100644 files/pt-br/web/javascript/reference/functions/arrow_functions/index.html create mode 100644 files/pt-br/web/javascript/reference/functions/definicoes_metodos/index.html create mode 100644 files/pt-br/web/javascript/reference/functions/get/index.html create mode 100644 files/pt-br/web/javascript/reference/functions/index.html create mode 100644 files/pt-br/web/javascript/reference/functions/parametros_predefinidos/index.html create mode 100644 files/pt-br/web/javascript/reference/functions/rest_parameters/index.html create mode 100644 files/pt-br/web/javascript/reference/functions/set/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/array/@@iterator/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/array/@@unscopables/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/array/concat/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/array/contains/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/array/copywithin/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/array/entries/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/array/every/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/array/fill/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/array/filtro/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/array/find/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/array/findindex/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/array/flat/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/array/flatmap/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/array/foreach/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/array/from/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/array/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/array/indexof/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/array/isarray/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/array/join/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/array/keys/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/array/lastindexof/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/array/length/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/array/map/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/array/observe/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/array/of/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/array/pop/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/array/prototype/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/array/push/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/array/reduce/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/array/reduceright/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/array/reverse/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/array/shift/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/array/slice/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/array/some/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/array/sort/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/array/splice/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/array/tolocalestring/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/array/tosource/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/array/tostring/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/array/unobserve/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/array/unshift/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/array/values/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/arraybuffer/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/asyncfunction/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/atomics/add/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/atomics/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/bigint/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/bigint/prototype/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/boolean/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/boolean/prototype/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/boolean/tosource/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/boolean/tostring/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/boolean/valueof/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/dataview/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/date/@@toprimitive/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/date/getdate/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/date/getday/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/date/getfullyear/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/date/gethours/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/date/getmilliseconds/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/date/getminutes/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/date/getmonth/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/date/getseconds/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/date/gettime/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/date/gettimezoneoffset/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/date/getutcdate/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/date/getutcday/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/date/getutcfullyear/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/date/getutchours/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/date/getutcmilliseconds/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/date/getutcminutes/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/date/getutcmonth/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/date/getutcseconds/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/date/getyear/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/date/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/date/now/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/date/parse/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/date/setdate/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/date/setfullyear/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/date/sethours/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/date/setmilliseconds/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/date/setminutes/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/date/setmonth/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/date/setseconds/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/date/settime/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/date/setutcdate/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/date/setutcfullyear/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/date/setutchours/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/date/setutcmilliseconds/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/date/setutcminutes/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/date/setutcmonth/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/date/setutcseconds/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/date/setyear/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/date/todatestring/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/date/togmtstring/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/date/toisostring/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/date/tojson/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/date/tolocaledatestring/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/date/tolocalestring/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/date/tolocaletimestring/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/date/tosource/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/date/tostring/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/date/totimestring/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/date/toutcstring/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/date/utc/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/date/valueof/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/decodeuri/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/decodeuricomponent/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/encodeuri/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/encodeuricomponent/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/error/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/error/tosource/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/error/tostring/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/escape/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/eval/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/evalerror/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/float32array/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/float64array/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/function/apply/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/function/arguments/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/function/arity/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/function/bind/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/function/call/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/function/caller/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/function/displayname/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/function/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/function/isgenerator/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/function/length/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/function/name/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/function/prototype/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/function/tosource/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/function/tostring/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/generator/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/globalthis/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/infinity/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/int16array/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/internalerror/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/intl/datetimeformat/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/intl/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/intl/numberformat/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/intl/numberformat/prototype/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/intl/relativetimeformat/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/isfinite/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/isnan/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/iterador/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/json/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/json/parse/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/json/stringify/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/map/clear/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/map/delete/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/map/entries/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/map/foreach/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/map/get/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/map/has/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/map/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/map/keys/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/map/prototype/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/map/set/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/map/size/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/map/values/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/abs/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/acos/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/acosh/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/asin/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/asinh/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/atan/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/atan2/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/atanh/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/cbrt/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/ceil/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/clz32/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/cos/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/cosh/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/e/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/exp/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/expm1/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/floor/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/hypot/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/ln10/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/ln2/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/log/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/log10/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/log10e/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/log1p/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/log2/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/log2e/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/max/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/min/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/pi/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/pow/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/random/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/round/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/sign/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/sin/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/sinh/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/sqrt/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/sqrt1_2/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/sqrt2/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/tan/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/tanh/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/math/trunc/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/nan/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/null/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/number/epsilon/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/number/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/number/isfinite/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/number/isinteger/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/number/isnan/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/number/issafeinteger/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/number/max_safe_integer/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/number/max_value/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/number/min_safe_integer/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/number/min_value/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/number/nan/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/number/negative_infinity/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/number/parsefloat/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/number/parseint/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/number/positive_infinity/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/number/prototype/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/number/toexponential/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/number/tofixed/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/number/tolocalestring/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/number/toprecision/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/number/tosource/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/number/tostring/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/number/valueof/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/object/__definegetter__/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/object/__definesetter__/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/object/__lookupgetter__/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/object/__lookupsetter__/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/object/assign/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/object/constructor/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/object/count/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/object/create/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/object/defineproperties/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/object/defineproperty/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/object/entries/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/object/freeze/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/object/fromentries/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/object/getownpropertydescriptor/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/object/getownpropertydescriptors/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/object/getownpropertynames/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/object/getownpropertysymbols/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/object/getprototypeof/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/object/hasownproperty/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/object/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/object/is/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/object/isextensible/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/object/isfrozen/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/object/isprototypeof/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/object/issealed/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/object/keys/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/object/observe/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/object/preventextensions/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/object/propertyisenumerable/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/object/proto/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/object/prototype/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/object/seal/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/object/setprototypeof/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/object/tolocalestring/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/object/tosource/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/object/tostring/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/object/valueof/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/object/values/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/parsefloat/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/parseint/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/promise/all/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/promise/allsettled/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/promise/catch/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/promise/finally/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/promise/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/promise/prototype/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/promise/race/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/promise/reject/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/promise/resolve/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/promise/then/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/proxy/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/referenceerror/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/reflect/apply/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/reflect/construct/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/reflect/defineproperty/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/reflect/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/reflect/set/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/regexp/compile/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/regexp/exec/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/regexp/ignorecase/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/regexp/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/regexp/sticky/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/regexp/test/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/set/add/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/set/clear/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/set/delete/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/set/entries/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/set/has/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/set/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/set/prototype/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/set/values/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/string/@@iterator/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/string/anchor/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/string/big/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/string/blink/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/string/bold/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/string/charat/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/string/charcodeat/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/string/codepointat/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/string/concat/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/string/endswith/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/string/fixed/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/string/fontcolor/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/string/fontsize/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/string/fromcharcode/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/string/fromcodepoint/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/string/includes/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/string/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/string/indexof/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/string/italics/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/string/lastindexof/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/string/length/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/string/link/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/string/localecompare/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/string/match/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/string/matchall/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/string/normalize/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/string/padend/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/string/padstart/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/string/prototype/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/string/raw/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/string/repeat/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/string/replace/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/string/replaceall/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/string/search/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/string/slice/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/string/small/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/string/split/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/string/startswith/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/string/strike/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/string/sub/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/string/substr/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/string/substring/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/string/sup/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/string/tolocalelowercase/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/string/tolocaleuppercase/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/string/tolowercase/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/string/tosource/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/string/tostring/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/string/touppercase/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/string/trim/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/string/trimend/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/string/trimstart/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/string/valueof/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/symbol/asynciterator/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/symbol/description/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/symbol/hasinstance/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/symbol/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/symbol/isconcatspreadable/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/symbol/iterator/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/symbol/match/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/symbol/matchall/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/symbol/replace/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/symbol/search/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/symbol/species/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/symbol/split/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/symbol/toprimitive/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/symbol/tostringtag/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/symbol/unscopables/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/typedarray/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/typedarray/sort/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/typeerror/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/undefined/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/unescape/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/uneval/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/weakmap/delete/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/weakmap/get/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/weakmap/has/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/weakmap/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/weakmap/prototype/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/weakmap/set/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/weakset/index.html create mode 100644 files/pt-br/web/javascript/reference/index.html create mode 100644 files/pt-br/web/javascript/reference/iteration_protocols/index.html create mode 100644 files/pt-br/web/javascript/reference/lexical_grammar/index.html create mode 100644 files/pt-br/web/javascript/reference/operators/arithmetic_operators/index.html create mode 100644 files/pt-br/web/javascript/reference/operators/array_comprehensions/index.html create mode 100644 files/pt-br/web/javascript/reference/operators/async_function/index.html create mode 100644 files/pt-br/web/javascript/reference/operators/atribuicao_via_desestruturacao/index.html create mode 100644 files/pt-br/web/javascript/reference/operators/await/index.html create mode 100644 files/pt-br/web/javascript/reference/operators/bitwise_operators/index.html create mode 100644 files/pt-br/web/javascript/reference/operators/bitwise_xor/index.html create mode 100644 files/pt-br/web/javascript/reference/operators/class/index.html create mode 100644 files/pt-br/web/javascript/reference/operators/expression_closures/index.html create mode 100644 files/pt-br/web/javascript/reference/operators/function/index.html create mode 100644 files/pt-br/web/javascript/reference/operators/function_star_/index.html create mode 100644 files/pt-br/web/javascript/reference/operators/generator_comprehensions/index.html create mode 100644 files/pt-br/web/javascript/reference/operators/grouping/index.html create mode 100644 files/pt-br/web/javascript/reference/operators/in/index.html create mode 100644 files/pt-br/web/javascript/reference/operators/index.html create mode 100644 files/pt-br/web/javascript/reference/operators/inicializador_objeto/index.html create mode 100644 files/pt-br/web/javascript/reference/operators/instanceof/index.html create mode 100644 files/pt-br/web/javascript/reference/operators/new.target/index.html create mode 100644 files/pt-br/web/javascript/reference/operators/new/index.html create mode 100644 files/pt-br/web/javascript/reference/operators/operador_condicional/index.html create mode 100644 files/pt-br/web/javascript/reference/operators/operador_de_coalescencia_nula/index.html create mode 100644 files/pt-br/web/javascript/reference/operators/operador_virgula/index.html create mode 100644 "files/pt-br/web/javascript/reference/operators/operadores_de_compara\303\247\303\243o/index.html" create mode 100644 files/pt-br/web/javascript/reference/operators/operadores_logicos/index.html create mode 100644 files/pt-br/web/javascript/reference/operators/operator_precedence/index.html create mode 100644 files/pt-br/web/javascript/reference/operators/optional_chaining/index.html create mode 100644 files/pt-br/web/javascript/reference/operators/pipeline_operator/index.html create mode 100644 files/pt-br/web/javascript/reference/operators/property_accessors/index.html create mode 100644 files/pt-br/web/javascript/reference/operators/spread_operator/index.html create mode 100644 files/pt-br/web/javascript/reference/operators/spread_syntax/index.html create mode 100644 files/pt-br/web/javascript/reference/operators/super/index.html create mode 100644 files/pt-br/web/javascript/reference/operators/this/index.html create mode 100644 files/pt-br/web/javascript/reference/operators/typeof/index.html create mode 100644 files/pt-br/web/javascript/reference/operators/void/index.html create mode 100644 files/pt-br/web/javascript/reference/operators/yield/index.html create mode 100644 files/pt-br/web/javascript/reference/operators/yield_star_/index.html create mode 100644 files/pt-br/web/javascript/reference/statements/block/index.html create mode 100644 files/pt-br/web/javascript/reference/statements/break/index.html create mode 100644 files/pt-br/web/javascript/reference/statements/class/index.html create mode 100644 files/pt-br/web/javascript/reference/statements/const/index.html create mode 100644 files/pt-br/web/javascript/reference/statements/continue/index.html create mode 100644 files/pt-br/web/javascript/reference/statements/debugger/index.html create mode 100644 files/pt-br/web/javascript/reference/statements/default/index.html create mode 100644 files/pt-br/web/javascript/reference/statements/do...while/index.html create mode 100644 files/pt-br/web/javascript/reference/statements/empty/index.html create mode 100644 files/pt-br/web/javascript/reference/statements/export/index.html create mode 100644 files/pt-br/web/javascript/reference/statements/for-await...of/index.html create mode 100644 files/pt-br/web/javascript/reference/statements/for...in/index.html create mode 100644 files/pt-br/web/javascript/reference/statements/for...of/index.html create mode 100644 files/pt-br/web/javascript/reference/statements/for/index.html create mode 100644 files/pt-br/web/javascript/reference/statements/for_each...in/index.html create mode 100644 files/pt-br/web/javascript/reference/statements/funcoes_assincronas/index.html create mode 100644 files/pt-br/web/javascript/reference/statements/function/index.html create mode 100644 files/pt-br/web/javascript/reference/statements/function_star_/index.html create mode 100644 files/pt-br/web/javascript/reference/statements/if...else/index.html create mode 100644 files/pt-br/web/javascript/reference/statements/import.meta/index.html create mode 100644 files/pt-br/web/javascript/reference/statements/import/index.html create mode 100644 files/pt-br/web/javascript/reference/statements/index.html create mode 100644 files/pt-br/web/javascript/reference/statements/label/index.html create mode 100644 files/pt-br/web/javascript/reference/statements/let/index.html create mode 100644 files/pt-br/web/javascript/reference/statements/return/index.html create mode 100644 files/pt-br/web/javascript/reference/statements/switch/index.html create mode 100644 files/pt-br/web/javascript/reference/statements/throw/index.html create mode 100644 files/pt-br/web/javascript/reference/statements/try...catch/index.html create mode 100644 files/pt-br/web/javascript/reference/statements/var/index.html create mode 100644 files/pt-br/web/javascript/reference/statements/while/index.html create mode 100644 files/pt-br/web/javascript/reference/statements/with/index.html create mode 100644 files/pt-br/web/javascript/reference/strict_mode/index.html create mode 100644 files/pt-br/web/javascript/reference/template_strings/index.html create mode 100644 files/pt-br/web/javascript/suporte_ao_ecmascript_6_na_mozilla/index.html create mode 100644 files/pt-br/web/javascript/typed_arrays/index.html create mode 100644 files/pt-br/web/manifest/index.html create mode 100644 files/pt-br/web/mathml/element/index.html create mode 100644 files/pt-br/web/mathml/element/math/index.html create mode 100644 files/pt-br/web/mathml/exemplos/index.html create mode 100644 files/pt-br/web/mathml/index.html create mode 100644 files/pt-br/web/performance/caminho_de_renderizacao_critico/index.html create mode 100644 files/pt-br/web/performance/index.html create mode 100644 files/pt-br/web/progressive_web_apps/index.html create mode 100644 "files/pt-br/web/progressive_web_apps/introdu\303\247\303\243o/index.html" create mode 100644 files/pt-br/web/reference/api/index.html create mode 100644 files/pt-br/web/reference/index.html create mode 100644 "files/pt-br/web/security/b\303\241sico_de_seguran\303\247a_da_informa\303\247\303\243o/confidencialidade,_integridade,_e_disponibilidade/index.html" create mode 100644 "files/pt-br/web/security/b\303\241sico_de_seguran\303\247a_da_informa\303\247\303\243o/index.html" create mode 100644 "files/pt-br/web/security/b\303\241sico_de_seguran\303\247a_da_informa\303\247\303\243o/seguranca_tcp_ip/index.html" create mode 100644 files/pt-br/web/security/index.html create mode 100644 files/pt-br/web/security/securing_your_site/index.html create mode 100644 files/pt-br/web/security/securing_your_site/turning_off_form_autocompletion/index.html create mode 100644 files/pt-br/web/svg/applying_svg_effects_to_html_content/index.html create mode 100644 files/pt-br/web/svg/attribute/class/index.html create mode 100644 files/pt-br/web/svg/attribute/contentstyletype/index.html create mode 100644 files/pt-br/web/svg/attribute/fill/index.html create mode 100644 files/pt-br/web/svg/attribute/index.html create mode 100644 files/pt-br/web/svg/attribute/keytimes/index.html create mode 100644 files/pt-br/web/svg/attribute/preserveaspectratio/index.html create mode 100644 files/pt-br/web/svg/attribute/stroke-dashoffset/index.html create mode 100644 files/pt-br/web/svg/attribute/stroke/index.html create mode 100644 files/pt-br/web/svg/attribute/style/index.html create mode 100644 files/pt-br/web/svg/attribute/version/index.html create mode 100644 files/pt-br/web/svg/attribute/viewbox/index.html create mode 100644 files/pt-br/web/svg/attribute/width/index.html create mode 100644 files/pt-br/web/svg/compatibility_sources/index.html create mode 100644 files/pt-br/web/svg/content_type/index.html create mode 100644 files/pt-br/web/svg/element/a/index.html create mode 100644 files/pt-br/web/svg/element/altglyph/index.html create mode 100644 files/pt-br/web/svg/element/altglyphdef/index.html create mode 100644 files/pt-br/web/svg/element/altglyphitem/index.html create mode 100644 files/pt-br/web/svg/element/animate/index.html create mode 100644 files/pt-br/web/svg/element/animatecolor/index.html create mode 100644 files/pt-br/web/svg/element/animatemotion/index.html create mode 100644 files/pt-br/web/svg/element/animatetransform/index.html create mode 100644 files/pt-br/web/svg/element/circle/index.html create mode 100644 files/pt-br/web/svg/element/color-profile/index.html create mode 100644 files/pt-br/web/svg/element/defs/index.html create mode 100644 files/pt-br/web/svg/element/desc/index.html create mode 100644 files/pt-br/web/svg/element/ellipse/index.html create mode 100644 files/pt-br/web/svg/element/filter/index.html create mode 100644 files/pt-br/web/svg/element/g/index.html create mode 100644 files/pt-br/web/svg/element/glyph/index.html create mode 100644 files/pt-br/web/svg/element/glyphref/index.html create mode 100644 files/pt-br/web/svg/element/hkern/index.html create mode 100644 files/pt-br/web/svg/element/image/index.html create mode 100644 files/pt-br/web/svg/element/index.html create mode 100644 files/pt-br/web/svg/element/line/index.html create mode 100644 files/pt-br/web/svg/element/lineargradient/index.html create mode 100644 files/pt-br/web/svg/element/marker/index.html create mode 100644 files/pt-br/web/svg/element/mask/index.html create mode 100644 files/pt-br/web/svg/element/metadata/index.html create mode 100644 files/pt-br/web/svg/element/missing-glyph/index.html create mode 100644 files/pt-br/web/svg/element/mpath/index.html create mode 100644 files/pt-br/web/svg/element/path/index.html create mode 100644 files/pt-br/web/svg/element/pattern/index.html create mode 100644 files/pt-br/web/svg/element/polygon/index.html create mode 100644 files/pt-br/web/svg/element/polyline/index.html create mode 100644 files/pt-br/web/svg/element/radialgradient/index.html create mode 100644 files/pt-br/web/svg/element/rect/index.html create mode 100644 files/pt-br/web/svg/element/script/index.html create mode 100644 files/pt-br/web/svg/element/set/index.html create mode 100644 files/pt-br/web/svg/element/stop/index.html create mode 100644 files/pt-br/web/svg/element/style/index.html create mode 100644 files/pt-br/web/svg/element/svg/index.html create mode 100644 files/pt-br/web/svg/element/switch/index.html create mode 100644 files/pt-br/web/svg/element/symbol/index.html create mode 100644 files/pt-br/web/svg/element/text/index.html create mode 100644 files/pt-br/web/svg/element/textpath/index.html create mode 100644 files/pt-br/web/svg/element/title/index.html create mode 100644 files/pt-br/web/svg/element/tref/index.html create mode 100644 files/pt-br/web/svg/element/tspan/index.html create mode 100644 files/pt-br/web/svg/element/use/index.html create mode 100644 files/pt-br/web/svg/element/view/index.html create mode 100644 files/pt-br/web/svg/element/vkern/index.html create mode 100644 files/pt-br/web/svg/index.html create mode 100644 files/pt-br/web/svg/intensivo_de_namespaces/index.html create mode 100644 files/pt-br/web/svg/tutorial/index.html create mode 100644 files/pt-br/web/svg/tutorial/introduction/index.html create mode 100644 files/pt-br/web/tutoriais/index.html create mode 100644 files/pt-br/web/web_components/index.html create mode 100644 files/pt-br/web/web_components/usando_custom_elements/index.html create mode 100644 files/pt-br/web/xslt/index.html (limited to 'files/pt-br/web') diff --git a/files/pt-br/web/accessibility/aria/aria_guides/index.html b/files/pt-br/web/accessibility/aria/aria_guides/index.html new file mode 100644 index 0000000000..698295b8d5 --- /dev/null +++ b/files/pt-br/web/accessibility/aria/aria_guides/index.html @@ -0,0 +1,27 @@ +--- +title: ARIA guides +slug: Web/Accessibility/ARIA/ARIA_Guides +tags: + - ARIA + - Accessibility +translation_of: Web/Accessibility/ARIA/ARIA_Guides +--- +

Aplicações de internet ricas acessíveis (ARIA) define caminhos para fazer a web mais acessível para pessoas com deficiências. Umas poucas linhas guias para seguirem que garante melhor acessibilidade, como usar drag and drop para colocações de widgets.

+ + diff --git a/files/pt-br/web/accessibility/aria/aria_techniques/index.html b/files/pt-br/web/accessibility/aria/aria_techniques/index.html new file mode 100644 index 0000000000..446c2132d4 --- /dev/null +++ b/files/pt-br/web/accessibility/aria/aria_techniques/index.html @@ -0,0 +1,194 @@ +--- +title: ARIA techniques +slug: Web/Accessibility/ARIA/ARIA_Techniques +tags: + - ARIA + - Acessibilidade + - Precisa de Tradução + - Referencia + - TopicStub + - Visão Geral +translation_of: Web/Accessibility/ARIA/ARIA_Techniques +--- +

O ARIA define as semânticas que podem ser aplicadas aos elementos, e são divididas em funções (definindo um tipo de elemento da interface do usuário) e estados e propriedades que são suportados por uma função. Os autores devem atribuir uma função ARIA e os estados e propriedades apropriados a um elemento durante seu ciclo de vida, a menos que o elemento já possua semântica ARIA apropriada (através do uso de um elemento HTML apropriado). A adição de semântica ARIA apenas expõe informações extras para a API de acessibilidade de um navegador e não afeta o DOM de uma página.

+ +

Funções

+ +

Funções de widget

+ + + +

Funções compostas

+ +

As técnicas abaixo descrevem cada função composta, bem como suas funções filho obrigatórias e opcionais.

+ + + +

Funções da estrutura de documento

+ + + +

Funções de ponto de referência

+ + + +

Funções de regiões ativa

+ + + +

Funções de janela

+ + + +

Estados e propriedades

+ +

Atributos de widget

+ + + +

Atributos da região ativa

+ + + +

Atributos de drag & drop

+ + + +

Atributos de relacionamento

+ + + +

Propriedades específicas do MicrosoftEdge

+ + diff --git a/files/pt-br/web/accessibility/aria/aria_techniques/usando_o_atributo_aria-labelledby/index.html b/files/pt-br/web/accessibility/aria/aria_techniques/usando_o_atributo_aria-labelledby/index.html new file mode 100644 index 0000000000..cd7cb90bb9 --- /dev/null +++ b/files/pt-br/web/accessibility/aria/aria_techniques/usando_o_atributo_aria-labelledby/index.html @@ -0,0 +1,158 @@ +--- +title: Usando o atributo aria-labelledby +slug: Web/Accessibility/ARIA/ARIA_Techniques/Usando_o_atributo_aria-labelledby +tags: + - ARIA + - Acessibilidade + - PrecisaDeConteúdo +translation_of: Web/Accessibility/ARIA/ARIA_Techniques/Using_the_aria-labelledby_attribute +--- +

Descrição

+ +

Essa técnica demonstra como usar o atributo aria-labelledby.

+ +

O atributo aria-labelledby é usado para indicar os IDs de elementos que são os rótulos para o objeto. É usado para estabelecer uma relação entre widgets ou grupos e suas labels. Usuários de tecnologias assistivas como leitores de telas navegam tipicamente uma página através de TABs entre as áreas da tela. Se uma label não está associada com um elemento input, widget ou grupo, não será legível por leitor de tela.

+ +

aria-labelledby é muito similar ao aria-describedby: uma label descreve a essência de um objeto, enquanto uma descrição prove mais informação que o usuário pode precisar.

+ +

O atributo aria-labelledby não é usado somente para elementos de formulário; é também usado para associar texto estático com widgets, grupos de elementos, painéis, regiões que tem um cabeçalho, definições e mais. A seção {{ anch("Exemplos") }} abaixo fornece mais informação sobre como usar os atributos nesses casos.

+ +

aria-labelledby podem ser usadas em conjunto com o elemento {{ HTMLElement("label") }} (usando o atributo for) para melhorar a compatibilidade com user agents que não suportam ainda ARIA.

+ +

Esse atributo pode ser usado com qualquer elemento HTML de formulário; não é limitado a elementos que tem uma role ARIA atribuída.

+ +

Value

+ +

Uma lista de IDs do elemento separada por espaços

+ +

Possíveis efeitos em user agents e tecnologias assistivas 

+ +

Quando ambos aria-labelledby e aria-label são usados, user agents dão precedência ao aria-labelledby quando computam o nome da propriedade acessível.

+ +
Nota: Opinões podem diferir em como as tecnologias assistivas devem manipular essa técnica. A informação fornecida acima é uma dessas opiniões e portanto não normativa.
+ +

Exemplos

+ +

Exemplo 1: Múltiplas Labels

+ +

No exemplo abaixo, cada campo input é rotulado por tanto por seu próprio rótulo individual como pelo rótulo do grupo:

+ +
<div id="billing">Endereço de Cobrança</div>
+
+<div>
+    <div id="name">Nome</div>
+    <input type="text" aria-labelledby="name billing"/>
+</div>
+<div>
+    <div id="address">Endereço</div>
+    <input type="text" aria-labelledby="address billing"/>
+</div>
+
+ +

Exemplo 2: Associando Cabeçalhos com Regiões

+ +

No exemplo abaixo, elementos de cabeçalho estão associados com o conteúdo que eles seguem. Note que a região sendo referenciada é a que contem o cabeçalho.

+ +
<div role="main" aria-labelledby="foo">
+   <h1 id="foo">Incêndios selvagens se espalham por San Diego Hills</h1>
+   Fortes ventos expandem o fogo inflamado pelas altas temperaturas ...
+</div>
+
+ +

Exemplo 3: Radio Groups

+ +

No exemplo abaixo,  o container de um radiogroup  é associado com suas labels usando o atributo aria-labelledby:

+ +
<div id="radio_label">Meu radio label</div>
+<ul role="radiogroup" aria-labelledby="radio_label">
+    <li role="radio">Item #1</li>
+    <li role="radio">Item #2</li>
+    <li role="radio">Item #3</li>
+</ul>
+
+ +

Exemplo 4: Dialog Label

+ +

No exemplo abaixo, o elemento cabeçalho que rotula o dialog é referenciado pelo atributo aria-labelledby:

+ +
<div role="dialog" aria-labelledby="dialogheader">
+    <h2 id="dialogheader">Escolha um Arquivo</h2>
+    ... Conteúdo do Dialog
+</div>
+
+ +

Exemplo 5: Definição Inline

+ +

No exemplo abaixo, a definição de um termo que é descrita no fluxo natural da narrativa é associada com o próprio termo usando o atributo aria-labelledby:

+ +
<p>O médico explicou que tinha sido um <dfn id="placebo">placebo</dfn>, ou <span role="definition" aria-labelledby="placebo">
+ou a uma preparação mais inerte prescrito para o alívio mental do paciente do que por seu efeito real sobre um distúrbio.</span>
+</p>
+
+ +

Exemplo 6: Definições de Listas

+ +

No exemplo abaixo, as definições numa lista formal de definições são associadas com os termos que eles definem usando o atributo aria-labelledby:

+ +
<dl>
+    <dt id="anathema">anátema</dt>
+    <dd role="definition" aria-labelledby="anathema">uma proibição ou maldição solenemente pronunciada pela autoridade eclesiástica
+                                                     e acompanhada por excomunhão</dd>
+    <dd role="definition" aria-labelledby="anathema">uma vigorosa denúncia</dd>
+
+    <dt id="homily">homilia</dt>
+    <dd role="definition" aria-labelledby="homily">um sermão usualmente curto</dd>
+    <dd role="definition" aria-labelledby="homily">uma leitura ou discurso sobre ou de um tema moral</dd>
+
+</dl>
+
+ +

Exemplo 7: Menus

+ +

No exemplo abaixo, um menu popup é associado com sua label usando o atributo aria-labelledby:

+ +
<div role="menubar">
+    <div role="menuitem" aria-haspopup="true" id="fileMenu">Arquivo</div>
+    <div role="menu" aria-labelledby="fileMenu">
+        <div role="menuitem">Abrir</div>
+        <div role="menuitem">Salvar</div>
+        <div role="menuitem">Salvar como ...</div>
+        ...
+    </div>
+    ...
+</div>
+
+ +

Exemplos Funcionais:

+ + + +

Notas 

+ +

O mapeamento mais comum de uma + API de acessibilidade +  para um rótulo é a propriedade acessível name

+ +

Usado pelas regras ARIA

+ +

todos os elementos de markup base

+ +

Técnicas ARIA relacionadas

+ + + +

Compatibilidade

+ +

TBD: Adicionar informação de suporte para combinações de produto UA e AT

+ +

Recursos Adicionais

+ + diff --git a/files/pt-br/web/accessibility/aria/aria_techniques/usando_o_atributo_aria-required/index.html b/files/pt-br/web/accessibility/aria/aria_techniques/usando_o_atributo_aria-required/index.html new file mode 100644 index 0000000000..e93611b182 --- /dev/null +++ b/files/pt-br/web/accessibility/aria/aria_techniques/usando_o_atributo_aria-required/index.html @@ -0,0 +1,83 @@ +--- +title: Usando o atributo aria-required +slug: Web/Accessibility/ARIA/ARIA_Techniques/Usando_o_atributo_aria-required +tags: + - ARIA + - Acessibilidade +translation_of: Web/Accessibility/ARIA/ARIA_Techniques/Using_the_aria-required_attribute +--- +
+
+

Descrição

+ +

O atributo aria-required é usado para indicar que a entrada do usuário é obrigatória em um elemento antes que um formulário possa ser enviado. Este atributo pode ser usado com qualquer elemento de formulário HTML típico; não se limita a elementos que têm uma  role atribuída.

+ +

{{ HTMLVersionInline("5") }} agora tem o atributo required, mas aria-required ainda é útil para agentes de usuário que não suportam ainda HTML5.

+ +

Valor

+ +

true ou false (Padrão: false)

+ +

Possíveis efeitos nos agentes de usuários e tecnologia assistiva 

+ +

Os leitores de tela devem anunciar o campo como obrigatório.

+ +

Observe que esse atributo não alterará automaticamente a apresentação do campo.

+ +
Nota: Opiniões podem diferir em como a tecnologia assistiva deve lidar com esta técnica. A informação fornecida acima é uma dessas opiniões e, portanto, não é normativa.
+ +

Exemplos

+ +

Exemplo 1: Um simples formulário

+ +

 

+ +
 <form action="post">
+     <label for="firstName">First name:</label>
+     <input id="firstName" type="text" aria-required="true" />
+     <br/>
+     <label for="lastName">Last name:</label>
+     <input id="lastName" type="text" aria-required="true" />
+     <br/>
+     <label for="streetAddress">Street address:</label>
+     <input id="streetAddress" type="text" />
+ </form>
+
+ +

Exemplos de trabalho:

+ +

Exemplo de Tooltip  (inclui o uso do atributo aria-required)

+ +

Notas 

+ +

Usado em ARIA roles

+ +
    +
  • Combobox
  • +
  • Gridcell
  • +
  • Listbox
  • +
  • Radiogroup
  • +
  • Spinbutton
  • +
  • Textbox
  • +
  • Tree
  • +
+ +

Técnicas relacionadas com ARIA

+ + + +

Compatibilidade

+ +

TBD: Add support information for common UA and AT product combinations

+ +

Recursos adicionais

+ + +
+
diff --git a/files/pt-br/web/accessibility/aria/aria_techniques/usando_o_slider_role/index.html b/files/pt-br/web/accessibility/aria/aria_techniques/usando_o_slider_role/index.html new file mode 100644 index 0000000000..18532f5f25 --- /dev/null +++ b/files/pt-br/web/accessibility/aria/aria_techniques/usando_o_slider_role/index.html @@ -0,0 +1,125 @@ +--- +title: Usando o slider role +slug: Web/Accessibility/ARIA/ARIA_Techniques/Usando_o_slider_role +translation_of: Web/Accessibility/ARIA/ARIA_Techniques/Using_the_slider_role +--- +

Descrição

+ +

Essa técnica demosntrará como usar o slider role. 

+ +

The slider role is used for markup that allows a user to select a value from within a given range. The slider role is assigned to the "thumb," the control that is adjusted to change the value. Typically, another element is styled to visually represent the range of possible valued, and the thumb positioned visually to represent the value within that range. As the user interacts with the thumb, the application must programmatically adjust the slider's aria-valuenow (and possible aria-valuetext) attribute to reflect the current value. See the {{ anch("Examples") }} section below for more information.

+ +

Keyboard And Focus

+ +

The slider should be keyboard focusable and operable. When the user tabs focus to the slider, it should land on the thumb: the control a mouse user would drag. Arrow keys should operate as follows (localization for right-to-left languages should reverse the direction of the arrows):

+ + + + + + + + + + + + + + + + + + + + + + +
Tecla(s)Ação
Setas para direita e para cima Incrementa o valor selecionado
Setas para esquerda e para baixoDecrementa o valor selecionado
Page Up and Page DownOptionally increase and decrease the value by a set amount (e.g. by 10 on a range from 0 to 100)
+ +

Possible effects on user agents and assistive technology 

+ +

 

+ +
Note: Opinions may differ on how assistive technology should handle this technique. The information provided above is one of those opinions and therefore not normative.
+ +

Examplos

+ +

Examplo 1: Escala numérica simples

+ +

In the example below, a simple slider is used to select a value between 1 and 100. The current volume is 50. The application will programmatically update the value of aria-valuenow in response to user input.

+ +
<label for="fader">Volume</label>
+<input type="range"
+  id="fader"
+  min="1"
+  max="100"
+  value="50"
+  step="1"
+  aria-valuemin="1"
+  aria-valuemax="100"
+  aria-valuenow="50"
+  oninput="outputUpdate(value)">
+<output for="fader" id="volume">50</output>
+
+ +

The following code snippet allows you to return the output as it is updated by user input:

+ +
function outputUpdate(vol) {
+  document.querySelector('#volume').value = vol;
+}
+
+ +

Examplo 2: Valores de texto

+ +

Sometimes, a slider is used to choose a value that is not, semantically, a number. In these cases, the aria-valuetext attribute is used to provide the appropriate text name for the currently selected value. In the example below, the slider is used to select a day of the week.

+ +
<label for="day-handle">Days</label>
+<div class="day-slider">
+  <div id="day-handle" class="day-slider-handle" role="slider" aria-labelledby="day-handle"
+     aria-valuemin="1"
+     aria-valuemax="7"
+     aria-valuenow="2"
+     aria-valuetext="Monday">
+ </div>
+</div>
+
+ +

The code snippet below shows a function that responds to user input and updates the aria-valuenow and aria-valuetext attributes:

+ +
var dayNames = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
+var updateSlider = function (newValue) {
+    var handle = document.getElementById("day-handle");
+    handle.setAttribute("aria-valuenow", newValue.toString());
+    handle.setAttribute("aria-valuetext", dayNames[newValue]);
+};
+
+ +

Working Examples:

+ + + +

Notas 

+ +

Atributos ARIA usados

+ + + + + +

Compatibility

+ +

TBD: Add support information for common UA and AT product combinations

+ +

Recursos Adicionais

+ + diff --git a/files/pt-br/web/accessibility/aria/aria_techniques/using_the_aria-describedby_attribute/index.html b/files/pt-br/web/accessibility/aria/aria_techniques/using_the_aria-describedby_attribute/index.html new file mode 100644 index 0000000000..c2c258dae7 --- /dev/null +++ b/files/pt-br/web/accessibility/aria/aria_techniques/using_the_aria-describedby_attribute/index.html @@ -0,0 +1,87 @@ +--- +title: Usando o atributo aria-describedby +slug: Web/Accessibility/ARIA/ARIA_Techniques/Using_the_aria-describedby_attribute +tags: + - ARIA + - Acessibilidade + - atributo +translation_of: Web/Accessibility/ARIA/ARIA_Techniques/Using_the_aria-describedby_attribute +--- +

Descrição

+ +

O atributo aria-describedby é usado para indicar os IDs dos elementos que descrevem o objeto. Isso é usado para estabelecer um relacionamento entre widgets ou grupos e texto que descrevem eles. Isso é muito similar ao aria-labelledby: um rótulo (label) que descreve a essência de um objeto, enquanto a descrição fornece mais informação do que o usuário pode precisar.

+ +

O atributo aria-describedby não é usado apenas para elementos de formulário; ele também é usado para associar texto estático com widgets, grupos de elementos, paineis, regiões que tem um cabeçalho, definiões e mais. A seção abaixo fornece mais informação sobre como usar o atributo nesses casos.

+ +

O atributo pode ser usando em qualquer elemento típico de um formulário HTML; isso não é limitado a elementos que tem um role ARIA atribuído.

+ +

Valor

+ +

uma lista de IDs de elementos separados por um espaço

+ +

Efeitos possíveis em user agents e tecnologia assistiva

+ +
Nota: Opiniões podem difererir em como a tecnologia assistiva deve lidar com essa técnica. A informação fornecida abaixo é uma dessas opiniões e, portanto, não normativa.
+ +

Exemplos

+ +

Exemplo 1: Descrições do ponto de referência do aplicativo

+ +

No exemplo abaixo, um parágrafo introdutório descreve uma aplicação de calendário. O aria-describedby é usado para associar o parágrado com o container da aplicação.

+ +
<div role="application" aria-labelledby="calendar" aria-describedby="info">
+    <h1 id="calendar">Calendário</h1>
+    <p id="info">
+        Esse calendário mostra a data do jogo do Boston Red Sox.
+    </p>
+    <div role="grid">
+        ...
+    </div>
+</div>
+
+ +

Exemplo 2: Um botão de fechar

+ +

No exemplo abaixo, um link que funciona como um botão de "fechar" num diálogo é descrito em outro lugar do documento.O atributo aria-describedby é usado para associar a descrição com o link.

+ +
<button aria-label="Close" aria-describedby="descriptionClose"
+    onclick="myDialog.close()">X</button>
+
+...
+
+<div id="descriptionClose">Fechar esta janela irá descartar qualquer informação inserida e
+retornará você para a página principal</div>
+
+ +

Exemplos funcionando:

+ + + +

Notas

+ + + +

Usado pelos roles de ARIA

+ +

todos os elementos do markup base

+ +

Técnicas relacionadas ao ARIA

+ + + +

Compatibilidade

+ +

Ainda não foi definido: Adicionar suporte a informação comum de combinações de produtos UA e AT

+ +

Recursos adicionais

+ + diff --git a/files/pt-br/web/accessibility/aria/aria_techniques/using_the_aria-label_attribute/index.html b/files/pt-br/web/accessibility/aria/aria_techniques/using_the_aria-label_attribute/index.html new file mode 100644 index 0000000000..57699fa5e3 --- /dev/null +++ b/files/pt-br/web/accessibility/aria/aria_techniques/using_the_aria-label_attribute/index.html @@ -0,0 +1,64 @@ +--- +title: Usando o atributo aria-label +slug: Web/Accessibility/ARIA/ARIA_Techniques/Using_the_aria-label_attribute +tags: + - ARIA + - Acessibilidade + - Conteúdo + - Referencia +translation_of: Web/Accessibility/ARIA/ARIA_Techniques/Using_the_aria-label_attribute +--- +

O atributo aria-label é usado para definir um string na tag do elemento atual. Use nos casos que a tag do texto não seja visível na tela. Se há texto visível na tag do elemento, usa aria-labelledby em vez.

+ +

Esse atributo pode ser usado em qualquer elemento de HTML; não se limita aos elementos que tem um papel ARIA atribuído.

+ +

Valor

+ +

string

+ +

Possíveis efeitos sobre os user agents e Tecnologia assistiva 

+ +
+

Edit section

+
+ +
Nota: Opiniões podem diferir em como tecnologia assistiva deve lidar com esta técnica. A informação fornecida acima é um desses pareceres e, portanto, não normativo.
+ +

Exemplos

+ +
+

Exemplo 1: Várias Etiquetas

+ +

No exemplo abaixo, um botão é denominado para olhar como um botão típico "fechar", com um X no meio. Uma vez que não há nada que indique que a finalidade do botão é para fechar a janela, o atributo aria-label é utilizado para fornecer o rótulo para quaisquer tecnologias assistiva.

+
+ +
<button aria-label="Fechar" onclick="myDialog.close()">X</button>
+
+ +

Working Examples:

+ +

 

+ +

Notas

+ +

The most common accessibility API mapping for a label is the accessible name property.

+ +

Used by ARIA roles

+ +

todos os elementos da marcação de base

+ + + + + +

Compatibilidade

+ +

TBD: Add support information for common UA and AT product combinations

+ +

Recursos Adicionais

+ + diff --git a/files/pt-br/web/accessibility/aria/aria_techniques/utilizando_o_alert_role/index.html b/files/pt-br/web/accessibility/aria/aria_techniques/utilizando_o_alert_role/index.html new file mode 100644 index 0000000000..25d3222fcd --- /dev/null +++ b/files/pt-br/web/accessibility/aria/aria_techniques/utilizando_o_alert_role/index.html @@ -0,0 +1,145 @@ +--- +title: Utilizando a função "alerta" +slug: Web/Accessibility/ARIA/ARIA_Techniques/Utilizando_o_alert_role +tags: + - ARIA + - Accessibility + - Acessibilidade + - Alertas + - Avançado + - CSS + - Caixas de aviso + - Configuração role + - Guía + - HTML+ARIA + - NeedsContent + - PrecisaDeConteúdo + - WAI-ARIA + - wcag1.2.1 + - wcag3.3.1 +translation_of: Web/Accessibility/ARIA/ARIA_Techniques/Using_the_alert_role +--- +

Descrição

+ +
+

Esta técnica mostra como utilizar o atributo role alert e demonstra seu efeito em navegadores e tecnologias assistivas.

+
+ +

O atributo de alerta é utilizado para comunicar alguma mensagem importante e, frequentemente, urgente. Quando este atributo (role) estiver ligado a um elemento, o navegador vai enviar um evento acessível de alerta aos produtos de tecnologia assistiva que, então, poderão notificar seus utilizadores sobre o que estiver acontecendo. O atributo alert é mais útil para as informações que requerem a atenção imediata na tela. Por exemplo:

+ + + +

Por causa da sua natureza intrusiva, o atributo de alerta deve ser usado moderadamente e, apenas, nas situações que exigirem atenção imediata. Mudanças dinâmicas que são menos urgentes devem receber um método menos agressivo, tal como a aria-live="polite", ou outros atributos (roles) para regiões dinâmicas.

+ +

Efeitos possíveis sobre as tecnologias assistivas e seus utilizadores

+ +

Quando o atributo (role) alerta é adicionado a um elemento, ou este se torna visível, o identificador de navegação (user agent) deve fazer o seguinte:

+ + + +

Os produtos de tecnologias assistivas devem atender tal evento e notificar seus utilizadores, em conformidade.

+ + + +
Nota: As opiniões podem divergir sobre como uma tecnologia assistiva deve gerenciar esta técnica. A informação oferecida acima é uma dessas opiniões e, portanto, não é normativa.
+ +

Exemplos

+ +

Exemplo 1: Adicionando o atributo (role) no código HTML:

+ +

O trecho abaixo mostra como o atributo role alert é inserido, diretamente, no código-fonte HTML. No momento em que o elemento termina de carregar, o leitor de tela deve ser notificado do alerta. Se o elemento já estiver no código-fonte original quando a página carregar, o leitor de tela vai anunciar o erro imediatamente após a apresentação do título da página.

+ +
<h2 role="alert">Your form could not be submitted because of 3 validation errors.(Seu formulário não pode ser submetido devido a 3 erros de validação)</h2>
+ +

Exemplo 2: Adicionando, dinamicamente, um elemento com a função de alerta:

+ +

Esta parte mostra como criar, de forma dinâmica, um elemento com uma função de alerta e como adicioná-lo à estrutura do documento:

+ +
var myAlert = document.createElement("p");
+myAlert.setAttribute("role", "alert");
+var myAlertText = document.createTextNode("You must agree with our terms of service to create an account.(Você deve concordar com os nossos termos de serviço, a fim de criar uma conta)");
+myAlert.appendChild(myAlertText);
+document.body.appendChild(myAlertText);
+
+ +

Nota: O mesmo resultado pode ser obtido com menos código, quando se utiliza uma biblioteca de script, como jQuery:

+ +
$("<p role='alert'>You must agree with our terms of service to create an account.(Você deve concordar com os nossos termos de serviço para criar uma conta)</p>").appendTo(document.body);
+
+ +

Exemplo 3: Adicionando a função de alerta a um elemento existente:

+ +

Às vezes é preferível adicionar uma função de alerta a um elemento que já está visível na página, a criar um novo elemento. Isto possibilita que os desenvolvedores reiterem a informação que virá a ser mais importante, ou urgente, para os utilizadores. Por exemplo, um controle de formulário pode ter uma instrução sobre o valor esperado. Caso um valor diferente seja inserido, o role="alert" pode ser adicionado ao texto de instrução e, então, o leitor de tela o anuncia como um alerta. O pseudo código, no fragmento abaixo, ilustra esta abordagem:

+ +
<p id="formInstruction">You must select at least 3 options</p>
+
+ +
// When the user tries to submit the form with less than 3 checkboxes selected (Quando houver a tentativa de submissão do formulário com menos de 3 caixas de seleção marcadas):
+document.getElementById("formInstruction").setAttribute("role", "alert");
+ +

Exemplo 4: Construindo um elemento com uma função de alerta visível:

+ +

Se um elemento já tem o atributo role="alert" e é, inicialmente, escondido pelo uso da CSS, torná-lo visível o faz disparar como se estivesse adicionado à página. Isto significa que um alerta existente pode ser "utilizado" múltiplas vezes. 

+ +

Nota: Na maioria dos casos, esta abordagem não é recomendada, porque não é a ideal para esconder erro, ou alerta de texto, que não for aplicável no momento. Utilizadores de tecnologias assistivas antigas podem, ainda, perceber o texto de alerta, mesmo quando este não devesse ser aplicado, fazendo com que acreditem, incorretamente, que há um problema.

+ +
.hidden {
+  display:none;
+}
+
+ +
<p id="expirationWarning" role="alert" class="hidden">Your log in session will expire in 2 minutes(A sua sessão vai expirar em 2 minutos)</p>
+
+ +
// removing the 'hidden' class makes the element visible, which will make the screen reader announce the alert:(Remover a classe "hidden" faz o leitor de tela anunciar o alerta)
+document.getElementById("expirationWarning").className = ""; 
+ +

Exemplos de Trabalhos:

+ + + +

Notas:

+ + + +

Atributos ARIA utilizados

+ + + +

Técnicas ARIA relacionadas

+ + + +

Compatibilidade

+ +

TBD: Adicionar informações de suporte para UA comum e combinações de produtos TA / AT

+ +

Recursos Adicionais

+ + + +

 

diff --git a/files/pt-br/web/accessibility/aria/aria_test_cases/index.html b/files/pt-br/web/accessibility/aria/aria_test_cases/index.html new file mode 100644 index 0000000000..c079dc751e --- /dev/null +++ b/files/pt-br/web/accessibility/aria/aria_test_cases/index.html @@ -0,0 +1,4701 @@ +--- +title: ARIA Casos de Teste +slug: Web/Accessibility/ARIA/ARIA_Test_Cases +translation_of: Web/Accessibility/ARIA/ARIA_Test_Cases +--- +

Introdução

+ +
A informação dessa página encontra-se desatualizada: sua última atualização foi em Novmebro de 2010. No entanto, as informações ainad podem ser úteis para alguns leitores.
+
+Para ver exemplos atualizados, entre em OpenAjaxAlliance ARIA examples page.
+ +

For each example we test the "Expected" results with assistive technologies, for each browser that AT supports WAI-ARIA in. Where a failure occurs we will test the browser for API incorrectness, using tools such as MSAA Inspect. This must be done in order to determine where to file a bug (browser or AT).

+ +

There are several purposes for providing this information:

+ +
    +
  1. Help browser vendors provide correct implementations
  2. +
  3. Help AT vendors provide correct implementations
  4. +
  5. Inform authors as to what actually works reliably
  6. +
+ +

In general we're testing with the latest public releases. However, where things don't work we may test with nightly builds if they are available, in order to show what is already fixed in upcoming releases.

+ +

We can add more screen readers if people are willing to step up and provide test results for them.

+ +

Tested UA/AT Combinations:

+ + + +

Test Case Structure

+ +

Test cases are organized as follows:

+ + + +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ATFirefoxIEOperaSafari
JAWS 9----
JAWS 10- +

1. pass 2. fail

+
--
VoiceOver (Leopard)n/an/a-fail
Window-Eyes----
NVDA----
Zoom (Leopard)passn/apasspass
ZoomText----
Orca----
+
+
+ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + +
Table Legend
-no info/test yet
n/anot applicable (not supported technically)
passexpected behaviour met
failexpected behaviour notmet
1. 2.reference to link example
+
+
+ +

 

+ +

Note Regarding Dojo/Dijit Test Files

+ +

The main purpose of Dojo's Dijit test files are for Dojo developers to exercise and debug the code. As such, they are used to test a variety of features, such as styling, behavior, mouse, and keyboard interactions, to name few. These test files are not specifically for testing ARIA. Still, Dojo's widgets implement ARIA, and the noted test files could be used as an "ARIA test file".

+ +

New Tests for Internet Explorer 8 RC1

+ +

On this MSDN page the ARIA state/role mapping in IE8 to MSAA Roles can be directly checked. Also, as a clever feature for AT testing, the firing of events (like EVENT_OBJECT_STATECHANGE) can be invoked from the examples. Finally, a list of currently non-mapped ARIA roles is given.

+ +

Documenting and Filing Bugs

+ +

Review the information on how to file a bug on an ARIA implementation. When documenting an issue, please also list it in the relevant compatibility table below. When possible provide a link to the bug in the database so that its status can be reviewed.

+ +

Widget Test Cases

+ +

Alert

+ +
    +
  1. Simple alert
  2. +
  3. Complex Alert
  4. +
  5. Real alert example with aria-required and aria-invalid -- type in a email address without an at sign to test the alert
  6. +
+ +

Expected AT Behavior:

+ + + +


+ Markup used:

+ + + +

Notes:

+ +

Results:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ATFirefoxIEOperaSafari
JAWS 9PassedFailn/an/a
JAWS 10PassedFail--
VoiceOver (Leopard)n/an/a-fail
Window-EyesPassed- not announced as "alert"Fail--
NVDAPassedn/a--
Zoom (Leopard)passn/apasspass
ZoomText----
Orca----
+ + + +

Alertdialog

+ +
    +
  1. Alert Dialog
  2. +
  3. YUI alert dialog (3rd button in this page)
  4. +
+ +

Expected AT Behavior:

+ + + +

Markup used:

+ + + +

Notes:

+ +

In the UIUC test example, the 'close' button cannot recieve focus.

+ +

Results:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ATFirefoxIEOperaSafari
JAWS 9--n/an/a
JAWS 102 PASS, 1 PASS with known focus of the Close button problem. +

FFD - I concur

+
---
Voiceover (Leopard)n/an/a-fail
VoiceOver (Leopard)n/an/a-fail
Window-Eyes----
NVDA-n/a--
Zoom (Leopard)passn/apasspass
Zoom (Leopard)passn/apasspass
ZoomTextFail- announced as 'alert'Pass--
Orca----
+ +

Button

+ +

Basic Button

+ +
    +
  1. Button with description
  2. +
  3. dojo nightly build -- lots of other types of buttons there as well.
  4. +
+ +

Expected AT Behavior:

+ + + +


+ Markup used:

+ +

Notes:

+ +

Results:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ATFirefoxIEOperaSafari
JAWS 9--n/an/a
JAWS 10Pass in non-V-PC mode, pass in V-PC-mode also if the button's text is not provided via labelledby or label.---
VoiceOver (Leopard)n/an/a-fail
Window-Eyes----
NVDA-n/a--
Zoom (Leopard)passn/apasspass
ZoomText----
Orca----
+ +

Toggle Button

+ +
    +
  1. Buttons with Icons and without Text -- under construction. Only the bold/italic buttons should be toggle buttons, and they aren't currently toggleable.
  2. +
+ +

Expected AT Behavior:

+ + + +

Markup used:

+ + + +

Notes:

+ +

Results:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ATFirefoxIEOperaSafari
JAWS 9--n/an/a
JAWS 10Pass in non-V-PC-mode, button's state is announced when pressed, or when toggling it to pressed. Fail in V PC mode. No indication is given that a button is pressed, or that it is pressed after activating it.---
VoiceOver (Leopard)n/an/a-fail
Window-Eyes----
NVDA-n/a--
Zoom (Leopard)passn/apasspass
ZoomText----
Orca----
+ + + +
    +
  1. dojo nightly build
  2. +
+ +

Expected AT Behavior:

+ + + +

Markup used:

+ +

Notes:

+ +

Results:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ATFirefoxIEOperaSafari
JAWS 9--n/an/a
JAWS 10Pass in Non-V-PC-mode. Buttons are indicated as menu buttons. Menus are tracked, closing menus also results in correct focus tracking. Partial fail in V-PC-Mode. The fact that a button is a menu button is not indicated with the virtual cursor. Menus and focus are properly tracked upon activation.---
VoiceOver (Leopard)n/an/a-fail
Window-Eyes----
NVDA-n/a--
Zoom (Leopard)passn/apasspass
ZoomText----
Orca----
+ +

Checkbox

+ +

Simple Checkbox

+ +

Testcases:

+ +
    +
  1. Set aria-checked="false" for unchecked
  2. +
  3. Both remove or set attribute for unchecked case -- also includes an invalid and required checkbox
  4. +
  5. Hierarchical (newly added test not in test results yet)
  6. +
  7. dojo nightly build
  8. +
+ +

Expected AT Behavior:

+ + + +

Markup used:

+ + + +

Notes:

+ +

Need testcase where aria-checked attribute is removed instead of set to false

+ +

Results:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ATFirefoxIEOperaSafari
JAWS 9--n/an/a
JAWS 10PassFail (changes not spoken)FailFail
VoiceOver (Leopard)n/an/a-fail
Window-EyesPass +
    +
  1. Pass
  2. +
  3. Fail (unchecked presented as checked, IE exposing incorrect state for no aria-checked attribute)
  4. +
+
FailFail
NVDAFail on #2 -- repetitive text spoken, first checkbox toggle speaks incorrect staten/aFailFail
Zoom (Leopard)passn/apasspass
ZoomTextPass-FailFail
OrcaPassn/a--
+ +

Tristate Checkbox

+ +

Testcases:

+ +
    +
  1. Both remove or unset for unchecked case
  2. +
+ +

Expected AT Behavior:

+ + + +

Markup used:

+ + + +

Notes:

+ +

Results:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ATFirefoxIEOperaSafari
JAWS 9--n/an/a
JAWS 10Partial pass. The state of tristate checkboxes is not announced when initially focusing. It is announced when toggling.Fail - changes not spokenFailFail
VoiceOver (Leopard)n/an/a-fail
Window-EyesPassFail (unchecked presented as checked, IE exposing incorrect state for no aria-checked attribute)FailFail
NVDAFail -- for change from mixed to fully checked, nothing spokenn/aFailFail
Zoom (Leopard)passn/apasspass
ZoomTextPass-FailFail
Orca-n/a--
+ +

Combobox

+ +

Testcases:

+ +
    +
  1. editable combo 2
  2. +
  3. dojo nightly build (combobox)
  4. +
  5. dojo nightly build (combobox with auto complete)
  6. +
+ +

Expected AT Behavior:

+ + + +

Markup used:

+ +

Notes:

+ +

Results:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ATFirefoxIEOperaSafari
JAWS 9--n/an/a
JAWS 10Fail. Label and current content as well as role are spoken, also when typing in a new value, that gets reflected. But when dropping down the lists of states in either example, after the second or so list item, JAWS turns off Forms Mode, and the user has to turn off V Cursor to be able to make selections or tab to anything useful.---
VoiceOver (Leopard)n/an/a-fail
Window-Eyes----
NVDA-n/a--
Zoom (Leopard)passn/apasspass
ZoomText----
Orca----
+ +

Datepicker

+ +

Testcases:

+ +
    +
  1. Datepicker Example
  2. +
+ +

Expected AT Behavior:

+ +

Markup used:

+ +

Notes:

+ +

Results:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ATFirefoxIEOperaSafari
JAWS 9--n/an/a
JAWS 10 ---
VoiceOver (Leopard)n/an/a-fail
Window-Eyes----
NVDA-n/a--
Zoom (Leopard)passn/apasspass
ZoomText----
Orca----
+ +

Description

+ +
    +
  1. Description for groupbox and for button
  2. +
+ +

(AL) Note: the description role is no longer necessary as long as aria-describedby is used; however, this test case is still useful for testing aria-describedby.

+ +

Expected AT Behavior:

+ + + +

Markup used:

+ + + +

Notes:

+ +

Results:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ATFirefoxIEOperaSafari
JAWS 9--n/an/a
JAWS 10----
VoiceOver (Leopard)n/an/a-fail
Window-Eyes----
NVDA-n/a--
Zoom (Leopard)passn/apasspass
ZoomText----
Orca----
+ +

Dialog

+ +
    +
  1. dojo nightly build- Note that this may not always work
  2. +
  3. Dojo 1.2.3 Release
  4. +
  5. YUI dialogs -- use first two dialog buttons
  6. +
+ +

Expected AT Behavior:

+ + + +

Markup used:

+ +

Notes:

+ +

Results:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ATFirefoxIEOperaSafari
JAWS 9--n/an/a
JAWS 10passfail--
VoiceOver (Leopard)n/an/a-fail
Window-Eyes----
NVDA-n/a--
Zoom (Leopard)passn/apasspass
ZoomText----
Orca----
+ +

Drag and Drop

+ +
    +
  1. Tic tac toe
  2. +
  3. Slide show
  4. +
+ +

Expected AT Behavior:

+ + + +

Markup used:

+ + + +

Notes:

+ + + +

Results:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ATFirefoxIEOperaSafari
JAWS 9--n/an/a
JAWS 10----
VoiceOver (Leopard)n/an/a-fail
Window-Eyes----
NVDA-n/a--
Zoom (Leopard)passn/apasspass
ZoomText----
Orca----
+ +

Grid

+ +

See various grid and table examples on the example page for grid variants.

+ +
    +
  1. Basic Grid -- single select
  2. +
  3. Grid in an application -- single select
  4. +
  5. Illinois Grid Example -- multi select
  6. +
+ +


+ Expected AT Behavior:

+ + + + + + + +

Markup used:

+ + + +

Notes:

+ +

Results:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ATFirefoxIEOperaSafari
JAWS 9--n/an/a
JAWS 10----
VoiceOver (Leopard)n/an/a-fail
Window-Eyes----
NVDA-n/a--
Zoom (Leopard)passn/apasspass
ZoomText----
Orca----
+ +

Treegrid

+ +

Examples:

+ +
    +
  1. Grid with expandable rows
  2. +
+ +

Expected AT Behavior:

+ + + +

Markup used:

+ +

Notes:

+ +

Results:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ATFirefoxIEOperaSafari
JAWS 9--n/an/a
JAWS 10----
VoiceOver (Leopard)n/an/a-fail
Window-Eyes----
NVDA-n/a--
Zoom (Leopard)passn/apasspass
ZoomText----
Orca----
+ +

Group

+ +

(no examples yet)

+ +

Expected AT Behavior:

+ + + +

Markup used:

+ +

Notes:

+ +

Results:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ATFirefoxIEOperaSafari
JAWS 9--n/an/a
JAWS 10----
VoiceOver (Leopard)n/an/a-fail
Window-Eyes----
NVDA-n/a--
Zoom (Leopard)passn/apasspass
ZoomText----
Orca----
+ +

 

+ +

Img

+ +
    +
  1. Tiled image
  2. +
+ +

Expected AT Behavior:

+ + + +

Markup used:

+ + + +

Notes:

+ +

If the screen reader does not provide the required behavior, then most likely it is a browser issue, for not respecting "Children Presentational: true" for that role. The accessible hierarchy should contain no children for the img.

+ +

Results:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ATFirefoxIEOperaSafari
JAWS 9--n/an/a
JAWS 10----
VoiceOver (Leopard)n/an/a-fail
Window-Eyes----
NVDA-n/a--
Zoom (Leopard)passn/apasspass
ZoomText----
Orca----
+ +

List

+ +

Simple List

+ +

Expected AT Behavior:

+ + + +

Markup used:

+ +

Notes:

+ +

Results:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ATFirefoxIEOperaSafari
JAWS 9--n/an/a
JAWS 10----
VoiceOver (Leopard)n/an/a-fail
Window-Eyes----
NVDA-n/a--
Zoom (Leopard)passn/apasspass
ZoomText----
Orca----
+ + + + + +

Expected AT Behavior:

+ + + +

Markup used:

+ +

Notes:

+ +

Results:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ATFirefoxIEOperaSafari
JAWS 9--n/an/a
JAWS 10----
VoiceOver (Leopard)n/an/a-fail
Window-Eyes----
NVDA-n/a--
Zoom (Leopard)passn/apasspass
ZoomText----
Orca----
+ +

Listbox and Option

+ +
    +
  1. dojo nightly build
  2. +
  3. Single select listbox using aria-activedescendant
  4. +
  5. Listbox in an iframe -- this is an important case as it's an example of how a mashup widget can be built (the widget source simply comes from another url, and is tied in using an iframe)
  6. +
  7. YUI "Carousel" listbox -- a more advanced test case
  8. +
+ +

Expected AT Behavior:

+ + + +

Markup used:

+ + + +

Notes:

+ +

Results:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ATFirefoxIEOperaSafari
JAWS 9--n/an/a
JAWS 10----
VoiceOver (Leopard)n/an/a-fail
Window-Eyes----
NVDA-n/a--
Zoom (Leopard)passn/apasspass
ZoomText----
Orca----
+ +

 

+ + + +
    +
  1. YUI menubar
  2. +
  3. Menubar 1
  4. +
  5. dojo nightly build - popup menu
  6. +
+ +


+ Expected AT Behavior:

+ + + +

Markup used:

+ + + +

Notes:

+ +

Results:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ATFirefoxIEOperaSafari
JAWS 9--n/an/a
JAWS 10----
VoiceOver (Leopard)n/an/a-fail
Window-Eyes----
NVDA-n/a--
Zoom (Leopard)passn/apasspass
ZoomText----
Orca----
+ +

Progressbar

+ +
    +
  1. dojo nightly build
  2. +
  3. Progress bar in "off" live region
  4. +
  5. Progressbar in "assertive" live region
  6. +
+ +

Expected AT Behavior:

+ + + +

Markup used:

+ + + +

Notes:

+ +

Results:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ATFirefoxIEOperaSafari
JAWS 9--n/an/a
JAWS 10----
VoiceOver (Leopard)n/an/a-fail
Window-Eyes----
NVDA-n/a--
Zoom (Leopard)passn/apasspass
ZoomText----
Orca----
+ +

Radiogroup and Radiobutton

+ +
    +
  1. Radio Example using CSS Background Images
  2. +
  3. Radio Example using IMG Element
  4. +
  5. Radio Example using aria-activedescendent Property
  6. +
  7. dojo nightly build
  8. +
+ +

Expected AT Behavior:

+ + + +

Markup used:

+ +

Notes:

+ +

Results:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ATFirefoxIEOperaSafari
JAWS 9--n/an/a
JAWS 10----
VoiceOver (Leopard)n/an/a-fail
Window-Eyes----
NVDA-n/a--
Zoom (Leopard)passn/apasspass
ZoomText----
Orca----
+ +

Separator

+ +

(no examples yet)

+ +

Expected AT Behavior:

+ + + +

Markup used:

+ +

Notes:

+ +

Results:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ATFirefoxIEOperaSafari
JAWS 9--n/an/a
JAWS 10----
VoiceOver (Leopard)n/an/a-fail
Window-Eyes----
NVDA-n/a--
Zoom (Leopard)passn/apasspass
ZoomText----
Orca----
+ +

Slider

+ +

Single Slider

+ +
    +
  1. Slider using in-line images for thumb
  2. +
  3. dojo nightly build
  4. +
  5. Simple slider
  6. +
  7. Pretty slider
  8. +
  9. MINDTROVE Rating Widget
  10. +
  11. Paciello Group slider
  12. +
+ +

Expected AT Behavior:

+ + + +

Markup used:

+ + + +

Notes:

+ +

Results:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ATFirefoxIEOperaSafari
JAWS 9--n/an/a
JAWS 10----
VoiceOver (Leopard)n/an/a-fail
Window-Eyes----
NVDA-n/a--
Zoom (Leopard)passn/apasspass
ZoomText----
Orca----
+ +

Multi-Thumb Slider

+ +
    +
  1. Multi-Thumb Slider Example using inline images for thumbs
  2. +
  3. TPG double slider
  4. +
+ +

Expected AT Behavior:

+ + + +

Markup used:

+ +

Notes:

+ +

Results:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ATFirefoxIEOperaSafari
JAWS 9--n/an/a
JAWS 10----
VoiceOver (Leopard)n/an/a-fail
Window-Eyes----
NVDA-n/a--
Zoom (Leopard)passn/apasspass
ZoomText----
Orca----
+ +

Spinner

+ +

Spin Button

+ +
    +
  1. dojo nightly build
  2. +
+ +

Expected AT Behavior:

+ + + +

Markup used:

+ +

Notes:

+ +

Results:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ATFirefoxIEOperaSafari
JAWS 9--n/an/a
JAWS 10----
VoiceOver (Leopard)n/an/a-fail
Window-Eyes----
NVDA-n/a--
Zoom (Leopard)passn/apasspass
ZoomText----
Orca----
+ +

Tabpanel

+ +
    +
  1. Simple Tabpanel Example
  2. +
  3. dojo nightly build
  4. +
  5. Another tab panel example
  6. +
  7. Just annother tab panel example
  8. +
  9. YUI Tab Panel example with live regions (using YUI ARIA plug-in).
  10. +
  11. MS IE8 Tab Control example
  12. +
+ +

Expected AT Behavior:

+ + + +

Markup used:

+ +

Notes:

+ +

Results:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ATFirefoxIEOperaSafari
JAWS 9--n/an/a
JAWS 10----
VoiceOver (Leopard)n/an/a-fail
Window-Eyes----
NVDA-n/a--
Zoom (Leopard)passn/apasspass
ZoomText----
Orca----
+ +

Textbox

+ +
    +
  1. dojo nightly build
  2. +
+ +

Expected AT Behavior:

+ + + +

Markup used:

+ +

Notes:

+ +

Results:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ATFirefoxIEOperaSafari
JAWS 9--n/an/a
JAWS 10----
VoiceOver (Leopard)n/an/a-fail
Window-Eyes----
NVDA-n/a--
Zoom (Leopard)passn/apasspass
ZoomText----
Orca----
+ +

Toolbar

+ +
    +
  1. Example to test ARIA live region and toolbar
  2. +
  3. dojo nightly build
  4. +
+ +

Expected AT Behavior:

+ + + +

Markup used:

+ +

Notes:

+ +

Results:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ATFirefoxIEOperaSafari
JAWS 9--n/an/a
JAWS 10----
VoiceOver (Leopard)n/an/a-fail
Window-Eyes----
NVDA-n/a--
Zoom (Leopard)passn/apasspass
ZoomText----
Orca----
+ +

Tooltip

+ +
    +
  1. dojo nightly build (tooltip)
  2. +
  3. Simple tooltip -- the tooltip for the link contains the text "Some tooltip"
  4. +
+ +

Expected AT Behavior:

+ + + +

Markup used:

+ + + +

Notes:

+ +

Results:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ATFirefoxIEOperaSafari
JAWS 9--n/an/a
JAWS 10----
VoiceOver (Leopard)n/an/a-fail
Window-Eyes----
NVDA-n/a--
Zoom (Leopard)passn/apasspass
ZoomText----
Orca----
+ +

Tree

+ +
    +
  1. dojo nightly build
  2. +
  3. Simple tree -- uses document structure to create hierarchy
  4. +
  5. Tree - Subtrees are encapsulated in treeitems
  6. +
  7. MS IE8 Tree example
  8. +
  9. We need an example that uses aria-level, aria-setsize and aria-posinset to create the hierarchy
  10. +
  11. We also need one that uses aria-owns to create the hierarchy / structure
  12. +
  13. We need one that uses the document to create structure, but uses nested ULs with links inside, and role="presentation"
  14. +
+ +

Expected AT Behavior:

+ + + +

Markup used:

+ + + +

Notes:

+ +

Results:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ATFirefoxIEOperaSafari
JAWS 9--n/an/a
JAWS 10----
VoiceOver (Leopard)n/an/a-fail
Window-Eyes----
NVDA-n/a--
Zoom (Leopard)passn/apasspass
ZoomText----
Orca----
+ +

Other Test Cases

+ +

Application

+ +
    +
  1. Simple application with inner document
  2. +
  3. With grid and menubar
  4. +
+ +

Expected AT Behavior:

+ + + +

Markup used:

+ + + +

Notes:

+ +

Results:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ATFirefoxIEOperaSafari
JAWS 9FailFailn/an/a
JAWS 10Pass with slight problems in the menu bar (wrong order of events or missing ones, sometimes making JAWS believe it is still in a menu when the menu has actually closed)Fail--
VoiceOver (Leopard)n/an/a-fail
Window-EyesFailFail--
NVDAFailn/a--
Zoom (Leopard)passn/apasspass
ZoomText----
Orca----
+ +

Document

+ + + +

Expected AT Behavior:

+ + + +

Markup used:

+ +

Notes:

+ +

Results:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ATFirefoxIEOperaSafari
JAWS 9--n/an/a
JAWS 10----
VoiceOver (Leopard)n/an/a-fail
Window-Eyes----
NVDA-n/a--
Zoom (Leopard)passn/apasspass
ZoomText----
Orca----
+ +

 

+ +

Landmarks

+ +
    +
  1. Real world Yahoo! news page with landmarks
  2. +
  3. Illinois Navigation Example
  4. +
  5. Test all landmarks -- very minimal test, not a real world case. The page includes some nested landmarks as well.
  6. +
  7. Juicy Studio -- real world example
  8. +
  9. This site -- another real world example
  10. +
  11. Application with inner document -- the only landmark here is the document, since role="application" as at the root
  12. +
+ +

Expected AT Behavior:

+ + + + + +


+ Markup used:

+ + + +

Notes:

+ + + +

Results:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ATFirefoxIEOperaSafari
JAWS 9--n/an/a
JAWS 10AL: Tested 2 and 4 with JAWS 10.0.512U on Nov 21, 2008 +

2. FAIL - No landmarks reported on page load but there are many in the source. Pressing ; does not visit any of them.
+ 4. FAIL - JAWS says it has 5 landmarks, when page first loads, pressing ; only moves between 2 of the landmarks. Also, JAWSKey+Ctrl+SemiColon keystroke displays only 4 of the landmarks (it seems to be missing search)

+
Exact same failures as with Firefox--
VoiceOver (Leopard)n/an/a-fail
Window-Eyes----
NVDA-n/a--
Zoom (Leopard)passn/apasspass
ZoomText----
Orca----
+ +

Live Regions

+ +

Thank you to Charles Chen for developing the live region examples.

+ +

aria-live

+ +
    +
  1. aria-live="off"
  2. +
  3. aria-live="polite"
  4. +
  5. aria-live="assertive"
  6. +
  7. aria-live="rude"
  8. +
  9. aria-live attribute is missing
  10. +
  11. nested live regions: "assertive" inside "off"
  12. +
  13. MS IE8 Chat Example
  14. +
+ +

Expected AT Behavior:

+ + + +

Markup used:

+ + + +

Notes:

+ +

Results:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ATFirefoxIEOperaSafari
JAWS 9--n/an/a
JAWS 10----
VoiceOver (Leopard)n/an/a-fail
Window-Eyes----
NVDA-n/a--
Zoom (Leopard)passn/apasspass
ZoomText----
Orca----
+ +

Labelled or Described Live Region

+ +
    +
  1. aria-labelledby="(id)" aria-live="polite"
  2. +
  3. aria-describedby="(id)" aria-live="polite"
  4. +
+ +

Expected AT Behavior:

+ + + +

Markup used:

+ + + +

Notes:

+ +

Results:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ATFirefoxIEOperaSafari
JAWS 9--n/an/a
JAWS 10----
VoiceOver (Leopard)n/an/a-fail
Window-Eyes----
NVDA-n/a--
Zoom (Leopard)passn/apasspass
ZoomText----
Orca----
+ +

aria-atomic="true"

+ +
    +
  1. aria-atomic="true" aria-live="polite"
  2. +
+ +

Expected AT Behavior:

+ + + +

Markup used:

+ + + +

Notes:

+ +

Results:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ATFirefoxIEOperaSafari
JAWS 9--n/an/a
JAWS 10----
VoiceOver (Leopard)n/an/a-fail
Window-Eyes----
NVDA-n/a--
Zoom (Leopard)passn/apasspass
ZoomText----
Orca----
+ +

aria-controls

+ +
    +
  1. aria-controls -- activating button makes live region change
  2. +
  3. aria-controls and live="polite" changes -- live region with a combination of polite real world changes and button-controlled changes
  4. +
+ +

Expected AT Behavior:

+ + + +

Markup used:

+ + + +

Notes:

+ +

Results:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ATFirefoxIEOperaSafari
JAWS 9--n/an/a
JAWS 10----
VoiceOver (Leopard)n/an/a-fail
Window-Eyes----
NVDA-n/a--
Zoom (Leopard)passn/apasspass
ZoomText----
Orca----
+ +

aria-relevant tests

+ +
    +
  1. aria-relevant="additions" aria-live="polite"
  2. +
  3. aria-relevant="removals" aria-live="polite"
  4. +
  5. aria-relevant="text" aria-live="polite"
  6. +
  7. aria-relevant="all" aria-live="polite"
  8. +
  9. aria-relevant="additions removals text"" aria-live="polite -- should have same behavior as "all"
  10. +
  11. aria-relevant="additions text" aria-live="polite"
  12. +
  13. aria-live="polite" -- aria-relevant is not set, so should act the same as "additions text"
  14. +
+ +


+ Expected AT Behavior:

+ + + +

Markup used:

+ + + +

Notes:

+ +

Results:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ATFirefoxIEOperaSafari
JAWS 9--n/an/a
JAWS 10----
VoiceOver (Leopard)n/an/a-fail
Window-Eyes----
NVDA-n/a--
Zoom (Leopard)passn/apasspass
ZoomText----
Orca----
+ +

Live roles: Log + Timer

+ +
    +
  1. Illinois Log and Timer example
  2. +
  3. CLC Chat -- see the accompanying notes
  4. +
  5. Chatzilla (this is a real app but uses ARIA in an HTML area for chat)
  6. +
+ +

Expected AT Behavior:

+ + + +

Markup used:

+ + + +

Notes:

+ +

Results:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ATFirefoxIEOperaSafari
JAWS 9--n/an/a
JAWS 10----
VoiceOver (Leopard)n/an/a-fail
Window-Eyes----
NVDA-n/a--
Zoom (Leopard)passn/apasspass
ZoomText----
Orca----
+ +

Live role: Marquee

+ +

(no examples yet)

+ +

Expected AT Behavior:

+ + + +

Markup used:

+ + + +

Notes:

+ +

Results:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ATFirefoxIEOperaSafari
JAWS 9--n/an/a
JAWS 10----
VoiceOver (Leopard)n/an/a-fail
Window-Eyes----
NVDA-n/a--
Zoom (Leopard)passn/apasspass
ZoomText----
Orca----
+ +

Live role: Status

+ +

(no examples yet)

+ +

Expected AT Behavior:

+ + + +

Markup used:

+ + + +

Notes:

+ +

Results:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ATFirefoxIEOperaSafari
JAWS 9--n/an/a
JAWS 10----
VoiceOver (Leopard)n/an/a-fail
Window-Eyes----
NVDA-n/a--
Zoom (Leopard)passn/apasspass
ZoomText----
Orca----
+ +

Live HTML table

+ +
    +
  1. Live game scores
  2. +
+ +

Expected AT Behavior:

+ + + +

Markup used:

+ + + +

Notes:

+ +

Scoreboard notes

+ +

Results:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ATFirefoxIEOperaSafari
JAWS 9--n/an/a
JAWS 10----
VoiceOver (Leopard)n/an/a-fail
Window-Eyes----
NVDA-n/a--
Zoom (Leopard)passn/apasspass
ZoomText----
Orca----
+ +

Property-Only Test Cases

+ +

These testcases involve ARIA properties used to enhance HTML controls (as opposed to JavaScript-built widgets).

+ +

autocomplete

+ +
    +
  1. Dojo autocomplete
  2. +
+ +

Expected AT Behavior:

+ + + +

Markup used:

+ + + +

Notes:

+ +

Results:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ATFirefoxIEOperaSafari
JAWS 9FailFailn/an/a
JAWS 10Fail - Does not announce the presence of AutoComplete possibilities, does not do this anywhere in Windows. Reads autocomplete suggestions through its ordinary highlight color mechanism.Fail--
VoiceOver (Leopard)n/an/a-fail
Window-EyesFailFail--
NVDAPassn/a--
Zoom (Leopard)passn/apasspass
ZoomText----
Orca----
+ +

 

+ +

describedby

+ +
    +
  1. aria-describedby
  2. +
  3. aria-describedby with display: none
  4. +
  5. aria-describedby with visibility: hidden
  6. +
  7. aria-describedby on img's with role="button"
  8. +
+ +

Expected AT Behavior:

+ + + +

Markup used:

+ + + +

Notes:

+ +

Results:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ATFirefoxIEOperaSafari
JAWS 9--n/an/a
JAWS 10----
VoiceOver (Leopard)n/an/a-fail
Window-Eyes----
NVDA-n/a--
Zoom (Leopard)passn/apasspass
ZoomText----
Orca----
+ +

label

+ +
    +
  1. aria-label
  2. +
+ +

Expected AT Behavior:

+ + + +

Markup used:

+ + + +

Notes:

+ + + +

Results:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ATFirefoxIEOperaSafari
JAWS 9--n/an/a
JAWS 10----
VoiceOver (Leopard)n/an/a-fail
Window-Eyes----
NVDAFailn/a--
Zoom (Leopard)passn/apasspass
ZoomText----
Orca----
+ +

labelledby

+ +
    +
  1. aria-labelledby
  2. +
+ +

Expected AT Behavior:

+ + + +

Markup used:

+ + + +

Notes:

+ + + +

Results:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ATFirefoxIEOperaSafari
JAWS 9--n/an/a
JAWS 10----
VoiceOver (Leopard)n/an/a-fail
Window-Eyes----
NVDA-n/a--
Zoom (Leopard)passn/apasspass
ZoomText----
Orca----
+ +

required

+ +
    +
  1. aria-required="true"
  2. +
+ +

Expected AT Behavior:

+ + + +

Markup used:

+ + + +

Notes:

+ +

Results:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ATFirefoxIEOperaSafari
JAWS 9--n/an/a
JAWS 10----
VoiceOver (Leopard)n/an/a-fail
Window-Eyes----
NVDA-n/a--
Zoom (Leopard)passn/apasspass
ZoomText----
Orca----
diff --git a/files/pt-br/web/accessibility/aria/forms/alerts/index.html b/files/pt-br/web/accessibility/aria/forms/alerts/index.html new file mode 100644 index 0000000000..b33525c5ad --- /dev/null +++ b/files/pt-br/web/accessibility/aria/forms/alerts/index.html @@ -0,0 +1,141 @@ +--- +title: Alerts +slug: Web/Accessibility/ARIA/forms/alerts +translation_of: Web/Accessibility/ARIA/forms/alerts +--- +

O problema

+ +

Você tem um formulário — um formulário de contato, por exemplo — no qual você deseja inserir algum that you want to put some accessible error checking into. Examples of common problems include e-mail addresses which are not valid, or a name field which does not contain at least a first name or a surname.

+ +

O formulário

+ +

Primeiro, por favor leia sobre a técnica de aria-required  if you have not done so, as this technique expands upon that.

+ +

Here is a simple form:

+ +
 <form method="post" action="post.php">
+   <fieldset>
+     <legend>Please enter your contact details</legend>
+     <label for="name">Your name (required):</label>
+     <input name="name" id="name" aria-required="true"/>
+     <br />
+     <label for="email">E-Mail address (required):</label>
+     <input name="email" id="email" aria-required="true"/>
+     <br />
+     <label for="website">Website (optional):</label>
+     <input name="website" id="website"/>
+   </fieldset>
+   <label for="message">Please enter your message (required):</label>
+   <br />
+   <textarea name="message" id="message" rows="5" cols="80"
+             aria-required="true"></textarea>
+   <br />
+   <input type="submit" name="submit" value="Send message"/>
+   <input type="reset" name="reset" value="Reset form"/>
+ </form>
+
+ +

Checking for validity and notifying the user

+ +

Form validations consists of several steps:

+ +
    +
  1. Checking if the e-mail address or entered name are valid. Each field has a set of criteria which must be met in order to pass validation.  In order to simplify this example, we’ll check whether the e-mail address contains the “@” symbol, and if the name entry contains at least 1 character.
  2. +
  3. If the above criteria is not met, the field’s aria-invalid attribute will be given a value of “true”.
  4. +
  5. If the criteria was not met, the user will be notified via an alert. Instead of using the JavaScript ‘alert’ function, we’ll use a simple WAI-ARIA widget for notification. This notifies the user of the error, but allows for them continue modifying the form without losing focus (caused by the “onblur” handler in JavaScript's default ‘alert’ function).
  6. +
+ +

Below is example JavaScript code which could be inserted above the closing “head” tag:

+ +
 <script type="application/javascript">
+ function removeOldAlert()
+ {
+   var oldAlert = document.getElementById("alert");
+   if (oldAlert){
+     document.body.removeChild(oldAlert);
+   }
+ }
+
+ function addAlert(aMsg)
+ {
+   removeOldAlert();
+   var newAlert = document.createElement("div");
+   newAlert.setAttribute("role", "alert");
+   newAlert.setAttribute("id", "alert");
+   var msg = document.createTextNode(aMsg);
+   newAlert.appendChild(msg);
+   document.body.appendChild(newAlert);
+ }
+
+ function checkValidity(aID, aSearchTerm, aMsg)
+ {
+   var elem = document.getElementById(aID);
+   var invalid = (elem.value.indexOf(aSearchTerm) < 0);
+   if (invalid) {
+     elem.setAttribute("aria-invalid", "true");
+     addAlert(aMsg);
+   } else {
+     elem.setAttribute("aria-invalid", "false");
+     removeOldAlert();
+   }
+ }
+ </script>
+
+ +

The checkValidity function

+ +

The primary method in JavaScript used for form validation is the checkValidity function. This method takes three parameters: The ID of the input that is to be validated, the term to search for to ensure validity, and the error message to be inserted into the alert.

+ +

To see if it is valid, the function checks whether the indexOf the input’s value is anything greater than -1. A value of -1 or less is returned if the index of the search term could not be found within the value.

+ +

If invalid, the function does two things:

+ +
    +
  1. It sets the element’s aria-invalid attribute to “true”, which will indicate to screen readers that there is invalid content in here.
  2. +
  3. It will call the addAlert function to add the alert with the provided error message.
  4. +
+ +

If the search term is found, the aria-invalid attribute is reset to “false”. In addition, any leftover alerts are removed.

+ +

The addAlert function

+ +

This function first removes any old alerts. The function is simple: It looks for an element with id “alert”, and if found, removes that from the document object model.

+ +

Next, the function creates a div element to hold the alert text. It gets an ID of “alert”. And it gets a role set of “alert”. This is actually ARIA-inspired, even though it doesn’t say “aria” in the attribute name. This is because that role is based on the XHTML Role Attribute Module that was simply ported to HTML for simplicity.

+ +

The text is added to the div element, and the div element is added to the document.

+ +

The moment this happens, Firefox will fire an “alert” event to assistive technologies when this div appears. Most screen readers will pick this one up automatically and speak it. This is similar to the Notification Bar in Firefox that prompts you whether you want to save a password. The alert we just created does not have any buttons to press, it just tells us what’s wrong.

+ +

Modifying the “onblur” event

+ +

All that’s left now is add the event handler. We need to change the two inputs for e-mail and name for this:

+ +
 <input name="name" id="name" aria-required="true"
+        onblur="checkValidity('name', ' ', 'Invalid name entered!');"/>
+ <br />
+ <input name="email" id="email" aria-required="true"
+        onblur="checkValidity('email', '@', 'Invalid e-mail address');"/>
+
+ +

Testing the example

+ +

If you use Firefox 3 and a currently-supported screen reader, try the following:

+ +
    +
  1. Enter only your first name as the name. When tabbing, you’ll hear an alert that tells you you’ve entered an invalid name. You can then shift-tab back and correct the error.
  2. +
  3. Enter an e-mail address without the “@” symbol. When tabbing out of this field, you should hear a warning that says you didn’t enter a valid e-mail address.
  4. +
+ +

In both cases, when returning focus to the field in question, your screen reader should tell you that this field is invalid. JAWS 9 supports this, but JAWS 8 does not, so this may not work in all versions of the screen readers supported.

+ +

A few questions that you might have

+ +
+
Q. Why did you put both “(required)” in the label text and the aria-required attribute on some of the inputs?
+
A. If this were a real live form, and the site was being visited by a browser that does not yet support ARIA, we’d still want to give an indication that this is a required field.
+
Q. Why don’t you set focus back to the invalid field automatically?
+
A. Because this is not allowed by the Windows API specs, and possibly others. Also, letting the focus jump around without real user interaction too often is not a nice thing to do in general. 
+
+ +
TBD: let's rethink this -- personally, I think setting focus might be good if done without causing a keyboard trap.
diff --git "a/files/pt-br/web/accessibility/aria/forms/dicas_b\303\241sicas_de_form/index.html" "b/files/pt-br/web/accessibility/aria/forms/dicas_b\303\241sicas_de_form/index.html" new file mode 100644 index 0000000000..722c60d420 --- /dev/null +++ "b/files/pt-br/web/accessibility/aria/forms/dicas_b\303\241sicas_de_form/index.html" @@ -0,0 +1,118 @@ +--- +title: Dicas básicas de form +slug: Web/Accessibility/ARIA/forms/Dicas_básicas_de_form +translation_of: Web/Accessibility/ARIA/forms/Basic_form_hints +--- +
+

Form labels

+
+ +

Quando estiver implementando forms usando elementos HTML tradicionais relacionados à foms, é importante fornecer labels para controles e para explicitamente associar um label com o seu ocntrole. Quando um usuário de leitor de tela navega uma página, o leitor de tel irá descrever os controles do form, mas sem uma associação direta entre o controle e seu label, o leitor de tela não tem maneira de saber qual label é o correto.

+ +

O exemplo abaixo mostra um form simples com labels. Note que cada elemento {{HTMLElement("input")}} tem um id, e cada elemento {{HTMLElement("label")}} tem um atributo for indicando o id do {{HTMLElement("input")}} associado.

+ +

Exempl0 1. Form simples com labels

+ +
<form>
+  <ul>
+    <li>
+      <input id="wine-1" type="checkbox" value="riesling"/>
+      <label for="wine-1">Berg Rottland Riesling</label>
+    </li>
+    <li>
+      <input id="wine-2" type="checkbox" value="weissbergunder"/>
+      <label for="wine-2">Weissbergunder</label>
+    </li>
+    <li>
+      <input id="wine-3" type="checkbox" value="pinot-grigio"/>
+      <label for="wine-3">Pinot Grigio</label>
+    </li>
+    <li>
+      <input id="wine-4" type="checkbox" value="gewurztraminer"/>
+      <label for="wine-4">Berg Rottland Riesling</label>
+    </li>
+  </ul>
+</form>
+
+ +

Rotulando com ARIA

+ +

O elemento HTML {{HTMLElement("label")}} é apropriado para elementos relacionados com form, mas muitos controles de form são implementados como widget JavaScript dinâmico, usando {{HTMLElement("div")}}s ou {{HTMLElement("span")}}s. WAI-ARIA, a especificação de Aplicações Internet Ricas em Acessibilidade da W3C Iniciativa de Acessibilidade Web, fornece o atributo aria-labelledby para esses casos.

+ +

O exemplo abaixo mostra um grupo de botões rádio usando um lista não ordenada. Note que na linha 3, o elemento {{HTMLElement("li")}} seta o atributo aria-labelledby para "rg1_label," o id do elemento {{HTMLElement("h3")}} na linha 1, que é o label para o grupo rádio.

+ +

Exemplo 2. Um grupo rádio implementado usando uma lista não ordenada (adaptado de http://www.oaa-accessibility.org/examplep/radio1/)

+ +
<h3 id="rg1_label">Lunch Options</h3>
+
+<ul class="radiogroup" id="rg1"  role="radiogroup" aria-labelledby="rg1_label">
+  <li id="r1"  tabindex="-1" role="radio" aria-checked="false">
+    <img role="presentation" src="radio-unchecked.gif" /> Thai
+  </li>
+  <li id="r2"  tabindex="-1" role="radio"  aria-checked="false">
+    <img role="presentation" src="radio-unchecked.gif" /> Subway
+  </li>
+  <li id="r3"   tabindex="0" role="radio" aria-checked="true">
+    <img role="presentation" src="radio-checked.gif" /> Radio Maria
+  </li>
+</ul>
+
+ +

Descrevendo com ARIA

+ +

Controles form às vezes tem uma descrição associada com eles, em adição ao label. ARIA fornece o atributo aria-describedby para diretamente associar a descrição com o controle.

+ +

O exemplo abaixo mostra um elemento {{HTMLElement("button")}} que é descrito por uma sentença num elemento {{HTMLElement("div")}} separado. O atributo aria-describedby no {{HTMLElement("button")}} referencia o id de {{HTMLElement("div")}}.

+ +

Exemplo 3. Um botão descrito por um elemento separado.

+ +
<button aria-describedby="descriptionRevert">Revert</button>
+<div id="descriptionRevert">Reverting will undo any changes that have been made since the last save.</div>
+ +

(Note que o atributo aria-describedby é usado para outros propósitos, além de controles do form.)

+ +

Campos inválidos e obrigatórios

+ +

Web developers tipicamente usam estratégias de apresentação para indicar campos obrigatórios ou campos inválidos, mas tecnologias assistivas (TAs) não podem necessariamente inferir essa informação a partir da apresentação. ARIA fornece atributos para indicar que os controles do form são obrigatórios ou inválidos:

+ + + +

O exemplo abaixo mostra um form simples com três campos. Nas linhas 4 e 12, o atributo aria-required é setado para true (em adição aos asteriscos próximos aos labels) indicando que os campos de nome e e-mail são obrigatórios. A segunda parte do exemplo é um trecho de JavaScript que valida o e-mail e seta o atributo aria-invalid do campo e-mail (linha 12 do HTML) de acordo com o resultado (em adição à mudança de apresentação do elemento).

+ +

Exemplo 4a. Um form com campos obrigatórios.

+ +
<form>
+  <div>
+    <label for="name">* Name:</label>
+    <input type="text" value="name" id="name" aria-required="true"/>
+  </div>
+  <div>
+    <label for="phone">Phone:</label>
+    <input type="text" value="phone" id="phone" aria-required="false"/>
+  </div>
+  <div>
+    <label for="email">* E-mail:</label>
+    <input type="text" value="email" id="email" aria-required="true"/>
+  </div>
+</form>
+ +

Exemplo 4b. Parte de um script que valida a entrada no form.

+ +
var validate = function () {
+  var emailElement = document.getElementById(emailFieldId);
+  var valid = emailValid(formData.email); // returns true if valid, false otherwise
+
+  emailElement.setAttribute("aria-invalid", !valid);
+  setElementBorderColour(emailElement, valid); // sets the border to red if second arg is false
+};
+ +

Fornecendo Mensagens de Erro Úteis

+ +

Leia como usar alertas ARIA para melhorar forms.

+ +
A ser decidido: devemos ou combinar em um artigo ou separar em técnicas, ou ambos. Além disso, é ARIA marcação apropriada para mensagens de erro em uma página carregada após a validação do lado do servidor?
+ +

Para maiores informações usando ARIA para acessibilidade de forms, veja o documento Práticas de Cricação de WAI-ARIA.

diff --git a/files/pt-br/web/accessibility/aria/forms/index.html b/files/pt-br/web/accessibility/aria/forms/index.html new file mode 100644 index 0000000000..355c70b673 --- /dev/null +++ b/files/pt-br/web/accessibility/aria/forms/index.html @@ -0,0 +1,21 @@ +--- +title: Formulários +slug: Web/Accessibility/ARIA/forms +tags: + - ARIA + - Accessibility + - Acessibilidade + - Rótulos + - WebMechanics + - formulários +translation_of: Web/Accessibility/ARIA/forms +--- +

As páginas a seguir fornecem várias técnicas para melhorar a acessibilidade nos formulários web:

+ + + +

Ver também o Artigo do Yahoo! sobre validação de formulário e ARIA, cobrindo muito do mesmo conteúdo.

diff --git a/files/pt-br/web/accessibility/aria/forms/multipart_labels/index.html b/files/pt-br/web/accessibility/aria/forms/multipart_labels/index.html new file mode 100644 index 0000000000..102274fadb --- /dev/null +++ b/files/pt-br/web/accessibility/aria/forms/multipart_labels/index.html @@ -0,0 +1,47 @@ +--- +title: Usando ARIA para rótulos com campos incorporados - Multipart labels +slug: Web/Accessibility/ARIA/forms/Multipart_labels +tags: + - ARIA + - Accessibility + - Acessibilidade + - Formulários+ARIA + - Guía + - Intermediário + - PrecisaDeConteúdo +translation_of: Web/Accessibility/ARIA/forms/Multipart_labels +--- +
+

O problema

+ +

Você tem um formulário onde existe uma pergunta simples e a resposta é mencionada na própria questão. Um exemplo clássico, que todos nós conhecemos das configurações de nossos navegadores, é a colocação "Deletar o histórico após x dias".  "Apagar o histórico após" está à esquerda da caixa de texto, x é o número, por exemplo, 21 e a palavra "dias" vem depois dessa caixa, formando uma sentença de fácil compreensão.

+ +

Se você está usando um leitor de tela tem que perceber que, quando vai para esta configuração no Firefox, escuta a pergunta "Deletar o histórico depois de 21 dias?", seguida por um aviso de que você está em uma caixa de texto contendo o número 21. Isso não é legal? Você não precisa navegar ao redor para descobrir a unidade. "Dias" pode, facilmente, ser "meses", ou "anos" em muitos diálogos comuns, não havendo maneira de descobrir, a não ser com comandos para reexaminar a tela.

+ +

A solução está em um atributo ARIA chamado aria-labelledby (aria-etiqueta liderada por). Seu parâmetro é uma cadeia de caracteres (string) que consiste de IDs dos elementos HTML que você quer concatenar em um único nome acessível.

+ +

Tanto o atributo aria-labelledby, como o aria-describedby (aria-descrito por), são especificados no elemento de formulário que será rotulado, por exemplo uma <input>. Em ambas as situações, as ligações do controle da rotulagem for/label, que podem, também, estar presentes, serão substituídas pelo atributo aria-labelledby. Se você oferecer o atributo aria-labelledby em uma página HTML, então deve, da mesma forma, providenciar uma arquitetura de rótulo que vá, igualmente, apoiar os navegadores mais antigos, que ainda não têm suporte ARIA. Com Firefox 3, seus utilizadores cegos conseguem, automaticamente, melhor acessibilidade com o novo atributo, mas quem utiliza navegadores antigos não sofrerá abandono no escuro, desta forma.

+ +

Exemplo:

+Desligar o computador após  minutos + +
<input aria-labelledby="labelShutdown shutdownTime shutdownUnit" type="checkbox" />
+<span id="labelShutdown">Shut down computer after</span>
+<input aria-labelledby="labelShutdown shutdownTime shutdownUnit" id="shutdownTime" type="text" value="10" />
+<span id="shutdownUnit"> minutes</span>
+
+ +

Uma nota para quem usa  JAWS 8

+ +

O JAWS 8.0 tem a sua própria lógica para encontrar os labels e isso o faz, sempre, substituir a caixa de texto com o accessibleName que uma página HTML recebe. Quanto ao JAWS 8, eu ainda não encontrei uma maneira de fazê-lo aceitar o label do exemplo acima. Mas o NVDA e o Window-Eyes fazem isso muito bem e a Orca, no Linux, também não apresenta problemas.  (Os autores do artigo, são: bunnybooboo, kscarfone, StephenKelly, Kritz, Fredchat, Sheppy, Aaronlev)

+ +
TBD: adicione mais informação de compatibilidade
+ +

Isto pode ser executado sem ARIA?

+ +

O membro da comunidade Ben Millard apontou, numa publicação em um blogue, que os controles podem ser embutidos nos labels, como mostrado no exemplo acima, usando HTML 4, controls can be embedded in labels as shown in the above example using HTML 4, simplesmente com a incorporação da entrada (input) no rótulo (label). Agradecemos pela informação, Ben! É muito útil e deixa claro que algumas técnicas que estão disponíveis há anos escapam, às vezes, até mesmo aos gurus. Esta técnica funciona em Firefox; entretanto, isso não é verdade para muitos outros navegadores, inclusive IE. Para labels com controles de formulários embutidos o uso do atributo aria-labelledby ainda é a melhor abordagem.

+ +

 

+
+ +

 

diff --git a/files/pt-br/web/accessibility/aria/guia_para_implementar_o_leitor_de_tela_aria/index.html b/files/pt-br/web/accessibility/aria/guia_para_implementar_o_leitor_de_tela_aria/index.html new file mode 100644 index 0000000000..73b9605ef1 --- /dev/null +++ b/files/pt-br/web/accessibility/aria/guia_para_implementar_o_leitor_de_tela_aria/index.html @@ -0,0 +1,35 @@ +--- +title: Guia para implementar o leitor de tela ARIA +slug: Web/Accessibility/ARIA/Guia_para_implementar_o_leitor_de_tela_ARIA +tags: + - ARIA + - Acessibilidade +translation_of: Web/Accessibility/ARIA/ARIA_Screen_Reader_Implementors_Guide +--- +

Regiões Ativas

+ +

Este é apenas um guia. Uma marcação de região ativa é uma área complexa que é algo aberto à interpretações. O que segue pretende prover um guia de implementação que respeita a necessidade dos desenvolvedores de leitores de tela para tentar novas coisas. A intenção é chegar a um balanço entre providenciar um guia útil em como usar o significado de marcação pretendido

+ +

Interpretando a marcação de região ativa WAI-ARIA

+ +
    +
  1. Mudanças ativas são são dicas: Em geral marcação de região ativa é dado pelo autor como dicas, e a tecnologia assistiva pode permitir , site or even region-specific settings, assim como heurística para ajudar com mudanças ativas nas páginas que não têm dicas WAI-ARIA.
  2. +
  3. Opcionalmente, criar uma segunda, queue adicional se o usuário configurar um segundo canal de hardware: Se há dois canais para apresentação (i.e. text-to-speech e display Braile), então duas queues podem ser mantidas para permitir apresentação paralela. Os canais poderiam se configurados pelo usuário para apresentar regiões ativas baseada em vez ou prioridades.
  4. +
  5. Regiões ocupadas: Qualquer alteração numa região marcada com aria-busy="true" não deve ser adicionada à queue até que aquele atributo seja limpo.
  6. +
  7. Prioridade (aria-live ou a partir da vez) tem primeira precedência: itens deveriam ser adicionados à queue baseadas no seu nível de prioridade da propriedade aria-live ou inerente da vez (i.e. role="log" é prioridade por padrão). Itens assertivos são os primeiros então nível de prioridade. Alternativamente, implementações podem escolher ter uma política de limpeza mais items de prioridade, i.e. itens assertivos limpam qualquer item de prioridade da queue.
  8. +
  9. Tempo toma a segunda procedência: Priorizar itens com o mesmo nível de prioridade de acordo com quando o evento ocorre (eventos anteriores vêm primeiro). Itens presentes do mesmo nível de prioridade na ordem do que ocorreu primeiro.
  10. +
  11. Regiões atômicas (aria-atomic="true")  com mudanças múltiplas não deveriam estar presentes duas vezes com o mesmo conrteúdo. Como um novo evento para uma região atômica é adicionada à queue e remove um evento anterior para a mesma região. É provavelmente desejável que tenha pelo menos um pequeno timeout antes de apresentar mudanças numa região atômica, com a finalidade de evitar apresentar a região duas vezes para duas mudançasque ocorrem rapidamente uma após a outra.
  12. +
  13. Inclua labels quando estiver apresntando mudanças: se a mudança ocorre em algo com um label de alguma forma  semântico, fale o label. Isso é particularmente importante para mudanças em data cells, onde os headers column e row fornecem informação contextual importante.
  14. +
+ +

Ideias para Configurações e Heurística

+ +
    +
  1. Permitir uma voz diferente (em text-to-speech) ou outras características de apresentação para setar mudanças ativas seperadamente.
  2. +
  3. Quando não há marcação WAI-ARIA presente, automaticamente apresenta algumas mudanças a mesnos que o usuário configure todas as mudanças ativas para desligado. Por exemplo, mudanças automáticas de fala que são causadas pela própria entrada do usuário, como parte do contexto daquela entrada.
  4. +
  5. Permitir configurações globais para desligar a apresentação de mudanças ativas, apresentar todas as mudanças ativas, use marcação, ou seja "esperto" (use heurística).
  6. +
+ +

Detalhes para Processamento via APIs Platform Acessibility

+ +

Esperamos que o desenvolvedor do navegador irá trabalhar para fornecer implementações consistentes. A imlementação mais completa das regiões ativas atualmente está no Firefox 3. Aqui está como regiões ativas WAI-ARIA são expostas no Firefox 3.

diff --git a/files/pt-br/web/accessibility/aria/index.html b/files/pt-br/web/accessibility/aria/index.html new file mode 100644 index 0000000000..75a8173c54 --- /dev/null +++ b/files/pt-br/web/accessibility/aria/index.html @@ -0,0 +1,148 @@ +--- +title: ARIA +slug: Web/Accessibility/ARIA +tags: + - AJAX + - ARIA + - Accessibility + - Acessibilidade + - Introdução + - JavaScript ARIA + - TopicStub + - W3C + - WAI-ARIA + - WAI-ARIA+HTML +translation_of: Web/Accessibility/ARIA +--- +

Aplicações para a Internet Ricas em Acessibilidade - Accessible Rich Internet Applications (ARIA) definem as formas de tornar o conteúdo e as aplicações da Rede Mundial - Web - (especialmente aqueles desenvolvidos com Ajax e JavaScript) mais acessíveis às pessoas com deficiência.

+ +

Por exemplo, a ARIA permite a marcação de regiões importantes na página (como uma caixa de busca, um cabeçalho, chamadas "pontos de referência") para facilitar a navegação (agilizam a utilização de leitores de tela, por exemplo), JavaScript para widgets, sugestões de preenchimento de formulário e mensagens de erro, atualizações de conteúdo em tempo real e muito mais.

+ +

O ARIA é um conjunto de atributos especiais para a acessibilidade, que pode ser adicionado a qualquer linguagem marcação, mas é especialmente adequado para HTML. O atributo da função define qual é o modelo de objeto (tais como um artigo, um alerta, ou algo que deslize). Há atributos adicionais ARIA que fornecem outras propriedades úteis, como a descrição de uma forma, ou o valor atual em uma barra de progresso.

+ +

O conjunto ARIA pode ser implementado nos navegadores mais populares e em leitores de tela. No entanto, as implementações variam e as tecnologias mais antigas não as suportam bem. Utilize um ARIA compatível, ou solicite a alguém que o atualize para as tecnologias mais recentes.

+ +
+

Nota: Por favor, participe e torne o ARIA melhor para as pessoas! Não tem muito tempo? Envie sugestões para acessibilidade - lista de correspondência da Mozilla, ou #accessibility canal IRC.

+
+ + + + + + + + + + + + + +
+

Começando em ARIA

+ +
+
Apresentando ARIA
+
Uma rápida introdução sobre como tornar um conteúdo dinâmico acessível com ARIA: Veja, também, o clássico ARIA intro by Gez Lemon, de 2008.
+
Aplicações Web e ARIA FAQ
+
Respostas às perguntas frequentes sobre WAI-ARIA e sobre por que é necessário tornar as aplicações web acessíveis.
+
Vídeos de Leitores de Tela Utilizando ARIA
+
Veja exemplos reais e simplificados de vídeos, por toda a web, que incluem o "antes" e o "depois" da acessibilidade. 
+
Usando ARIA com HTML
+
Um guia prático para desenvolvedores. Traz sugestões sobre quais atributos ARIA usar com os elementos HTML. As sugestões são baseadas em realidades implementadas.
+
+ +

Melhorias Simples ARIA

+ +
+
Melhorando a Navegação nas Páginas com os Pontos de Referência ARIA
+
Uma deliciosa introdução à utilização de pontos de referência para beneficiar a navegação pelas páginas da internete por quem utiliza os leitores de tela ARIA. Veja, também, as notas da implementação de pontos de referência ARIA e exemplos de situações reais (atualizadas a partir de 11 de julho).
+
Melhorando a Acessibilidade nos Formulários
+
O conjunto ARIA não é, apenas, para conteúdo dinâmico! Aprenda como aperfeiçoar a acessibilidade nos formulários HTML utilizando alguns atributos adicionais ARIA. 
+
Regiões dinâmicas (trabalho em progresso)
+
As regiões dinâmicas oferecem sugestões, aos leitores de tela, sobre como controlar as alterações nos conteúdos das páginas.
+
Utilizando a ARIA Regiões Dinâmicas para Apresentar as Alterações no Conteúdo
+
Um resumo sobre as regiões dinâmicas, pelos criadores do programa de leitura de tela  JAWS. Note que as regiões dinâmicas também são suportadas pela NVDA, no Firefox e VoiceOver, com Safari.
+
+ +

ARIA para Widgets Roteirizados

+ +
+
Navegação pelo Teclado e Foco para Widgets em JavaScript
+
A primeira etapa do desenvolvimento de um widget acessível com JavaScript é tornà-lo navegável através do teclado. Este artigo descreve as fases dessa operação. O artigo Yahoo! Administrando focos também é de grande ajuda.
+
Guia de Estilo para Navegação através do Teclado
+
Um desafio em ARIA é conseguir que os desenvolvedores executem procedimentos estáveis - claramente melhores para quem os utiliza. Este guia de estilos descreve a interface de teclado para os widgets comuns.
+
+ +

Recursos ARIA

+ +
+
A Técnica na Execução de Widgets, Tutoriais e Exemplos
+
Precisa de um controle dezlizante, um menu, ou algum outro tipo de widget? Encontre, aqui, as maneiras de obtê-los.
+
Bibliotecas  JavaScript UI com ARIA habilitada
+
Se você está começando um projeto novo, escolha uma biblioteca UI para widget com suporte a ARIA já embutido. Atenção: isto é de 2009 -- este conteúdo deve ser movido para uma página MDN, onde pode ser atualizado.
+
Acessibilidade em HTML5 e Aplicações Ricas - Materiais de Oficina CSUN 2012
+
Inclua apresentações de eslaides e exemplos.
+
+
+

Lista de Correspondência

+ +
+
ARIA Livre no Grupo Google
+
Área de perguntas sobre ARIA, bem como de fazer sugestões para melhorar a documentação ARIA encontrada nestas páginas.
+
+ +

Blogs

+ +

As informações ARIA nos blogues tendem a ficar desatualizadas rapidamente. Sem contar que há outras boas informações fora deles, de desenvolvedores que estão tornando o conjunto Aria funcional hoje.

+ +

Paciello Group

+ +

Cultura Acessível

+ +

Encontrando Erros

+ +

Erros nos arquivos ARIA em navegadores, leitores de telas e bibliotecas JavaScript.

+ +

Exemplos

+ +
+
Exemplos de Bibliotecas ARIA
+
Um conjunto de exemplos de arquivos das bibliotecas base, com os quais fica muito fácil aprender.
+
Demonstração de Biblioteca para a Accessibilidade JS em Widget
+
Dojo, jQueryFluid, YUI
+
+ +
+
Correio Eletrônico Yahoo!
+
A Yahoo! colocou tudo reunido com o Yahoo! e-mail, uma aplicação para a web que parece um aplicativo nativo. E funciona muito bem. Em uma análise do e-mail Yahoo! pelo leitor de tela, Marco Zehe diz: "Que o bom trabalho permaneça!".
+
+ +
+
Pesquisa Yahoo!
+
A Yahoo! tem feito um trabalho incrível no avanço do ARIA, aplicando suas posibilidades de forma plena e compartilhando suas técnicas. A Pesquisa Yahoo! usa uma combinação de pontos de referência ARIA, regiões dinâmicas e widgets.
+
+ +

Esforços pela Padronização

+ +
+
Uma Visão Geral das Atividades WAI-ARIA na W3C
+
Uma visão geral oficial dos esforços de padronização da WAI-ARIA pela Iniciativa de tornar a Web Acessível (Web Accessibility Initiative - WAI)
+
Especificações WAI-ARIA
+
As especificações W3C são referências úteis. Note que, nesta fase, é importante testar a compatibilidade, uma vez que as implementações ainda estão inconsistentes.
+
Práticas Oficiais WAI-ARIA
+
Conforme as especificações da W3C WAI-ARIA, a excelênca nas práticas oficiais representam o futuro ideal - o dia em que todos os autores possam trabalhar em suas realizações sobre uma base ARIA consistente em navegadores e leitores de tela. A documentação W3C proporcionará a você uma visão aprofundada de ARIA.
+
+ Por enquanto, desenvolvedores web que implementem ARIA devem priorizar a compatibilidade. Use as melhores documentações das práticas e exemplos baseados em implementações atuais.
+
A Força-Tarefa da Acessibilidade Open AJAX
+
Os centros de pesquisa Open AJAX envolvem ferramentas de desenvolvimento, modelos de arquivos e testes automatizados para ARIA.
+
Em Construção: Técnicas ARIA  WCAG 2.0
+
A comunidade necessita de um conjunto completo de técnicas  WCAG voltadas para WAI-ARIA + HTML, a fim de que as organizações possam estar confortáveis ao proclamar que o teor de suas ARIAs habilitadas é compatível com essas técnicas WCAG. É muito importante que as regulamentações, ou políticas, sejam baseadas em WCAG.
+
+
+ + +
+
Accessibilidade, AJAX, JavaScript
+
+
diff --git a/files/pt-br/web/accessibility/aria/roles/index.html b/files/pt-br/web/accessibility/aria/roles/index.html new file mode 100644 index 0000000000..d26540b113 --- /dev/null +++ b/files/pt-br/web/accessibility/aria/roles/index.html @@ -0,0 +1,78 @@ +--- +title: WAI-ARIA Roles +slug: Web/Accessibility/ARIA/Roles +tags: + - ARIA + - ARIA Roles + - Acessibilidade + - Referencia + - Rôles +translation_of: Web/Accessibility/ARIA/Roles +--- +

Essa página lista referências às atribuções WAI-ARIA discutidos no MDN. Para visualizar a lista completa, veja Using ARIA: Roles, States, and Properties

+ +

{{SubpagesWithSummaries}}

+ + diff --git a/files/pt-br/web/accessibility/aria/web_applications_and_aria_faq/index.html b/files/pt-br/web/accessibility/aria/web_applications_and_aria_faq/index.html new file mode 100644 index 0000000000..4141f81ffc --- /dev/null +++ b/files/pt-br/web/accessibility/aria/web_applications_and_aria_faq/index.html @@ -0,0 +1,320 @@ +--- +title: Aplicações web e ARIA - Perguntas Frequentes (FAQ) +slug: Web/Accessibility/ARIA/Web_applications_and_ARIA_FAQ +tags: + - ARIA + - Accessibility + - Acessibilidade + - Guía + - Intro + - Introdução + - JavaScript + - W3C + - WAI-ARIA +translation_of: Web/Accessibility/ARIA/Web_applications_and_ARIA_FAQ +--- +

O que significa ARIA?

+ +

WAI-ARIA, que quer dizer Accessible Rich Internet Applications (Aplicações Ricas para uma Internete Acessível), são as especificações da Web Accessibility Initiative (Iniciativa pela Acessibilidade na Web), da W3C (World Wide Web Consortium). O conjunto ARIA oferece a maneira de tornar as aplicações e widgets da rede mundial mais acessíveis a uma diversidade maior de pessoas, incluindo quem utiliza tecnologias assistivas, como leitores de telas, ou lentes de aumento.

+ +

O conjunto ARIA fornece semânticas adicionais para descrever a função (role), estado (state) e funcionalidade de muitos controles familiares da interface de utilização, tais como menus, deslizantes, árvores e diálogos. E, também, provê informação estrutural adicional, o que auxilia os autores a identificar as áreas de referência (landmarks), regiões e malhas nas suas páginas. O conjunto ARIA habilita aplicações dinâmicas e widgets gerenciados pela JavaScript a interoperar com uma gama de tecnologias assistivas baseadas em ambiente.

+ +

Para mais informações sobre como criar widgets acessíveis com ARIA, veja a Visão geral da acessibilidade em aplicações web e widgets -  Overview of accessible web applications and widgets.

+ +

ARIA - onde tem suporte?

+ +

ARIA é um grupo de especificações relativamente novo, mas o suporte está crescendo. Uma larga variedade de navegadores comumente usados, tecnologias assistivas, conjunto de ferramentas JavaScript e aplicações, agora, suportam o conjunto ARIA. Entretanto, velhas versões destas tecnologias ainda podem estar sendo utilizadas por muita gente. Quem sabe você possa considerar a implementação de ARIA pela utilização de técnicas de aprimoramento progressivo — como adicionar ARIA usando JavaScript e não diretamente na sua marcação — no intuito de obter, graciosamente, o suporte nos navegadores e tecnologias assistivas mais antigos.

+ + + +

O conjunto ARIA encontra suporte nos seguintes navegadores:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NavegadorrVersão MínimaObservações
Firefox3.0+Funciona com NVDA,  JAWS 10+ e Orca
ChromeMais recentesO suporte a leitores de tela ainda é experimental a partir do Chrome 15
Safari4+No Safari 5 o suporte está muito melhorado.
+ Para regiões dinâmicas é preciso o Safari 5 com VoiceOver no iOS5, ou OS X Lion
Opera9.5+ +

Necessita o VoiceOver no OS X.                                                   TBD: como está funcionando atualmente?

+
Internet Explorer8+Funciona com JAWS 10+ e NVDA.                                          Não existe suporte para regiões dinâmicas no NVDA.
+ O suporte em IE9  está muito aperfeiçoado.
+ +

Em certos casos, as versões anteriores podem suportar, apenas, algumas características do conjunto ARIA. Tabelas mais detalhadas da compatibilidade de navegadores estão disponíveis a partir de múltiplas fontes:

+ + + +

Tecnologias Assistivas

+ +

As tecnologias assistivas estão, progressivamente, abraçando o conjunto ARIA. Algumas delas incluem:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Tecnologia AssistivaVersão mínima para o conjunto ARIA básicoVersão mínima para regiões dinâmicas e suportes de alerta
NVDA2010.2
+ (NVDA é, sempre, um aprimoramento gratuito)
2011.1 para Firefox, sem apoio para regiões dinãmicas no IE a partir de 2011.2.
Orca? (TBD)? (TBD)
VoiceOverOSX 10.5,
+ iOS 4
OS X 10.7
+ iOS 5
JAWS810
Window-Eyes7Atualmente, sem suporte para regiões vivas
ZoomText?Atualmente, sem suporte para regiões vivas
+ +

Nota: as primeiras versões destas ferramentas tinham, muitas vezes, implementações ARIA parciais, ou com problemas.

+ +

Para notas sobre o suporte  JAWS para ARIA a partir do JAWS 10, veja este artigo do Paciello Group: JAWS Support for ARIA.

+ +

O Conjunto de Ferramentas JavaScript

+ +

Funções, estados, e propriedades ARIA foram adicionadas a uma série de conjuntos de ferramentas JavaScript populares para a interface de utilização, incluindo:

+ + + +

Para mais informações sobre acessibilidade com o conjunto de ferramentas JavaScript, leia:

+ + + +

Você pode me dar um exemplo do conjunto ARIA em ação?

+ +

Com prazer: ) Eis, aqui, a marcação para um widget de uma barra de progresso:

+ +
<div id="percent-loaded" role="progressbar" aria-valuenow="75" aria-valuemin="0" aria-valuemax="100" />
+ +

Esta barra de progresso é construída usando uma <div>, o que não é muito descritivo. Infelizmente, não há muitas etiquetas semânticas disponíveis para desenvolvedores em HTML 4, logo, nós precisamos incluir as funções e propriedades ARIA. Estas são especificadas pela adição de atributos ao elemento. Neste exemplo, o atributo role="progressbar" informa, ao navegador, que este elemento é, agora, um widget de barra de progresso movimentado pela JavaScript. Os atributos aria-valuemin (aria-valor mínimo) e aria-valuemax (aria-valor máximo) determinam os valores mínimo e máximo para essa barra de progresso e o aria-valuenow (aria-valor agora) descreve o seu estado atual.

+ +

Além de inseridos diretamente na marcação, os atributos ARIA podem ser adicionados ao elemento e atualizados dinamicamente pela utilização de códigos em JavaScript, como este:

+ +
// Find the progress bar <div> in the DOM.
+var progressBar = document.getElementById("percent-loaded");
+
+// Set its ARIA roles and states, so that assistive technologies know what kind of widget it is.
+progressBar.setAttribute("role", "progressbar");
+progressBar.setAttribute("aria-valuemin", 0);
+progressBar.setAttribute("aria-valuemax", 100);
+
+// Create a function that can be called at any time to update the value of the progress bar.
+function updateProgress(percentComplete) {
+  progressBar.setAttribute("aria-valuenow", percentComplete);
+}
+ +

 

+ +

Se eu adicionar ARIA a estruturação, ou o comportamento, da minha página vão mudar?

+ +

Não, o conjunto ARIA é disponibilizado, apenas, para as tecnologias assistivas APIs (Interface de Programação de Aplicações) e não afeta as funcionalidades nativas dos navegadores em relação ao DOM, nem ao estilo. Do ponto de vista dos navegadores, a HTML nativa define o significado semântico e o comportamento de um elemento, com os atributos ARIA agindo como uma camada de topo, com a finalidade de dar suporte à TA/AT API. Embora o conjunto ARIA não vá alterar qualquer modelo, bem como todos os atributos HTML, a CSS pode tirar vantagem dos atributos ARIA como seletores de elemento. Isto pode providenciar um mecanismo conveniente para o modelo de widgets capacitados com ARIA.

+ +
.tab-panel[aria-hidden="true"] {
+  display: none;
+  }
+
+.tab-panel[aria-hidden="false"] {
+  display: block;
+  }
+
+ +

E quanto à validação?

+ +

Os novos atributos introduzidas em ARIA, tais como role e aqueles com o prefixo aria-, não são, oficialmente, parte das especificações HTML 4, ou XHTML 4. Como resultado, as páginas que incluem ARIA podem não validar o uso ferramentas como o  W3C's Markup Validator.

+ +

A primeira solução potencial para este problema é evitar inserir as funções e os estados ARIA diretamente na sua marcação. Em vez disso, use a JavaScript para adicionar, dinamicamente, o conjunto ARIA à sua página, como mostrado na resposta à " Você pode me dar um exemplo do conjunto ARIA em ação?". A sua página ainda vai ser, teoricamente, inválida, mas vai passar todas as verificações de validação estática corretamente.

+ +

Outra alternativa é usar a declaração de tipo de documento (doctype) HTML5, que inclui suporte embutido para ARIA. O validador HTML5  do W3C nunca vai encontrar usos inválidos de ARIA em páginas HTML5 para você.

+ +

Como a HTML 5 se relaciona com o conjunto ARIA?

+ +

A HTML 5 introduz uma série de novas etiquetas semânticas úteis na linguagem HTML. Algumas delas se justapõe, diretamente, com as funções disponíveis em ARIA, tais como o novo elemento <progress>. Nos casos em que o navegador suporte uma marcação HTML que também exista em ARIA, normalmente, não há a necessidade de acrescentar as funções e estados ARIA ao elemento. O conjunto ARIA engloba muitas funções, estados e propriedades que não estão disponíveis em HTML5, então, estas continuarão sendo úteis aos desenvolvedores que usam HTML5. Para mais informações, Steve Faulkner escreveu um ótimo  overview of the relationship between HTML5 and ARIA (em inglês).

+ +

Degrading Gracefully de HTML5 para ARIA

+ +

Ao entregar conteúdo a navegadores que não são sensíveis à linguagem HTML5, você pode considerar uma gracefully degrading para o uso do conjunto ARIA, quando necessário. Assim, utilizando o exemplo da barra de progresso, você pode fazer a alteração para uma "role="progressbar", nos casos em que a marcação <progressbar> não for suportada.

+ +

Aqui você tem um exemplo da marcação usada para uma barra de progresso em HTML5:

+ +
<!DOCTYPE html>
+<html>
+  <head><title>Gracefully degrading progress bar</title></head>
+  <body>
+    <progress id="progress-bar" value="0" max="100">0% complete</progress>
+    <button id="update-button">Update</button>
+ </body>
+</html>
+
+ +

...e aqui está o código JavaScript que vai garantir que a barra de progresso ainda funcione em navegadores mais antigos:

+ +
var progressBar = document.getElementById("progress-bar");
+
+// Check to see if the browser supports the HTML5 <progress> tag.
+var supportsHTML5Progress = (typeof (HTMLProgressElement) !== "undefined");
+
+function setupProgress() {
+  if (!supportsHTML5Progress) {
+    // HTML5 <progress> isn't supported in this browser, so we need to add
+    // ARIA roles and states to the element.
+    progressBar.setAttribute("role", "progressbar");
+    progressBar.setAttribute("aria-valuemin", 0);
+    progressBar.setAttribute("aria-valuemax", 100);
+  }
+}
+
+function updateProgress(percentComplete) {
+  if (!supportsHTML5Progress) {
+    // HTML5 <progress> isn't supported by this browser,
+    // so we need to update the aria-valuenow attribute
+    progressBar.setAttribute("aria-valuenow", percentComplete);
+  } else {
+    // HTML5 <progress> is supported, so update the value attribute instead.
+    progressBar.setAttribute("value", percentComplete);
+  }
+
+  progressBar.textContent = percentComplete + "% complete";
+}
+
+function initDemo() {
+  setupProgress(); // Setup the progress bar.
+
+  // Bind a click handler to the button, which will update the progress bar to 75%.
+  document.getElementById("update-button").addEventListener("click", function (e) {
+    updateProgress(75);
+    e.preventDefault();
+  }, false);
+}
+initDemo();
+
+ +

 

+ +

Como funcionam as tecnologias assistivas?

+ +

Tecnologias assistivas usam uma API (Interface de Programação de Aplicações) construída em cada sistema operacional, concebida, especificamente, para descrever as funções, estados e estruturas da interface de utilização de uma aplicação. Por exemplo, um leitor de tela utiliza esta API para ler a interface de utilização com um mecanismo de vocalização do texto, uma lente de aumento a utiliza para realçar áreas importantes - ou ativas - da tela e um teclado virtual pode utilizá-la para proporcionar um tipo de teclado mais eficiente dentro de determinado contexto - ou o controle da UI. Tecnologias assistivas, muitas vezes, também acessam uma página do DOM, do princípio ao fim, através desta API, para entender sua semântica e atributos da página.

+ +

O conjunto ARIA proporciona uma ponte entre o mundo do DOM e a área de trabalho. Os navegadores expõe os elementos capacitados com o conjunto ARIA para as APIs das tecnologias assistivas, como se estes fossem widgets nativos. Como resultado, quem os utiliza ganha uma experiência de uso muito mais consistente, na qual widgets dinâmicos, da web, impulsionados pela JavaScript são comparáveis aos seus equivalentes da área de trabalho.

+ +

 

+ +

Como experimento o uso que fiz do conjunto ARIA? Existem ferramentas gratuitas disponíveis?

+ +

Existem várias ferramentas de inspeção e depuração para ajudar você no seu teste da ação do conjunto ARIA:

+ + + +

Há vários leitores de tela gratuitos, ou de código aberto, que podem ser utilizados, para você colocar a mão na massa nos seus testes com ARIA. Estes incluem:

+ + + +

Quando você estiver testando um leitor de tela, mantenha dois pontos-chave em mente:

+ +
    +
  1. Experimentadores ocasionais de leitores de tela nunca vão opinar suficientemente, por isso, teste e obtenha respostas de quem, realmente, utiliza essas tecnologias.
  2. +
  3. A acessibilidade vai muito além de, apenas, dar suporte aos leitores de tela. Tente experimentar uma variedade de técnicas de usabilidade e acessibilidade.
  4. +
+ +

Outras ferramentas de teste úteis e técnicas para aplicativos e widgets com habilitação ARIA:

+ + + +

Onde acontecem as discussões sobre ARIA?

+ + + +

Onde posso aprender mais sobre ARIA?

+ + + +

a autoria do artigo é de: morenoh149, kscarfone, akhabibullina, xfq, Fredchat, mpiotrowicz, Sheppy, BrendanMcKeon, anastasia, jswisher, Aaronlev, colinbdclark.

+ +

 

diff --git a/files/pt-br/web/accessibility/aria/widgets/index.html b/files/pt-br/web/accessibility/aria/widgets/index.html new file mode 100644 index 0000000000..136aecae2e --- /dev/null +++ b/files/pt-br/web/accessibility/aria/widgets/index.html @@ -0,0 +1,10 @@ +--- +title: widgets +slug: Web/Accessibility/ARIA/widgets +tags: + - Accessibility + - NeedsTranslation + - TopicStub +translation_of: Web/Accessibility/ARIA/widgets +--- +

This page was auto-generated because a user created a sub-page to this page.

diff --git "a/files/pt-br/web/accessibility/aria/widgets/vis\303\243o_geral/index.html" "b/files/pt-br/web/accessibility/aria/widgets/vis\303\243o_geral/index.html" new file mode 100644 index 0000000000..6e8cb06ae2 --- /dev/null +++ "b/files/pt-br/web/accessibility/aria/widgets/vis\303\243o_geral/index.html" @@ -0,0 +1,72 @@ +--- +title: Visão geral +slug: Web/Accessibility/ARIA/widgets/Visão_geral +tags: + - Acessibilidade + - JavaScript + - Landing + - PrecisaAtualizar +translation_of: Web/Accessibility/ARIA/widgets/overview +--- +
Aviso: precisa de atualização
+ +

Introdução 

+ +

Alguns exemplos funcionais e boas práticas na construção de widgets acessíveis aplicando JavaScript.

+ +

Recursos Gerais

+ + + +

Caixa de seleção

+ + + + + + + +

Deslizantes

+ + + +

Abas

+ + + +

Combo-box

+ + + + + + + +

Validação de Formulários

+ + + +

Tabelas

+ + diff --git a/files/pt-br/web/accessibility/at-apis/gecko/index.html b/files/pt-br/web/accessibility/at-apis/gecko/index.html new file mode 100644 index 0000000000..1abe2834d5 --- /dev/null +++ b/files/pt-br/web/accessibility/at-apis/gecko/index.html @@ -0,0 +1,10 @@ +--- +title: Gecko +slug: Web/Accessibility/AT-APIs/Gecko +tags: + - Accessibility + - NeedsTranslation + - TopicStub +translation_of: Mozilla/Tech/Accessibility/AT-APIs/Gecko +--- +

{{wiki.localize('System.API.page-generated-for-subpage')}}

diff --git a/files/pt-br/web/accessibility/at-apis/gecko/roles/index.html b/files/pt-br/web/accessibility/at-apis/gecko/roles/index.html new file mode 100644 index 0000000000..a3e835eb0b --- /dev/null +++ b/files/pt-br/web/accessibility/at-apis/gecko/roles/index.html @@ -0,0 +1,255 @@ +--- +title: Gecko Roles +slug: Web/Accessibility/AT-APIs/Gecko/Roles +translation_of: Mozilla/Tech/Accessibility/AT-APIs/Gecko/Roles +--- +

« AT APIs Support Page

+ +

This page offers a list of accessible roles used in Gecko. Role constants are defined in the nsIAccessibleRole interface.

+ +
+
ROLE_NOTHING
+
Used when the accessible item doesn't have a strongly defined role.
+
ROLE_TITLEBAR
+
Represents a title or caption bar for a window. Used by MSAA only, this is supported automatically by Microsoft Windows.
+
ROLE_MENUBAR
+
Represents the menu bar (positioned beneath the title bar of a window on most platforms or at the top of the screen on Mac OS X) from which menus are selected by the user.
+
ROLE_SCROLLBAR
+
Represents a vertical or horizontal scroll bar, which is part of the client area or used in a control.
+
ROLE_GRIP
+
Represents a special mouse pointer, which allows a user to manipulate user interface elements such as windows. For example, a user clicks and drags a sizing grip in the lower-right corner of a window to resize it
+
ROLE_SOUND
+
Represents a system sound, which is associated with various system events.
+
ROLE_CURSOR
+
Represents the system mouse pointer.
+
ROLE_CARET
+
Represents the system caret.
+
ROLE_ALERT
+
Represents an alert or a condition that a user should be notified about. Assistive Technologies typically respond to the role by reading the entire onscreen contents of containers advertising this role. Should be used for warning dialogs, etc.
+
ROLE_WINDOW
+
Represents the window frame, which contains child objects such as a title bar, client, and other objects contained in a window. The role is supported automatically by Microsoft Windows.
+
ROLE_INTERNAL_FRAME
+
A sub-document.
+
ROLE_MENUPOPUP
+
Represents a menu, which presents a list of options from which the user can make a selection to perform an action.
+
ROLE_MENUITEM
+
Represents a menu item, which is an entry in a menu that a user can choose to carry out a command, select an option.
+
ROLE_TOOLTIP
+
Represents a tooltip that provides helpful hints; this is generally displayed at the mouse cursor position.
+
ROLE_APPLICATION
+
Represents a main window for an application.
+
ROLE_DOCUMENT
+
Represents a document window. A document window is always contained within an application window.
+
ROLE_PANE
+
Represents a pane within a frame or document window. Users can navigate between panes and within the contents of the current pane, but cannot navigate between items in different panes. Thus, panes represent a level of grouping lower than frame windows or documents, but above individual controls.
+
ROLE_CHART
+
Represents a graphical image used to represent data.
+
ROLE_DIALOG
+
Represents a dialog box or message box.
+
ROLE_BORDER
+
Represents a window border.
+
ROLE_GROUPING
+
Logically groups other objects.
+
ROLE_SEPARATOR
+
Used to visually divide a space into two regions, such as a separator menu item or a bar that divides split panes within a window.
+
ROLE_TOOLBAR
+
Represents a toolbar, which is a grouping of controls (push buttons or toggle buttons) that provides easy access to frequently used features.
+
ROLE_STATUSBAR
+
Represents a status bar, which is an area at the bottom of a window that displays information about the current operation, state of the application, or selected object. The status bar has multiple fields, which display different kinds of information.
+
ROLE_TABLE
+
Represents a table that contains rows and columns of cells, and optionally, row headers and column headers.
+
ROLE_COLUMNHEADER
+
Represents a column header, providing a visual label for a column in a table.
+
ROLE_ROWHEADER
+
Represents a row header, which provides a visual label for a table row.
+
ROLE_COLUMN
+
Represents a column of cells within a table.
+
ROLE_ROW
+
Represents a row of cells within a table.
+
ROLE_CELL
+
Represents a cell within a table.
+
ROLE_LINK
+
Represents a link to something else. This object might look like text or a graphic, but it acts like a button.
+
ROLE_HELPBALLOON
+
Displays a Help topic in the form of a ToolTip or Help balloon.
+
ROLE_CHARACTER
+
Represents a cartoon-like graphic object, such as Microsoft Office Assistant, which is displayed to provide help to users of an application.
+
ROLE_LIST
+
Represents a list box, allowing the user to select one or more items.
+
ROLE_LISTITEM
+
Represents an item in a list.
+
ROLE_OUTLINE
+
Represents an outline or tree structure, such as a tree view control, that displays a hierarchical list and allows the user to expand and collapse branches.
+
ROLE_OUTLINEITEM
+
Represents an item in an outline or tree structure.
+
ROLE_PAGETAB
+
Represents a page tab, it is a child of a page tab list.
+
ROLE_PROPERTYPAGE
+
Represents a property sheet.
+
ROLE_INDICATOR
+
Represents an indicator, such as a pointer graphic, that points to the current item.
+
ROLE_GRAPHIC
+
Represents a picture.
+
ROLE_STATICTEXT
+
Represents read-only text, such as labels for other controls or instructions in a dialog box. Static text cannot be modified or selected.
+
ROLE_TEXT_LEAF
+
Represents selectable text that allows edits or is designated read-only.
+
ROLE_PUSHBUTTON
+
Represents a push button control.
+
ROLE_CHECKBUTTON
+
Represents a check box control.
+
ROLE_RADIOBUTTON
+
Represents an option button, also called a radio button. It is one of a group of mutually exclusive options. All objects sharing a single parent that have this attribute are assumed to be part of single mutually exclusive group.
+
ROLE_COMBOBOX
+
Represents a combo box; an edit control with an associated list box that provides a set of predefined choices.
+
ROLE_DROPLIST
+
Represents the calendar control.
+
ROLE_PROGRESSBAR
+
Represents a progress bar, dynamically showing the user the percent complete of an operation in progress.
+
ROLE_DIAL
+
Represents a dial or knob whose purpose is to allow a user to set a value.
+
ROLE_HOTKEYFIELD
+
Represents a hot-key field that allows the user to enter a combination or sequence of keystrokes.
+
ROLE_SLIDER
+
Represents a slider, which allows the user to adjust a setting in given increments between minimum and maximum values.
+
ROLE_SPINBUTTON
+
Represents a spin box, which is a control that allows the user to increment or decrement the value displayed in a separate "buddy" control associated with the spin box.
+
ROLE_DIAGRAM
+
Represents a graphical image used to diagram data.
+
ROLE_ANIMATION
+
Represents an animation control, which contains content that changes over time, such as a control that displays a series of bitmap frames.
+
ROLE_EQUATION
+
Represents a mathematical equation. It is used by MATHML.
+
ROLE_BUTTONDROPDOWN
+
Represents a button that drops down a list of items.
+
ROLE_BUTTONMENU
+
Represents a button that drops down a menu.
+
ROLE_BUTTONDROPDOWNGRID
+
Represents a button that drops down a grid.
+
ROLE_WHITESPACE
+
Represents blank space between other objects.
+
ROLE_PAGETABLIST
+
Represents a container of page tab controls.
+
ROLE_CLOCK
+
Represents a control that displays time.
+
ROLE_SPLITBUTTON
+
Represents a button on a toolbar that has a drop-down list icon directly adjacent to the button.
+
ROLE_IPADDRESS
+
Represents an edit control designed for an Internet Protocol (IP) address. The edit control is divided into sections for the different parts of the IP address.
+
ROLE_ACCEL_LABEL
+
Represents a label control that has an accelerator.
+
ROLE_ARROW
+
Represents an arrow in one of the four cardinal directions.
+
ROLE_CANVAS
+
Represents a control that can be drawn into and is used to trap events.
+
ROLE_CHECK_MENU_ITEM
+
Represents a menu item with a check box.
+
ROLE_COLOR_CHOOSER
+
Represents a specialized dialog that lets the user choose a color.
+
ROLE_DATE_EDITOR
+
Represents control whose purpose is to allow a user to edit a date.
+
ROLE_DESKTOP_ICON
+
An iconified internal frame in an ROLE_DESKTOP_PANE.
+
ROLE_DESKTOP_FRAME
+
A desktop pane. A pane that supports internal frames and iconified versions of those internal frames.
+
ROLE_DIRECTORY_PANE
+
A directory pane. A pane that allows the user to navigate through and select the contents of a directory. May be used by a file chooser.
+
ROLE_FILE_CHOOSER
+
A file chooser. A specialized dialog that displays the files in the directory and lets the user select a file, browse a different directory, or specify a filename. May use the directory pane to show the contents of a directory.
+
ROLE_FONT_CHOOSER
+
A font chooser. A font chooser is a component that lets the user pick various attributes for fonts.
+
ROLE_CHROME_WINDOW
+
Frame role. A top level window with a title bar, border, menu bar, etc. It is often used as the primary window for an application.
+
ROLE_GLASS_PANE
+
A glass pane. A pane that is guaranteed to be painted on top of all panes beneath it.
+
ROLE_HTML_CONTAINER
+
A document container for HTML, whose children represent the document content.
+
ROLE_ICON
+
A small fixed size picture, typically used to decorate components.
+
ROLE_LABEL
+
Presents an icon or short string in an interface.
+
ROLE_LAYERED_PANE
+
A layered pane. A specialized pane that allows its children to be drawn in layers, providing a form of stacking order. This is usually the pane that holds the menu bar as well as the pane that contains most of the visual components in a window.
+
ROLE_OPTION_PANE
+
A specialized pane whose primary use is inside a dialog.
+
ROLE_PASSWORD_TEXT
+
A text object uses for passwords, or other places where the text content is not shown visibly to the user.
+
ROLE_POPUP_MENU
+
A temporary window that is usually used to offer the user a list of choices, and then hides when the user selects one of those choices.
+
ROLE_RADIO_MENU_ITEM
+
A radio button that is a menu item.
+
ROLE_ROOT_PANE
+
A root pane. A specialized pane that has a glass pane and a layered pane as its children. Its children can include scroll bars and a viewport.
+
ROLE_SCROLL_PANE
+
A scroll pane. An object that allows a user to incrementally view a large amount of information.
+
ROLE_SPLIT_PANE
+
A split pane. A specialized panel that presents two other panels at the same time. Between the two panels is a divider the user can manipulate to make one panel larger and the other panel smaller.
+
ROLE_TABLE_COLUMN_HEADER
+
The header for a column of a table.
+
ROLE_TABLE_ROW_HEADER
+
The header for a row of a table.
+
ROLE_TEAR_OFF_MENU_ITEM
+
A menu item used to tear off and reattach its menu.
+
ROLE_TERMINAL
+
Represents an accessible terminal.
+
ROLE_TEXT_CONTAINER
+
Collection of objects that constitute a logical text entity.
+
ROLE_TOGGLE_BUTTON
+
A toggle button. A specialized push button that can be checked or unchecked, but does not provide a separate indicator for the current state.
+
ROLE_TREE_TABLE
+
Representas a control that is capable of expanding and collapsing rows as well as showing multiple columns of data.
+
ROLE_VIEWPORT
+
A viewport. An object usually used in a scroll pane. It represents the portion of the entire data that the user can see. As the user manipulates the scroll bars, the contents of the viewport can change.
+
ROLE_HEADER
+
Header of a document page.
+
ROLE_FOOTER
+
Footer of a document page.
+
ROLE_PARAGRAPH
+
A paragraph of text.
+
ROLE_RULER
+
A ruler such as those used in word processors.
+
ROLE_AUTOCOMPLETE
+
A text entry having dialog or list containing items for insertion into an entry widget, for instance a list of words for completion of a text entry.
+
ROLE_EDITBAR
+
An editable text object in a toolbar.
+
ROLE_ENTRY
+
An control whose textual content may be entered or modified by the user.
+
ROLE_CAPTION
+
A caption describing another object.
+
ROLE_DOCUMENT_FRAME
+
A visual frame or container which contains a view of document content. Document frames may occur within another Document instance, in which case the second document may be said to be embedded in the containing instance. HTML frames are often ROLE_DOCUMENT_FRAME. Either this object, or a singleton descendant, should implement the Document interface.
+
ROLE_HEADING
+
Heading.
+
ROLE_PAGE
+
An object representing a page of document content. It is used in documents which are accessed by the user on a page by page basis.
+
ROLE_SECTION
+
A container of document content.
+
ROLE_REDUNDANT_OBJECT
+
An object which is redundant with another object in the accessible hierarchy. ATs typically ignore objects with this role.
+
ROLE_FORM
+
A container of form controls.
+
ROLE_IME
+
An object which is used to allow input of characters not found on a keyboard, such as the input of Chinese characters on a Western keyboard.
+
ROLE_APP_ROOT
+
 ???
+
ROLE_PARENT_MENUITEM
+
Represents a menu item, which is an entry in a menu that a user can choose to display another menu.
+
ROLE_CALENDAR
+
A calendar that allows the user to select a date.
+
ROLE_COMBOBOX_LIST
+
A list of items that is shown by combobox.
+
ROLE_COMBOBOX_OPTION
+
A item of list that is shown by combobox
+
ROLE_IMAGE_MAP
+
An image map -- has child links representing the areas
+
ROLE_OPTION
+
An option in a listbox
+
ROLE_RICH_OPTION
+
A rich option in a listbox, it can have other widgets as children
+
ROLE_LISTBOX
+
A list of options
+
+ +
+

Editor's note: Use template ROLE_ to get reference on accessible role. It looks like ROLE_MENUITEM.

+
diff --git a/files/pt-br/web/accessibility/at-apis/index.html b/files/pt-br/web/accessibility/at-apis/index.html new file mode 100644 index 0000000000..57b2f546d4 --- /dev/null +++ b/files/pt-br/web/accessibility/at-apis/index.html @@ -0,0 +1,176 @@ +--- +title: AT APIs Support +slug: Web/Accessibility/AT-APIs +tags: + - AT_APIs + - Accessibility + - NeedsTranslation + - TopicStub +translation_of: Mozilla/Tech/Accessibility/AT-APIs +--- +

Introduction

+ +
Documentation is in progress still. But in the meantime it more up-to-date and contains more details than existed analogues for AT-SPI and MSAA
+ +

This documentation explains how makers of screen readers, voice dictation packages, onscreen keyboards, magnification software and other assitive technologies can support Gecko-based software. We provide for them the support of these products on Windows, Linux/Unix and OS X platforms.

+ +

Accessible Gecko

+ +

Gecko is a rendering engine that Firefox, SeaMonkey, Netscape and yelp use. Gecko can render a variety of content, not just HTML and supports key web standards such as Cascading Style Sheets, Javascript and the W3C DOM. Gecko also handles the users keystrokes and mouse clicks. Gecko is the core architecture that we are adding accessibility to, in order to support basic accessibility in all applications that are based on it.

+ +

Gecko Based Applications

+ +

Gecko can be used in two ways to create application:

+ +

Embedded Clients

+ +

Embedded clients use Gecko only in the content window, at the moment for HTML and generic XML only. They typically use standard Windows controls for their user interface -- the area outside of the client content window, plus the context menu.

+ + + +

XUL Applications

+ +

XUL applications make full use of the Gecko architecture, not only for HTML content, but also for the entire user interface. Widgets such as menus, tab panels, tree views and dialogs are provided via an XML language called XUL (eXtensible User-interface Language). None of the user interface contains standard OS controls. This is done to ensure a common look and feel across all supported platforms, and to allow for different skins (appearances). Developing a XUL window is not that different from developing a web page, but the elements available to add widgets are more powerful and designed to be similar to desktop widgets.

+ +

Examples of XUL applications:

+ + + +

Gecko Version

+ +

For Firefox and all other Gecko-based products: this documentation applies to up-to-date product builds based on Gecko 1.9.2 -- currently not available on official releases. However most of described features are supported starting from Gecko 1.9.0 (Firefox 3.0). However it's preferable to grab the current build of Firefox or any other Gecko-based product to be up to dated:

+ + + +

Determining if Accessibility is Enabled in a Firefox

+ +

Accessibility is enabled on Windows and Linux platforms by default. As well you might find helpful the about:accessibilityenabled Firefox extension.

+ +

Supported AT APIs

+ +

AT APIs terms

+ +
+
Microsoft Active Accessibility (MSAA)
+
an API devised by Microsoft so that accessibility aids can track what's going on inside the user interface of any software package that supports it. If you seriously need to understand MSAA, you'll need to read the docs on MSDN and play with the sample apps and code that come with MSAA SDK 1.3. (I recommend SDK 1.3 because the MSAA SDK 2.0 doesn't come with the source code to the testing tools. The other differences are not important).
+
IAccessible2 (IA2)
+
IAccessible2 is a new accessibility API which complements Microsoft's earlier work on MSAA. This API fills critical accessibility API gaps in the MSAA offering.
+
Assistive Technology Service Provider Interface (AT-SPI)
+
an API devised by Sun Microsystems so that accessibility aids can track what's going on inside the user interface of any software package that supports it. If you seriously need to understand AT-SPI, you'll need to read the docs on gnome.org and play with the available sample apps and code, such as at-poke. Please note that the web docs are sometimes out of date, and the latest AT-SPI is available on CVS.
+
Universal Access (UA)
+
Universal Access (UA) is the Apple's accessibility framework.
+
+ +

Windows platform

+ +

We support MSAA (Microsoft Active Accessibility) and IAccessible2 on Windows. Also we expose MS COM interfaces ISimpleDOM* to provide an access to DOM tree.

+ +

IAccessible2 is a set of interfaces that overlay the MSAA (IAccessible) and DOM (ISimpleDOM*) interface support. Any object that supports IAccessible will also support IAccessible2 and possibly any of the other IA2 interfaces.

+ +

Linux/Unix platform

+ +

We support ATK/AT-SPI interfaces on Linux.

+ +

Mac platform

+ +

We currently support only a subset of Universal Access. The rest of the Mozilla Universal Access support is in progress.

+ +

Accessible Web Standards

+ +

Gecko exposes the number of XML languages including HTML to AT. Refer to accessible web specifications page to learn what and how markup languages are exposed.

+ +

AT APIs Implementation Details

+ +

Refer to implementation details page to see how Gecko supports interesting AT API. There you will find information how AT API interfaces, roles, states and etc are mapped into Gecko accessibility API and visa versa.

+ +

Keyboard User Interface and API

+ +

Fortunately, Gecko uses the standard keyboard API's for each supported platform. The Mozilla keyboard shortcuts for content are similar to what is used in other browsers. Here is a list of Firefox keyboard shortcuts.

+ +

Test Tools

+ +

Here you will find a list of tools to test accessibility Gecko-based applications.

+ + + +

Screen Readers

+ +

Here's a list of screen readers we are oriented to in the first place.

+ + + +

Contacts

+ +

Please discuss accessibility issues on the Mozilla Accessibility groups or on the Mozilla Accessibility IRC channel.

diff --git a/files/pt-br/web/accessibility/xforms/index.html b/files/pt-br/web/accessibility/xforms/index.html new file mode 100644 index 0000000000..91b47d43f0 --- /dev/null +++ b/files/pt-br/web/accessibility/xforms/index.html @@ -0,0 +1,198 @@ +--- +title: XForms Accessibility +slug: Web/Accessibility/XForms +tags: + - Accessibility + - NeedsTranslation + - Obsolete + - TopicStub + - XForms +translation_of: Mozilla/Tech/Accessibility/XForms +--- +

 

+ +

Intoduction

+ +

This article provides a quick guide to how accessibility is handled in Gecko for XForms.. Assistive technologies API for XForms is supported starting from Firefox 3 (Gecko 1.9). Implementation of accessible objects for XForms elements is based on top of the existing object hierarchy introduced in the Mozilla accessibility module. XForms elements behavior is implemented in accordance with accessible toolkit checklist.

+ +

In general, when elements are similar to HTML elements, they are exposed to MSAA/ATK in a similar way.

+ +

Get Build

+ +

Subsections below explain how you can obtain accessible XForms-enabled build. These are either downloading latest build of firefox or building it yourself.

+ +

Downloading Builds

+ +
Notion: XForms is no longer distributed with Firefox build. You must build it yourself. See section below.
+ +

For Firefox, you may directly download the nighly "trunk" build of Firefox and install the XForms extension which lives in 'xpi' directory of the build. Note, XForms accessibility is implemented only on trunk. Trunk builds are not considered stable and should not be installed on top of the Firefox used for daily browsing. Currently we have verified that XForms accessibility is working on the Windows platform, and Linux testing has not yet been done, although everything should work and is ready to be tested. You will find trunk builds of Firefox at ftp.mozilla.org, trunk builds of XForms extension (Windows) at ftp.mozilla.org or trunk builds of XForms extension (Linux) ftp.mozilla.org.

+ +

Build It Yourself

+ +

If you would like to build firefox/seamonkey yourself then please ensure your .mozconfig file has the following option:

+ + + +

How To Test

+ +

There are two approaches to test XForms accessibility. The first is to use and assistive technology such as a screen reader, or an accessibility testing tool, to make sure XForms elements have proper accessible objects. Or you may be guided by toolkit checklist to check keyboard navigation for XForms controls.

+ +

You can try the following link to test XForms accessibility:

+ + + +

Keyboard Navigation Issues

+ + + +

Though XForms spec declares navindex attribute to define the navigation sequence (see 1.0 specs or 1.1 specs) but Rich Schwerdtfeger (Distinguished Engineer, SWG Accessibility Architect/Strategist Chair, IBM Accessibility Architecture Review Board) gave some clarification about navindex. He wrote:

+ +
Navindex was in XForms - it was stripped out as it was believed the focus model was dependent on the content which used it. So, yes we don't care about navindex in XForms. If you use xhtml1.x use tabindex. If you use Xhtml2 use nextfocus.
+ +

Therefore since Mozilla XForms works in XHTML (1.x) or XUL documents only then we use tabindex instead. Note, we support -moz-user-focus style neither for XHTML or XUL.

+ +

AT API

+ +

Accessible properties

+ +

This section describes common rules how accessibility properties are formed for forms control elements.

+ +

name

+ +

It is formed from value of child XForms label element if the element doesn't have labelledby attribute.

+ +

description

+ +

It is formed from value of child XForms hint element if the element doesn't have describedby attribute.

+ +

state

+ +

It is formed as well from model item properties (MIPs) of instance node that XForms element is bound to as from valid/invalid or in-range/out-of-range states of instance node. Instance node states are mapped to accessibility state constants declared in nsIAccessibleStates interface like it shown below:

+ + + +

attributes

+ +

Redefines datatype ARIA attribute. Its value is XML Schema builit-in datatype of instance node that XForms element is bound to.

+ +

children

+ +

Mozilla XForms implementation allows form control elements to have child elements. Therefore accessible children are formed from any accessible child elements of form control element and from elements that are introduced by its presentation.

+ +

Forms Controls Module

+ +

Some of form control elements may be represented in few ways by different widgets. This section lists accessible presentations for form control elements.

+ +

input

+ +

A key xforms element to show and change the instance data to which it is bound (see the spec, the docs). The follwoing representations input element are accessible:

+ + + +

secret

+ +

Used for inputting passwords (see the spec, the docs). This element is represented by password field.

+ +

textarea

+ +

Serves to show/change multiline text (see the spec, the docs). This element is represented by multiline text field.

+ +

output

+ +

Serves to show instance data that the element is bound to (see the spec, the docs). It can have the following presentations:

+ + + +

upload

+ +

Provides a means for the user to select a file (see the spec, the docs). This element is represented by upload.

+ +

range

+ +

Allows the user to choose a value from within a specific range of values (see the spec, the docs). Currently it is represented by a slider only.

+ +

trigger

+ +

Allows the user to initiate actions (see the spec, the docs). This element is represented by button.

+ +

submit

+ +

Invokes the submission of the selected instance data to its target destination (see the spec, the docs). This element is represented by button.

+ +

select

+ +

Allows the user to choose one or multiple values from a list of pre-defined values (see the spec, the docs). It can have the following representations:

+ + + +

select1

+ +

Allows the user to choose a single value from a list of pre-defined values (see the spec, the docs). It can have the following representations:

+ + + +

Additional Elements

+ +

These elements may be used as child elements to the form controls described above. Some of these elements are not accessible itself but they makes accessibility properties for XForms elements that hold them.

+ +

label

+ +

Specifies the label for the xforms control (see the spec, the docs). Every form control other than the output element must contain a label element. The value of label element is used as name of accessible object.

+ +

help

+ +

Specifies contextual help for the containing form control (see the spec, the docs). The help element has ROLE_ALERT role.

+ +

hint

+ +

Similar to a tooltip (see the spec, the docs). The value of hint element is used as description of accessible object.

+ +

alert

+ +

This message will be shown when the form control cannot properly bind to instance data or when the instance data value is invalid or out of the specified range of selectable values (see the spec, the docs). The alert element has ROLE_ALERT role for both usual and inline alert elements.

+ +

message

+ +

Used in combination with event listeners to display a message to the user when the specified event occurs (see the spec, the docs). The message element has ROLE_ALERT role.

+ +

Resources

+ +

Below you will find a list of XForms/Accessiblity resources:

+ + diff --git a/files/pt-br/web/accessibility/xforms/upload/index.html b/files/pt-br/web/accessibility/xforms/upload/index.html new file mode 100644 index 0000000000..2be80c89f4 --- /dev/null +++ b/files/pt-br/web/accessibility/xforms/upload/index.html @@ -0,0 +1,45 @@ +--- +title: Upload Representation +slug: Web/Accessibility/XForms/Upload +tags: + - Acessibilidade + - Acessibilidade_XForms + - Obsolento + - XForms +translation_of: Mozilla/Tech/Accessibility/XForms/Upload +--- +

 

+ +

« Accessibility XForms Support Page

+ +

Sumário

+ +

Provê meios para usuários selecionarem arquivos. Essa apresentação é usada para upload de elementos (veja o documento). A representação do upload é combinada com o campo de texto para mostrar a URL do arquivouploaded, o botão de upload e o botão de limpeza.

+ +

Interfaces Expostas

+ + + +

Propriedades de Acessibilidade

+ +

nsIAccessible

+ + + +

Accessible children

+ + diff --git a/files/pt-br/web/acessibilidade/accessibilidade_para_plataforma_movel/index.html b/files/pt-br/web/acessibilidade/accessibilidade_para_plataforma_movel/index.html new file mode 100644 index 0000000000..29d407c175 --- /dev/null +++ b/files/pt-br/web/acessibilidade/accessibilidade_para_plataforma_movel/index.html @@ -0,0 +1,100 @@ +--- +title: Acessibilidade para plataforma móvel +slug: Web/Acessibilidade/Accessibilidade_para_plataforma_movel +tags: + - Acessibilidade + - Firefox OS + - Guías + - Móveis +translation_of: Web/Accessibility/Mobile_accessibility_checklist +--- +
+

Este documento contém uma lista concisa de requisitos para desenvolvedores de aplicativos móveis. Tem como intenção evoluir continuamente conforme forem aparecendo outros padrões.

+
+ +

Cor

+ + + +
+

   Jon Snook escreveu um útil Colour Contrast Checker  que é usado para checar o contraste de cores entre o background e o foreground. De maneira alternativa o Tanaguru Contrast-Finder faz um trabalho similar, mas também sugeste melhores contrastes de cores considerando as usadas.

+
+ +

Visibilidade

+ + + +

Foco

+ + + +

Textos Equivalentes

+ + + +

Manipulação de Estado

+ + + +

Orientações gerais

+ + + +
+

Tanaguru's automated accessibility testing service fornece uma maneira útil para descobrir alguns erros de acessibilidade que ocorrem em páginas web, ou instalando aplicativos web (ex: Firefox OS.) Você pode encontrar mais sobre a técnica de implementação do Tanaguru, como também contribuir para o projeto tanaguru.org.

+
+ +
+

A versão original desse documento foi escrita por Yura Zenevich.

+
+ +

 

diff --git a/files/pt-br/web/acessibilidade/an_overview_of_accessible_web_applications_and_widgets/index.html b/files/pt-br/web/acessibilidade/an_overview_of_accessible_web_applications_and_widgets/index.html new file mode 100644 index 0000000000..df43b575a6 --- /dev/null +++ b/files/pt-br/web/acessibilidade/an_overview_of_accessible_web_applications_and_widgets/index.html @@ -0,0 +1,234 @@ +--- +title: Visão geral da acessibilidade nas aplicações web e widgets +slug: Web/Acessibilidade/An_overview_of_accessible_web_applications_and_widgets +tags: + - ARIA + - Accessibility + - Acessibilidade + - Aplicativos Web + - CSS + - DHTML + - Guía + - HTML+ARIA + - Navegação+Teclado + - WAI-ARA + - Widgets +translation_of: Web/Accessibility/An_overview_of_accessible_web_applications_and_widgets +--- +

A Rede Mundial está mudando. Estatísticamente, os sítios baseados em páginas estão, cada vez mais, sendo repostos por aplicações dinâmicas, em estilo Ambiente, que fazem uso intenso de JavaScript e AJAX. Estilistas estão criando novos widgets e controles inteiramente com a combinação de JavaScript, HTML e CSS. Este salto tem o potencial de aperfeiçoar, dramaticamente, a capacidade de resposta e a usabilidade da Rede, mas milhares de utilizadores estão sob o risco de exclusão, devido a algumas lacunas na acessibilidade. A JavaScript tem, tradicionalmente, tido a reputação de ser inviável para quem usa tecnologias assistivas, como leitores de tela mas, agora, existem maneiras de criar interfaces de utilização dinâmicas acessíveis a uma ampla variedade de pessoas.

+ +

O problema

+ +

A maior parte do conjunto de ferramentas JavaScript oferece uma biblioteca de utilização de widgets que imita o comportamento de interfaces de Ambiente familiares. Deslizantes, barras de menus, visão de arquivos em lista e muito mais pode ser construído com uma combinação de JavaScript, CSS e HTML. Uma vez que a especificação da HTML 4 não fornece etiquetas integradas (built-in tags) que descrevam estes tipos de widgets semanticamente, os desenvolvedores recorrem ao uso de elementos genéricos, tais como <div> e <span>. Embora isto resulte em um widget que se pareça com seu duplo de ambiente, geralmente não existe informação semântica suficiente, na marcação, para torná-lo utilizável por uma tecnologia assistiva. Teor dinâmico em uma página da Rede Mundial pode ser particularmente problemático para quem, por alguma razão, não pode ver a tela. Cotações de ações, alimentação instantânea de atualizações do twitter, indicadores de progresso e conteúdos similares alteram o DOM, enquanto uma tecnologia assistiva (TA/AT) pode não ser alertada disso. Aqui é onde o conjunto ARIA entra.

+ +

Exemplo 1: Marcação para um widget de abas construído sem as indicações ARIA. Não existem informações semânticas, na marcação, que descrevam a sua forma, nem a sua função.

+ +
<!-- This is a tabs widget. How would you know, looking only at the markup? -->
+<ol>
+  <li id="ch1Tab">
+    <a href="#ch1Panel">Chapter 1</a>
+  </li>
+  <li id="ch2Tab">
+    <a href="#ch2Panel">Chapter 2</a>
+  </li>
+  <li id="quizTab">
+    <a href="#quizPanel">Quiz</a>
+  </li>
+</ol>
+
+<div>
+  <div id="ch1Panel">Chapter 1 content goes here</div>
+  <div id="ch2Panel">Chapter 2 content goes here</div>
+  <div id="quizPanel">Quiz content goes here</div>
+</div>
+ +

Exemplo 2: Como o widget de abas pode ser visto. Seus utilizadores podem reconhecer sua aparência, mas não há semântica legível por mecanismos de tecnologias assistivas.
+ Screenshot of the tabs widget

+ +

ARIA

+ +

As definições para WAI-ARIA Accessible Rich Internet Applications (Aplicações Ricas para uma Internete Acessível), da W3C -  Web Accessibility Initiative (Iniciativa pela Acessibilidade na Rede Mundial/World Wide Web Consortium-W3C) - oferecem uma via para a adição das necessidades semânticas perdidas pelas tecnologias assistivas, como os leitores de tela. O conjunto ARIA possibilita que desenvolvedores possam descrever seus widgets de forma mais detalhada com a inclusão de atributos especiais à marcação. Projetado para preencher a lacuna entre o padrão de rotulagem HTML e os controles com estilo ambiente encontrados em aplicações dinâmicas pela web, o conjunto ARIA fornece funções (roles) e estados (states) que descrevem o comportamento da maioria das interfaces de utilização dos widgets conhecidas.

+ +

A especificação ARIA está dividida em três tipos diferentes de atributos: funções (roles), estados (states) e propriedades (properties). As funções (roles) descrevem os widgets que não estão disponíveis de outra forma em HTML 4, como deslizantes, barras de menu, abas e diálogos. As propriedades (properties) descrevem as características desses widgets - se podem ser arrastados (draggable), se existe algum elemento obrigatório, ou se trazem uma janela de explosão (popup) associada. Os estados (states) descrevem a interação atual de um elemento, informando à tecnlogia assistiva se este se encontra ativo, desativado, selecionado, ou oculto.

+ +

Os atributos ARIA são projetados para serem interpretados automaticamente pelo navegador e traduzidos para as APIs (Application Programming Interface/Interface de Programação de Aplicativo) de acessibilidade nativas do sistema operacional. Quando o conjunto ARIA está presente as tecnologias assistivas são capazes de reconhecer e interagir com os controles personalizados pela  JavaScript da mesma forma que fazem com os seus equivalentes de ambiente. Isto tem o potencial de oferecer uma experiência de utilização muito mais consistente do que aquela que foi possível nas gerações anteriores das aplicações da Rede, uma vez que os utilizadores de tecnologias assistivas podem empregar todo o seu conhecimento sobre o funcionamento das aplicações de ambiente, ao usar aquelas que são baseadas na web.

+ +

Exemplo 3: Marcação para um widget de abas com os atributos ARIA adicionados:

+ +
<!-- Now *these* are Tabs! -->
+<!-- We've added role attributes to describe the tab list and each tab. -->
+<ol role="tablist">
+  <li id="ch1Tab" role="tab">
+    <a href="#ch1Panel">Chapter 1</a>
+  </li>
+  <li id="ch2Tab" role="tab">
+    <a href="#ch2Panel">Chapter 2</a>
+  </li>
+  <li id="quizTab" role="tab">
+    <a href="#quizPanel">Quiz</a>
+  </li>
+</ol>
+
+<div>
+  <!-- Notice the role and aria-labelledby attributes we've added to describe these panels. -->
+  <div id="ch1Panel" role="tabpanel" aria-labelledby="ch1Tab">Chapter 1 content goes here</div>
+  <div id="ch2Panel" role="tabpanel" aria-labelledby="ch2Tab">Chapter 2 content goes here</div>
+  <div id="quizPanel" role="tabpanel" aria-labelledby="quizTab">Quiz content goes here</div>
+</div>
+
+ +

O conjunto ARIA tem suporte nas últimas versões de todos os maiores navegadores, incluindo Firefox, Safari, Opera, Chrome e Internet Explorer. Muitas das tecnologias assistivas, como as de código aberto NVDA e os leitores de tela Orca, da mesma foma, trazem suporte ao ARIA. Progressivamente, as bibliotecas  JavaScript para widget, tais como  jQuery UI, YUI, Google Closure e Dojo Dijit também incluem as marcações ARIA.

+ +

Mudanças na apresentação

+ +

Mudanças de apresentação dinâmicas agregam o uso de CSS para alterar a aparência do conteúdo (uma borda vermelha em volta de algum dado inválido, ou a troca da cor de fundo de uma caixa de seleção já marcada), bem como quando um item é exibido, ou escondido.

+ +

Mudanças de estado

+ +

O conjunto ARIA provê atributos para declarar o estado atual da interface de utilização de um widget. Os exemplos abrangem (mas não são apenas estes, com certeza( :

+ + + +

(Para uma lista completa de estados ARIA, consulte a ARIA list of states and properties (lista de estados e propriedades ARIA).

+ +

Os desenvolvedores devem dar preferência ao uso dos estados ARIA para indicar a situação atual dos elementos widgets na interface de utilização (UI) e os seletores de atributos CSS para alterar a sua aparência, com base nas mudanças desses estados (em vez de usar um roteiro (script) para mudar um nome de classe de um elemento).

+ +

A Open Ajax Alliance (OAA - Aliança OpenAJAX ) disponibiliza um exemplo de um seletor de atributos CSS baseado nos estados ARIA (em inglês) - an example of CSS attribute selectors based on ARIA states. O exemplo mostra a interface de um editor WYS/WYG com um sistema de menu dinâmico. Os itens selecionados no menu, como o tipo de fonte estão, visualmente, distintos dos outros. As partes importantes do exemplo são explicadas a seguir.

+ +

Neste exemplo, a HTML para um menu tem a forma exibida abaixo. Note como, nas linhas 7 e 13, a propriedade (property) aria-checked é usada para declarar o estado da seleção dos itens do menu.

+ +

Exemplo 1a: HTML para um menu selecionável (adaptado da  http://www.oaa-accessibility.org/example/25/).

+ +
<ul id="fontMenu" class="menu" role="menu" aria-hidden="true">
+  <li id="sans-serif"
+      class="menu-item"
+      role="menuitemradio"
+      tabindex="-1"
+      aria-controls="st1"
+      aria-checked="true">Sans-serif</li>
+  <li id="serif"
+      class="menu-item"
+      role="menuitemradio"
+      tabindex="-1"
+      aria-controls="st1"
+      aria-checked="false">Serif</li>
+  ...
+
+ +

A CSS usada para alterar a aparência do item selecionado é mostrada no Exemplo 1b. Perceba que não existe um nome de classe (classname) de personalização, apenas o estado do atributo aria-checked, na linha 1.

+ +

Exemplo 1b: Seletor baseado em atributo para indicar um estado (da  http://www.oaa-accessibility.org/example/25/).

+ +
li[aria-checked="true"] {
+  font-weight: bold;
+  background-image: url('images/dot.png');
+  background-repeat: no-repeat;
+  background-position: 5px 10px;
+}
+
+ +

O  JavaScript para atualizar a propriedade aria-checked tem a forma exibida no Exemplo 1c. Repare que o roteiro (script) apenas atualiza o atributo aria-checked (linhas 3 e 8); também não é necessário adicionar, ou remover, um nome de classe personalizada.

+ +

Exemplo 1c: A  JavaScript atualiza o atributo aria-checked  (baseado em  http://www.oaa-accessibility.org/example/25/).

+ +
var processMenuChoice = function(item) {
+  // 'check' the selected item
+  item.setAttribute('aria-checked', 'true');
+  // 'un-check' the other menu items
+  var sib = item.parentNode.firstChild;
+  for (; sib; sib = sib.nextSibling ) {
+    if ( sib.nodeType === 1 && sib !== item ) {
+      sib.setAttribute('aria-checked', 'false');
+    }
+  }
+};
+
+ +

Alterações visuais

+ +

Quando o conteúdo visual é alterado (isto é, um elemento é escondido, ou mostrado), os desenvolvedores devem mudar o valor da propriedade aria-hidden. As técnicas descritas acima devem ser usadas, a fim de declarar a CSS para ocultar um elemento utilizando display:none (exibir:nenhum).

+ +

O sítio da Open Ajax Alliance fornece um exemplo de uma dica de tela (tooltip) que utiliza o estado aria-hidden para controlar a sua visibilidade (em inglês) an example of a tooltip that uses aria-hidden to control the visibility of the tooltip. O exemplo mostra um formulário web simples, com caixas de dicas de tela contendo instruções associadas aos campos de entrada. As partes relevantes deste exemplo estão explicadas abaixo.

+ +

Aqui, a HTML para a dica de tela tem a forma exibida no Exemplo 2a. A linha 9 configura o estado da aria-hidden para true.

+ +

Exemplo 2a: HTML para dicas de tela (adaptado de  http://www.oaa-accessibility.org/example/39/).

+ +
<div class="text">
+    <label id="tp1-label" for="first">First Name:</label>
+    <input type="text" id="first" name="first" size="20"
+           aria-labelledby="tp1-label"
+           aria-describedby="tp1"
+           aria-required="false" />
+    <div id="tp1" class="tooltip"
+         role="tooltip"
+         aria-hidden="true">Your first name is optional</div>
+</div>
+
+ +

A CSS para esta marcação está explicada no Exemplo 2b. Veja que não há uso de classname personalizada, apenas o estado do atributo aria-hidden, na linha 1.

+ +

Exemplo 2b:  Seletor basedo em atributo para indicar um estado  (de http://www.oaa-accessibility.org/example/39/).

+ +
div.tooltip[aria-hidden="true"] {
+  display: none;
+  }
+
+ +

O JavaScript que atualiza a propriedade aria-hidden tem a forma exposta no Exemplo 2c. Observe que o roteiro apenas atualiza o atributo aria-hidden (linha 2); não é necessário adicionar, nem remover, uma classname customizada.

+ +

Exemplo 2c: JavaScript para atualização do atributo aria-checked (com base em http://www.oaa-accessibility.org/example/39/).

+ +
var showTip = function(el) {
+  el.setAttribute('aria-hidden', 'false');
+}
+ +

Mudança de Atributo (Role)

+ +
Em construção
+ +

O conjunto ARIA possibilita que os desenvolvedores possam declarar uma função semântica para um elemento que, de outro modo, não a apresentaria, ou a ofereceria de forma incorreta. Por exemplo, quando alguma lista desordenada é utilizada para criar um menu, à {{ HTMLElement("ul") }} deve ser dada uma role de menubar e cada {{ HTMLElement("li") }} deve ter uma role de menuitem.

+ +

O papel (role) de um elemento não deve mudar. Em vez disso, remova o elemento original e ocupe seu lugar com um elemento que tenha a função (role) nova.

+ +

Por exemplo, considere um widget de edição "inline": um componente que possibilita que seus utilizadores sejam capazes de editar uma parte de um texto, sem mudar toda a composição. Este componente carrega o modo "visualizar", no qual o texto não pode ser modificado, mas pode ser ativado e um modo "editar", no qual o texto pode ser alterado. Se você o desenvolve, pode ter a tentação de implementar o modo "visualizar" com o uso do elemento texto "somente leitura"  {{ HTMLElement("input") }}, definindo a sua ARIA role para button e, em seguida, alternando para o modo "editar", para tornar o elemento apto à gravação e removendo o atributo role no modo "editar" (desde que os elementos {{ HTMLElement("input") }} tenham as suas próprias funções semânticas).

+ +

Não faça isso. Em substituição, implemente o modo "visualizar" usando um elemento completamente diferente, tal como uma {{ HTMLElement("div") }}, ou {{ HTMLElement("span") }} com uma role de button e o modo « edit » utilizando um elemento texto {{ HTMLElement("input") }}.

+ +

Mudanças assíncronas de conteúdo

+ +
Em construção. Veja, também, Regiões Dinâmicas
+ + + +

Muitas vezes, os desenvolvedores negligenciam o suporte ao teclado quando criam widgets personalizados. Para ser acessível a uma gama maior de pessoas, todas as configurações de uma aplicação web, ou de um widget, devem oferecer controles pelo teclado, sem a necessidade de um rato. Na prática isto, frequentemente, envolve as convenções suportadas por widgets similares, de ambiente, tirando plena vantagem das teclas Tab, Entra, Barra de Espaço e Setas.

+ +

Tradicionalmente, a navegação pelo teclado na web tem sido limitada à tecla Tab, que é pressionada para dar foco a cada botão, vínculo, ou formulário na página, em uma ordenação linear e Shift-Tab para navegar em sentido contrário (navegação regresssiva). É uma forma unidimensional de navegação - para frente e para trás, um elemento por vez. Em páginas mais pesadas, alguém que navegue apenas pelo teclado deve pressioná-lo dezenas de vezes antes de alcançar a seção desejada. Implementar as convenções para teclado no modelo ambiente, para a web, tem o potencial de tornar a navegação significativamente mais rápida para essas pessoas.

+ +

Aqui está um resumo sobre como a navegação pelo teclado deve funcionar, com a habilitação do conjunto ARIA, na aplicação web:

+ + + +

Assim, para o exemplo de widget de abas acima, a pessoa que estiver navegando deve ser capaz de entrar e sair da caixa que o contém usando as teclas "Tab" e "Shift+Tab" ( a <ol> na nossa marcação). Uma vez que o foco, pelo teclado, estiver dentro do contêiner, as teclas de setas devem permitir a navegação entre as suas diferentes guias (os elementos <li> ). A partir daqui as convenções variam de plataforma para plataforma. No Windows, a próxima aba deve ser ativada, automaticamente, quando as teclas de setas forem pressionadas. Em Mac OS X, seus utilizadores ativam a próxima aba pressionando a tecla "Entra", ou a "barra de espaço". Um  tutorial abrangente, para a criação de widgets, com navegação pelo teclado, descreve como implementar esse comportamento utilizando JavaScript Keyboard-navigable JavaScript widgets (JavaScript para widgets navegáveis pelo teclado).

+ +

Para mais detalhes sobre as convenções da navegação pelo teclado em modelo ambiente, um guia completo (em inglês) DHTML style guide (guia de estilos da HTML Dinâmica) está disponível. Este guia oferece uma visão global de como a navegação pelo teclado deve funcionar em cada tipo de widget suportado pelo conjunto ARIA. A  W3C também oferece um documento que ajuda muito, ARIA Best Practices, incluindo a navegação pelo teclado e as convenções de atalhos para uma variedade de widgets.

+ +

Veja, também

+ + diff --git a/files/pt-br/web/acessibilidade/desenvolvimento_web/index.html b/files/pt-br/web/acessibilidade/desenvolvimento_web/index.html new file mode 100644 index 0000000000..a8b43d18fa --- /dev/null +++ b/files/pt-br/web/acessibilidade/desenvolvimento_web/index.html @@ -0,0 +1,54 @@ +--- +title: Desenvolvimento Web +slug: Web/Acessibilidade/Desenvolvimento_Web +tags: + - ARIA + - Accessibility + - Acessibilidade + - DHTML + - Desenvolvimento Web + - WebMechanics + - Widgets acessíveis + - XUL +translation_of: Web/Accessibility +--- +

Este documento oferece mais informações para os desenvolvedores sobre as acessibilidades web e XUL

+ + + + + + + + +
+

Acessibilidade na Rede Mundial

+ +
+
ARIA para desenvolvedores
+
O conjunto ARIA possibilita a acessibilidade em conteúdo dinâmico HTML. São exemplos de uso de ARIA os conteúdos de regiões dinâmicas e widgets com JavaScript.
+
JavaScript para widgets navegáveis pelo teclado
+
Até agora, programadores web construiam seus modelos de widgets baseados em <div> e <span>, por faltarem as técnicas adequadas. A acessibilidade através do teclado é parte das exigências mínimas para a acessibilidade, das quais todos os desenvolvedores devem ter consciência.
+
+ +

Acessibilidade XUL

+ +
+
 
+
Construindo componentes personalizados e acessíveis com XUL
+
A utilização das técnicas de acessibilidade DHTML, a fim de tornar acessíveis os componentes customizados com a XUL.
+
Acessibilidade XUL - diretrizes de autoria
+
Quando a autoria está de acordo com estas diretrizes, a XUL é capaz de gerar interfaces acessíveis. Codificadores, revisores, construtores e engenheiros de produção (QA) devem se familiarizar com elas.
+
+
+

Recursos Externos

+ +
+
Mergulhe na Acessibilidade
+
Este livro responde a duas questões e a primeira, é: "Por que eu devo tornar meu sítio mais acessível?". A segunda, é: "Como eu posso fazer meu sítio mais acessível?"
+
Construindo páginas acessíveis
+
Uma boa lista sobre acessiblidade na rede mundial, feita pela IBM.
+
+
+ +

 

diff --git a/files/pt-br/web/acessibilidade/entendendo_wcag/index.html b/files/pt-br/web/acessibilidade/entendendo_wcag/index.html new file mode 100644 index 0000000000..392c1008b7 --- /dev/null +++ b/files/pt-br/web/acessibilidade/entendendo_wcag/index.html @@ -0,0 +1,57 @@ +--- +title: Entendendo as Diretrizes de Acessibilidade do Conteúdo Web +slug: Web/Acessibilidade/Entendendo_WCAG +tags: + - WCAG + - Web Content Accessibility Guidelines +translation_of: Web/Accessibility/Understanding_WCAG +--- +

Este conjunto de artigos fornece explicações rápidas para ajudá-lo a entender as etapas que devem ser seguidas para estar em conformidade com as recomendações descritas nas Diretrizes de Acessibilidade para Conteúdo Web 2.0 ou 2.1 do W3C (ou apenas WCAG, para as finalidades deste artigo).

+ +

O WCAG 2.0 e 2.1 fornece um conjunto detalhado de diretrizes para tornar o conteúdo web mais acessível para pessoas com uma ampla variedade de deficiências. Isso é compreensivo, porém incrivelmente detalhado e muito difícil de obter uma compreensão rápida disso. Por essa razão, nós fizemos uma sumário com os passos práticosque você precisa saber para satisfazer as diferentes recomendações, com mais alguns link para mais detalhes do que está sendo solicitado.

+ +

Os quatro princípios

+ +

WCAG is broadly broken down into four principles — major things that web content must be to be considered accessible (see Understanding the Four Principles of Accessibility for the WCAG definitions).

+ +

Each of the links below will take you to pages that further expand on these areas, giving you practical advice on how to write your web content so it conforms to the success criteria outlined in each of the WCAG 2.0 and 2.1 guidelines that further sub-divides each principle.

+ + + +

Should I use WCAG 2.0 or 2.1?

+ +

WCAG 2.1 is the most recent and relevant accessibility standard. Use WCAG 2.1 to help more people with disabilities and reduce the future legal risk for web site owners. Target WCAG 2.0 first when allocating resources. Then step up to WCAG 2.1. 

+ +

O que é o WCAG 2.1?

+ +

WCAG 2.1 was published as an official recommendation on 05 June 2018. The European Union (EU) adopted WCAG 2.1 as the digital accessibility standard in September 2018. W3C published a press release WCAG 2.1 Adoption in Europe

+ +

WCAG 2.1 includes:

+ + + + + +

This guide is intended to provide practical information to help you build better, more accessible websites. However, we are not lawyers, and none of this constitutes legal advice. If you are worried about the legal implications of web accessibility, we'd recommend that you check the specific legislation governing accessibility for the web/public resources in your country or locale, and seek the advice of a qualified lawyer.

+ +

O que é acessibilidade? e particulamente o Guia de Acessibilidade e a seção de regras fornecem mais informações relacionadas.

diff --git a/files/pt-br/web/acessibilidade/entendendo_wcag/keyboard/index.html b/files/pt-br/web/acessibilidade/entendendo_wcag/keyboard/index.html new file mode 100644 index 0000000000..905c6d062f --- /dev/null +++ b/files/pt-br/web/acessibilidade/entendendo_wcag/keyboard/index.html @@ -0,0 +1,87 @@ +--- +title: Keyboard +slug: Web/Acessibilidade/Entendendo_WCAG/Keyboard +translation_of: Web/Accessibility/Understanding_WCAG/Keyboard +--- +
To be fully accessible, a web page must be operable by someone using only a keyboard to access and control it. This includes users of screen readers, but can also include users who have trouble operating a pointing device such as a mouse or trackball, or whose mouse is not working at the moment, or who simply prefer to use a keyboard for input whenever possible.
+ +

Focusable elements should have interactive semantics

+ +

If an element can be focused using the keyboard, then it should be interactive; that is, the user should be able to do something to it and produce a change of some kind (for example, activating a link or changing an option).

+ +
+

Note: One important exception to this rule is if the element has role="document" applied to it, inside an interactive context (such as role="application"). In such a case, focusing the nested document is the only way of returning assistive technology to a non-interactive state (often called "browse mode").

+
+ +

Most interactive elements are focusable by default; you can make an element focusable by adding a tabindex=0 attribute value to it. However, you should only add tabindex if you have also made the element interactive, for example, by defining appropriate event handlers keyboard events.

+ +

See also

+ + + +

Avoid using tabindex attribute greater than zero

+ +

The tabindex attribute indicates that an element is focusable using the keyboard. A value of zero indicates that the element is part of the default focus order, which is based on the ordering of elements in the HTML document. A positive value puts the element ahead of those in the default ordering; elements with positive values are focused in the order of their tabindex values (1, then 2, then 3, etc.).

+ +

This creates confusion for keyboard-only users when the focus order differs from the logical order of the page. A better strategy is to structure the HTML document so that focusable elements are in a logical order, without the need to re-order them with positive tabindex values.

+ +

See also

+ + + +

Clickable elements must be focusable and should have interactive semantics

+ +

If an element can be clicked with a pointing device, such as a mouse, then it should also be focusable using the keyboard, and the user should be able to do something by interacting with it.

+ +

An element is clickable if it has an onclick event handler defined. You can make it focusable by adding a tabindex=0 attribute value to it. You can make it operable with the keyboard by defining an onkeydown event handler; in most cases, the action taken by event handler should be the same for both types of events.

+ +

See also

+ + + +

Interactive elements must be able to be activated using a keyboard

+ +

If the user can interact with an element using touch or a pointing device, then the element should also support interacting using the keyboard. That is, if you have defined event handlers for touch or click events, you should also define them for keyboard events. The keyboard event handlers should enable the effectively the same interaction as the touch or click handlers.

+ +

See also

+ + + +

Interactive elements must be focusable

+ +

If the user can interact with an element (for example, using touch or a pointing device), then it should be focusable using the keyboard. You can make it focusable by adding a tabindex=0 attribute value to it. That will add the element to the list of elements that can be focused by pressing the Tab key, in the sequence of such elements as defined in the HTML document.

+ +

See also

+ + + +

Focusable element must have focus styling

+ +

Any element that can receive keyboard focus should have visible styling that indicates when the element is focused. You can do this with the :focus CSS pseudo-class.

+ +

Standard focusable elements such as links and input fields are given special styling by the browser by default, so you might not need to specify focus styling for such elements, unless you want the focus styling to be more distinctive.

+ +

If you create your own focusable components, be sure that you also define focus styling for them.

+ +

See also

+ + diff --git a/files/pt-br/web/acessibilidade/index.html b/files/pt-br/web/acessibilidade/index.html new file mode 100644 index 0000000000..b494b06163 --- /dev/null +++ b/files/pt-br/web/acessibilidade/index.html @@ -0,0 +1,52 @@ +--- +title: Acessibilidade +slug: Web/Acessibilidade +tags: + - ARIA + - Acessibilidade + - Avançado + - Desenvolvimento Web + - TA - Tecnologias Assistivas +translation_of: Web/Accessibility +--- +

Acessiblidade no desenvolvimento Web significa permitir que o máximo possível de pessoas possa acessar os sites da web mesmo quando suas habilidades são limitadas de alguma forma. Aqui nós fornecemos informações sobre o desenvolvimento de conteúdo acessível.

+ +

"A palavra Acessibilidade é, frequentemente, usada para descrever facilidades ou assistências às pessoas com necessidades especiais, como em acessível para cadeirantes. Isto pode se estender para o Sistema Braille, rampas para cadeirantes, sinais sonoros em passagens de pedestres, modelos de páginas e assim por diante". Acessibilidade na Wikipedia

+ +

"A Web é, fundamentalmente, projetada para funcionar para todas as pessoas, independentemente de máquina, programas, língua, cultura, localização ou capacidade física ou mental de seus utilizadores. Quando a web atende a esses requisitos, ela se torna acessível a pessoas com dificuldades auditivas, motoras, visuais e cognitivas". W3C - Acessibilidade

+ +
+
+

Documentação

+ +
+
Desenvolvimento Web
+
Uma coleção de artigos destinados a mostrar as principais questões de desenvolvimento web no mundo da acessibilidade.
+
ARIA
+
Uma coleção de artigos para aprender como usar ARIA e tornar seus documentos HTML mais acessíveis.
+
Desenvolvimento de tecnologias assistivas (TA)
+
Uma coleção de artigos direcionados a desenvolvedores de tecnologias assistivas.
+
Acessibilidade em dispositivos móveis
+
Esse documento fornece uma breve lista das necessidades da acessibilidade para desenvolvedores de aplicativos móveis.
+
+ +

Ver todos os artigos sobre Acessibilidade...

+
+ +
+

Ferramentas para desenvolvedores web

+ + + + + +

Outras páginas úteis

+ + +
+
diff --git a/files/pt-br/web/acessibilidade/problemas_com_jaws_no_firefox/index.html b/files/pt-br/web/acessibilidade/problemas_com_jaws_no_firefox/index.html new file mode 100644 index 0000000000..65fe989377 --- /dev/null +++ b/files/pt-br/web/acessibilidade/problemas_com_jaws_no_firefox/index.html @@ -0,0 +1,11 @@ +--- +title: Problemas com JAWS no Firefox +slug: Web/Acessibilidade/Problemas_com_JAWS_no_Firefox +tags: + - Acessibilidade + - Obsolento +translation_of: Web/Accessibility/JAWS_Issues_with_Firefox +--- +

Problemas JAWS Firefox conhecidos

+ +

Esse artigo não é mais relevante. Por favor, veja o FAQ no site de suporte Mozilla.

diff --git a/files/pt-br/web/api/abortsignal/aborted/index.html b/files/pt-br/web/api/abortsignal/aborted/index.html new file mode 100644 index 0000000000..6158b810e9 --- /dev/null +++ b/files/pt-br/web/api/abortsignal/aborted/index.html @@ -0,0 +1,62 @@ +--- +title: AbortSignal.aborted +slug: Web/API/AbortSignal/aborted +tags: + - API + - AbortSignal + - Propriedade + - aborted +translation_of: Web/API/AbortSignal/aborted +--- +
{{APIRef("DOM")}}{{SeeCompatTable}}
+ +

A propriedade aborted é apenas para leitura e fornece um valor {{domxref("Boolean")}} indicando se as solicitações ao objeto sinal de comunicação DOM forão abortadas (true) ou não (false).

+ +

Sintaxe

+ +
var isAborted = abortSignal.aborted;
+ +

Valor

+ +

Um valor {{domxref("Boolean")}}

+ +

Exemplos

+ +

No fragmento abaixo, criamos um novo objeto AbortController e recebemos dele um sinal {{domxref("AbortSignal")}} (disponível na propriedade signal). Depois checamos se o sinal foi ou não abortado usando a propriedade aborted, e então enviamos um log apropriado para o console.

+ +
var controller = new AbortController();
+var signal = controller.signal;
+
+// ...
+
+signal.aborted ? console.log('Pedido foi abortado') : console.log('Pedido nao foi abortado');
+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('DOM WHATWG', '#dom-abortsignal-onabort', 'onabort')}}{{Spec2('DOM WHATWG')}}Definição Inicial
+ +

Compatibilidade de Navegadores

+ + + +

{{Compat("api.AbortSignal.aborted")}}

+ +

Veja Também

+ + diff --git a/files/pt-br/web/api/abortsignal/index.html b/files/pt-br/web/api/abortsignal/index.html new file mode 100644 index 0000000000..1bfd9766c7 --- /dev/null +++ b/files/pt-br/web/api/abortsignal/index.html @@ -0,0 +1,101 @@ +--- +title: AbortSignal +slug: Web/API/AbortSignal +tags: + - API + - AbortSignal + - DOM + - Experimental + - Interface + - Referencia +translation_of: Web/API/AbortSignal +--- +
{{APIRef("DOM")}}{{SeeCompatTable}}
+ +

A interface AbortSignal  representa o sinal de um objeto que permite a você se comunicar com uma Requisição de DOM (como Fetch) e aborta-la se necessário via um objeto {{domxref("AbortController")}}

+ +

Propriedades

+ +

A interface AbortSignal também herda propriedades de sua interface pai, {{domxref("EventTarget")}}.

+ +
+
{{domxref("AbortSignal.aborted")}} {{readonlyInline}}
+
Um {{domxref("Boolean")}} que indica quando a(s) Request(s) com a qual o sinal está se comunicando está/estão abortadas(true) ou não(false).
+
+ +

Handlers de Eventos

+ +
+
{{domxref("AbortSignal.onabort")}}
+
Invocado quando um {{event("abort_(dom_abort_api)", "abort")}} evento dispara, ex: quando as requests do DOM que o sinal estão se comunicando são/estão abortadas.
+
+ +

Métodos

+ +

A interface AbortSignal também herda métodos de sua interface pai, {{domxref("EventTarget")}}.

+ +

Exemplos

+ +

No exemplo de código a seguir, nós vamos focar em fazer download de um vídeo usando a Fetch API.

+ +

Nós primeiro criaremos um controller usando o construtor do {{domxref("AbortController.AbortController","AbortController()")}}, e então pegar a referência de seu objeto {{domxref("AbortSignal")}} associado usando a propriedade {{domxref("AbortController.signal")}}.

+ +

Quando a requisição Fetch é iniciada, nós passamos o AbortSignal  como uma opção dentro do objeto de opções da request (veja {signal}, abaixo). Isso associa o sinal e o controller com a requisição fetch e nos permite aborta-la chamando {{domxref("AbortController.abort()")}}, como visto abaixo no segundo event listener.

+ +
var controller = new AbortController();
+var signal = controller.signal;
+
+var downloadBtn = document.querySelector('.download');
+var abortBtn = document.querySelector('.abort');
+
+downloadBtn.addEventListener('click', fetchVideo);
+
+abortBtn.addEventListener('click', function() {
+  controller.abort();
+  console.log('Download aborted');
+});
+
+function fetchVideo() {
+  ...
+  fetch(url, {signal}).then(function(response) {
+    ...
+  }).catch(function(e) {
+    reports.textContent = 'Download error: ' + e.message;
+  })
+}
+ +
+

Nota: Quando abort() é chamado, a promessa do fetch() é rejeitada com um AbortError.

+
+ +

Você pode encontrar um exemplo completo no GitHub — veja abort-api (see it running live also).

+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('DOM WHATWG', '#interface-AbortSignal', 'AbortSignal')}}{{Spec2('DOM WHATWG')}}Initial definition
+ +

Compatibilidade de Browser

+ + + +

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

+ +

Veja Também

+ + diff --git a/files/pt-br/web/api/abstractworker/index.html b/files/pt-br/web/api/abstractworker/index.html new file mode 100644 index 0000000000..824ccd2aaa --- /dev/null +++ b/files/pt-br/web/api/abstractworker/index.html @@ -0,0 +1,103 @@ +--- +title: AbstractWorker +slug: Web/API/AbstractWorker +translation_of: Web/API/AbstractWorker +--- +

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

+ +

Resumo

+ +

A interface AbstractWorker abstrai propriedades e métodos comuns para todo o tipo de Workers, sendo {{domxref("Worker")}} ou {{domxref("SharedWorker")}}.

+ +

Propriedades

+ +

A interface AbstractWorker não herda qualquer propriedade..

+ +
+
{{domxref("AbstractWorker.onerror")}}
+
É um {{ domxref("EventListener") }} que é chamado sempre que um {{domxref("ErrorEvent")}} do tipo error borbulha através do Worker.
+
+ +

Métodos

+ +

A interface AbstractWorker não implementa ou herda qualquer método.

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG', "#the-abstractworker-abstract-interface", "AbstractWorker")}}{{Spec2('HTML WHATWG')}}Sem mudanças para {{SpecName("Web Workers")}}.
{{SpecName('Web Workers', "#the-abstractworker-abstract-interface", "AbstractWorker")}}{{Spec2('HTML5 W3C')}}Definição Inicial
+ +

Compatibilidade de Browser

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
RecursoChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte Básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
RecursoAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Suporte Básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Veja também

+ + + +

 

diff --git a/files/pt-br/web/api/abstractworker/onerror/index.html b/files/pt-br/web/api/abstractworker/onerror/index.html new file mode 100644 index 0000000000..b6ce35361e --- /dev/null +++ b/files/pt-br/web/api/abstractworker/onerror/index.html @@ -0,0 +1,104 @@ +--- +title: AbstractWorker.onerror +slug: Web/API/AbstractWorker/onerror +translation_of: Web/API/AbstractWorker/onerror +--- +

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

+ +

Resumo

+ +

A propriedade AbstractWorker.onerror da interface {{domxref("AbstractWorker")}} representa um {{domxref("EventHandler")}}, que é uma função a ser chamada quando o evento {{event("error")}} ocorre através de um balão de notificação {{domxref("Worker")}}.

+ +

Sintaxe

+ +
myWorker.onerror = function() { ... };
+ +

Exemplo

+ +

O seguinte trecho de código mostra criação de um objeto Worker usando o construtor de Worker() e criando um manipulador onerror no objeto resultante:

+ +
var myWorker = new Worker("worker.js");
+
+myWorker.onerror = function() {
+  console.log('Há um erro com o seu worker!');
+}
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG', "#handler-abstractworker-onerror", "AbstractWorker.onerror")}}{{Spec2('HTML WHATWG')}}Nenhuma mudança em {{SpecName("Web Workers")}}.
{{SpecName('Web Workers', "#handler-abstractworker-onerror", "AbstractWorker.onerror")}}{{Spec2('Web Workers')}}Definição inicial.
+ +

Compatibilidade dos Navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticasChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico{{CompatChrome(4)}}{{CompatGeckoDesktop("1.9.1")}}1010.64
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticasAndroidFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari Mobile
Suporte básico4.4{{CompatGeckoMobile("1.9.1")}}1.0.11011.55.1
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/ambient_light_events/index.html b/files/pt-br/web/api/ambient_light_events/index.html new file mode 100644 index 0000000000..d011d08e08 --- /dev/null +++ b/files/pt-br/web/api/ambient_light_events/index.html @@ -0,0 +1,116 @@ +--- +title: Ambient Light Events +slug: Web/API/Ambient_Light_Events +tags: + - Ambiente de luz + - Ambiente de luz API + - Ambiente e luz HTML5 API +translation_of: Web/API/Ambient_Light_Events +--- +
Os eventos de luz ambiente são uma maneira útil de tornar uma página da Web ou uma aplicação consciente de qualquer alteração na intensidade da luz. Isso permite que eles reajam a tal mudança, por exemplo alterando o contraste de cores da interface do usuário (UI) ou alterando a exposição necessária para tirar uma foto.
+ +
 
+ +

Eventos de  luz

+ +

Quando o sensor de luz de um dispositivo detecta uma mudança no nível de luz, ele notifica o navegador dessa alteração. Quando o navegador obtém tal notificação, ele dispara um evento DeviceLightEvent que fornece informações sobre a intensidade da luz exata.

+ +

Este evento pode ser capturado no nível do objeto da janela usando o método addEventListener (usando o nome do evento devicelight) ou anexando um manipulador de eventos à propriedade window.ondevicelight.

+ +

Uma vez capturado, o objeto de evento dá acesso à intensidade da luz expressa em lux através da propriedade DeviceLightEvent.value.

+ +

Exemplo

+ +
window.addEventListener('devicelight', function(event) {
+  var html = document.getElementsByTagName('html')[0];
+
+  if (event.value < 50) {
+    html.classList.add('darklight');
+    html.classList.remove('brightlight');
+  } else {
+    html.classList.add('brightlight');
+    html.classList.remove('darklight');
+  }
+});
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoEstatusComentário
Sensor de luz ambiente A definição de "Ambient Light Events" nessa especificação. +

Rascunho do Editor

+
Definição inicial
+ +

Compatibilidade do navegador

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
{{domxref("DeviceLightEvent")}}{{CompatNo}}{{CompatGeckoDesktop("22.0")}}[1]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
{{domxref("DeviceLightEvent")}}{{CompatNo}}support{{CompatGeckoMobile("15.0")}}[1]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] O evento "devicelight" é implementado e a preferência ativada por padrão no Firefox Mobile para Android (15.0) e no Firefox OS (B2G). Começando com Gecko 22.0 geckoRelease ("22.0"), uma implementação de desktop para Mac OS X também está disponível. O suporte para o Windows 7 está em andamento (veja bug (754199)).

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/angle_instanced_arrays/index.html b/files/pt-br/web/api/angle_instanced_arrays/index.html new file mode 100644 index 0000000000..18f90385a0 --- /dev/null +++ b/files/pt-br/web/api/angle_instanced_arrays/index.html @@ -0,0 +1,88 @@ +--- +title: ANGLE_instanced_arrays +slug: Web/API/ANGLE_instanced_arrays +tags: + - API + - Reference + - WebGL + - WebGL extension +translation_of: Web/API/ANGLE_instanced_arrays +--- +
{{APIRef("WebGL")}}
+ +

A extenção ANGLE_instanced_arrays é parte do WebGL API e permite desenhar o mesmo objeto, ou grupos de objectos semelhantes várias vezes, se eles compartilham os mesmos dados de vértice, contagem primitiva e tipo.

+ +

As extensões WebGL estão disponíveis usando o método {{domxref("WebGLRenderingContext.getExtension()")}}. Para mais informações, veja também Usando Extenções no WebGL tutorial.

+ +
+

Disponibilidade: Esta extenção só está disponível para contextos {{domxref("WebGLRenderingContext", "WebGL1", "", 1)}}. Em {{domxref("WebGL2RenderingContext", "WebGL2", "", 1)}}, a funcionalidade desta extenção está disponível no contexto WebGL2 por padrão e as constantes e métodos estao disponíveis sem o sufixo "ANGLE".

+ +

Apesar do nome "ANGLE", esta extenção funciona em qualquer dispositivo se o hardware oferece suporte a ele e não apenas no Windows ao usar a biblioteca ANGLE. "ANGLE" apenas indica que essa extencão foi escrita pelos autores da biblioteca ANGLE.

+
+ +

Constantes

+ +

Essa extensão expõe uma nova constante, que pode ser usada no método {{domxref("WebGLRenderingContext.getVertexAttrib()", "gl.getVertexAttrib()")}}:

+ +
+
ext.VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE
+
Retorna um {{domxref("GLint")}} descrevendo o divisor de frequência usado para renderização instanciada quando usado no {{domxref("WebGLRenderingContext.getVertexAttrib()", "gl.getVertexAttrib()")}} como parâmetro pname.
+
+ +

Métodos

+ +

Essa extensão expõe três novos métodos.

+ +
+
{{domxref("ANGLE_instanced_arrays.drawArraysInstancedANGLE()", "ext.drawArraysInstancedANGLE()")}}
+
+

Se comporta de forma idêntica a {{domxref("WebGLRenderingContext.drawArrays()", "gl.drawArrays()")}} exceto que múltiplo instâncias do intervalo de elementos são executadas e a instância avança para cada iteração.

+
+
{{domxref("ANGLE_instanced_arrays.drawElementsInstancedANGLE()", "ext.drawElementsInstancedANGLE()")}}
+
+

Comporta-se de forma idêntica para o {{domxref("WebGLRenderingContext.drawElements()", "gl.drawElements()")}} exceto que várias instâncias do conjunto de elementos são executadas e a instância avança entre cada conjunto.

+
+
{{domxref("ANGLE_instanced_arrays.vertexAttribDivisorANGLE()", "ext.vertexAttribDivisorANGLE()")}}
+
+

Modifica a taxa na qual os atributos de vértice genéricos avançam ao renderizar várias instâncias de primitivos com {{domxref("ANGLE_instanced_arrays.drawArraysInstancedANGLE()", "ext.drawArraysInstancedANGLE()")}} e {{domxref("ANGLE_instanced_arrays.drawElementsInstancedANGLE()", "ext.drawElementsInstancedANGLE()")}}.

+
+
+ +

Exemplos

+ +

Habilitando a extenção:

+ +
var ext = gl.getExtension('ANGLE_instanced_arrays');
+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('ANGLE_instanced_arrays', '', 'ANGLE_instanced_arrays')}}{{Spec2('ANGLE_instanced_arrays')}}definição inicial.
+ +

Compatibilidade do navegador

+ + + +

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

+ +

Ver também

+ + diff --git a/files/pt-br/web/api/animation/cancel/index.html b/files/pt-br/web/api/animation/cancel/index.html new file mode 100644 index 0000000000..ceb1b7cf6c --- /dev/null +++ b/files/pt-br/web/api/animation/cancel/index.html @@ -0,0 +1,120 @@ +--- +title: Animation.cancel() +slug: Web/API/Animation/cancel +translation_of: Web/API/Animation/cancel +--- +

{{ SeeCompatTable() }}{{ APIRef("Web Animations API") }}

+ +

O método Animation.cancel() da interface  {{domxref("Animation")}} , limpa todas as  {{domxref("KeyframeEffect", "keyframeEffects")}} geradas pela animação e aborta esta execução.

+ +
+

Quando uma animação é cancelada, os valores de {{domxref("Animation.startTime", "startTime")}} e {{domxref("Animation.currentTime", "currentTime")}} são definidos como null.

+
+ +

Sintaxe

+ +
+
// cancela animação
+animation.cancel();
+
+ +

Parametros

+ +

Nenhum.

+ +

Valor de retorno

+ +

Nenhum.

+ +
+
+ +

Exceptions

+ +

Se o método {{domxref("Animation.playState")}} da animação estiver executando quando a operação for cancelada, esta ação vai rejeitar a {{domxref("Animation.finished", "current finished promise")}} com a {{domxref("DOMException")}} nomeada AbortError.

+ +
+
+ +

Especificações

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Animations', '#dom-animation-cancel', 'Animation.cancel()' )}}{{Spec2('Web Animations')}}Editor's draft.
+ +

Compatibilidade do navegador

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatUnknown}}{{CompatGeckoDesktop(40)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{ CompatUnknown}}{{CompatUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/animation/currenttime/index.html b/files/pt-br/web/api/animation/currenttime/index.html new file mode 100644 index 0000000000..e5b7c25559 --- /dev/null +++ b/files/pt-br/web/api/animation/currenttime/index.html @@ -0,0 +1,112 @@ +--- +title: Animation.currentTime +slug: Web/API/Animation/currentTime +translation_of: Web/API/Animation/currentTime +--- +

{{APIRef("Web Animations")}}{{SeeCompatTable}}

+ +

A propriedade Animation.currentTime da Web Animations API retorna e altera o tempo atual da animação em milésimos de segundos, seja estando em execução ou pausada.

+ +

Se a animação não tem uma {{domxref("AnimationTimeline", "timeline")}}, está inativa, ou ainda não foi colocada em execução, o valor de retorno do currentTime será null

+ +

Sintaxe

+ +
vartempoAtual = Animation.currentTime;
+Animation.currentTime = novoTempo;
+ +

Valor

+ +

Um número que representará no tempo atual da animação em milésimos de segundos, ou null para desativar a animação.

+ +

Examples

+ +

No jogo Drink Me/Eat Me, O tamanho da Alice é animado e pode crescer ou diminuir. No início do jogo, o tamanho dela foi colocado entre os dois extremos do animation's currentTime no meio do KeyframeEffect's duration, desta maneira:

+ +
aliceChange.currentTime = aliceChange.effect.timing.duration / 2;
+ +

Outra forma mais genérica para encontrar o marco de 50% da animação pode ser feito da seguinte forma:

+ +
animation.currentTime =
+  animation.effect.getComputedTiming().delay +
+  animation.effect.getComputedTiming().activeDuration / 2;
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçõesStatusComentário
{{SpecName('Web Animations', '#dom-animation-currenttime', 'currentTime')}}{{Spec2("Web Animations")}} 
+ +

Compatibilidade de Navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(39.0)}}{{CompatGeckoDesktop(48)}}[1]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatChrome(39.0)}}{{CompatGeckoMobile(48)}}[1]{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatChrome(39.0)}}
+
+ +

[1] A Web Animations API está ativa por padrão apenas no Firefox Developer Edition e nas versões do Nightly. Você pode habilitá-la em versões beta configurando a preferência dom.animations-api.core.enabled para true, e também desativar em qualquer Firefox mudando esta mesma preferência para false.

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/animation/index.html b/files/pt-br/web/api/animation/index.html new file mode 100644 index 0000000000..09d2f0091c --- /dev/null +++ b/files/pt-br/web/api/animation/index.html @@ -0,0 +1,171 @@ +--- +title: Animation +slug: Web/API/Animation +tags: + - API + - Animations + - Experimental + - Interface + - NeedsTranslation + - Reference + - TopicStub + - Web Animations + - waapi + - web animation api +translation_of: Web/API/Animation +--- +

{{ APIRef("Web Animations API") }}{{SeeCompatTable}}

+ +

A interface Animation da Web Animations API representa um único player de animação e fornece controles e uma linha do tempo (timeline) para um nó de animação ou recurso.

+ +

Construtor

+ +
+
{{domxref("Animation.Animation()", "Animation()")}}
+
Cria uma nova instância do objeto Animation.
+
+ +

Propriedades

+ +
+
{{domxref("Animation.currentTime")}}
+
O valor do tempo atual da animação, em milissegundos, esteja ela executando ou pausada. Se a animação não tem uma {{domxref("AnimationTimeline", "timeline")}}, está inativa ou ainda não foi executada, este valor é null.
+
+ +
+
{{domxref("Animation.effect")}}
+
Obtém e define o {{domxref("KeyframeEffect")}} associado a essa animação.
+
{{domxref("Animation.finished")}} {{readOnlyInline}}
+
Retorna a Primise de finalização atual para essa animação.
+
+ +
+
{{domxref("Animation.id")}}
+
Obtém e define a String usada para identificar a animação.
+
{{domxref("Animation.oncancel")}}
+
Obtém e define o manipulador para o evento cancel.
+
{{domxref("Animation.onfinish")}}
+
Obtém e define o manipulador para o evento finish.
+
{{domxref("Animation.playState")}} {{readOnlyInline}}
+
Retorna um valor enumerado descrevendo o estado de execução de uma animação.
+
+ +
+
{{domxref("Animation.playbackRate")}}
+
Obtém ou define a taxa de execução da animação.
+
+ +
+
{{domxref("Animation.ready")}} {{readOnlyInline}}
+
Retorna a promessa atual para quando essa animação estiver pronta.
+
+ +
+
{{domxref("Animation.startTime")}}
+
Obtém ou define o tempo agendado quando a execução de uma animação deve começar.
+
+ +
+
{{domxref("Animation.timeline")}}
+
Obtém ou define a {{domxref("AnimationTimeline", "timeline")}} associada a essa animação.
+
+ +

Métodos

+ +
+
{{domxref("Animation.cancel()")}}
+
Limpa todos os {{domxref("KeyframeEffect", "keyframeEffects")}} causados por essa animação e aborta sua execução.
+
+ +
+
{{domxref("Animation.finish()")}}
+
Vai até um dos extremos dessa animação, dependendo se ela está executando ou retornando.
+
+ +
+
{{domxref("Animation.pause()")}}
+
Suspende a execução de uma animação.
+
+ +
+
{{domxref("Animation.play()")}}
+
Inicia ou continua a execução de uma animação ou a recomeça se ela tiver terminado anteriormente.
+
+ +
+
{{domxref("Animation.reverse()")}}
+
Move a animação ao contrário, parando no início da animação.
+
+ +

Especificações

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

Compatibilidade com navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
RecursoChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico{{CompatChrome(39.0)}} [1]{{CompatGeckoDesktop(40.0)}} [2]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
RecursoAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}} [1]{{CompatGeckoDesktop(40.0)}} [2]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] Implementado como AnimationPlayer (nome da interface em uma versão primária da especificação).

+ +

[2] Anteriormente ao Firefox 40, estava disponível como AnimationPlayer. Em ambos os casos, é necessário definir a preferência dom.animations-api.core.enabled para poder usá-la.

+ +

 

diff --git a/files/pt-br/web/api/animation/playstate/index.html b/files/pt-br/web/api/animation/playstate/index.html new file mode 100644 index 0000000000..a31d8d7c64 --- /dev/null +++ b/files/pt-br/web/api/animation/playstate/index.html @@ -0,0 +1,152 @@ +--- +title: Animation.playState +slug: Web/API/Animation/playState +translation_of: Web/API/Animation/playState +--- +

{{APIRef("Web Animations")}}{{SeeCompatTable}}

+ +


+ A propriedade Animation.playState do Web Animations API retorna e altera um valor enumerado que descreve o estado de reprodução da animação.

+ +
+

Essa propriedade é apenas de leitura para Animações CSS e Transições.

+
+ +

Sintaxe

+ +
var estadoAtualDaReproducao = Animation.playState;
+
+Animation.playState =novoEstado;
+
+ +

Valor

+ +
+
idle
+
O tempo atual da animação não está acertado e não há tarefas pendentes.
+
pending
+
A animação está aguardando a realização de algumas tarefas para ser completada.
+
running
+
A animação está rodando.
+
paused
+
A animação está parada e a propriedade {{domxref("Animation.currentTime")}} não está sendo atualizada.
+
finished
+
A animação alcançou um de seus finais e a propriedade {{domxref("Animation.currentTime")}} não está sendo atualizada.
+
+ +

Exemplo

+ +

No jogo Growing/Shrinking Alice Game , os jogadores podem chegar ao final com a Alice chorando em uma poça de lágrimas. No jogo, por razões de performance, as lágrimas só são animadas quando estão visiveis. Então elas devem ficar pausadas enquanto a animação ocorre, como no exemplo:

+ +
// Configurando a animação das lágrimas
+
+tears.forEach(function(el) {
+  el.animate(
+    tearsFalling,
+    {
+      delay: getRandomMsRange(-1000, 1000), // aleatório para cada lágrima
+      duration: getRandomMsRange(2000, 6000), // aleatório para cada lágrima
+      iterations: Infinity,
+      easing: "cubic-bezier(0.6, 0.04, 0.98, 0.335)"
+    });
+  el.playState = 'paused';
+});
+
+
+// Rodar as lágrimas caindo quando o final precisa aparecer.
+
+tears.forEach(function(el) {
+  el.playState = 'playing';
+});
+
+
+// Reseta a animação e coloca o estado em pause.
+
+tears.forEach(function(el) {
+  el.playState = "paused";
+  el.currentTime = 0;
+});
+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçõesStatusComentários
{{SpecName('Web Animations', '#play-state', 'playState')}}{{Spec2("Web Animations")}}Initial definition.
+ +

Compatibilidade de Navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(39.0)}} [1]{{CompatGeckoDesktop(48)}}[2]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatChrome(39.0)}} [1]{{CompatChrome(39.0)}} [1]{{CompatGeckoMobile(48)}}[2]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] Antes do Chrome 50, este atributo retorna idle para animações que ainda não foram reproduzidas . A partir do Chrome 50, ele retorna paused.

+ +

[2] A Web Animations API está ativa por padrão apenas no Firefox Developer Edition e nas versões do Nightly. Você pode habilitá-la em versões beta configurando a preferência dom.animations-api.core.enabled para true, e também desativar em qualquer Firefox mudando esta mesma preferência para false.

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/animationevent/animationevent/index.html b/files/pt-br/web/api/animationevent/animationevent/index.html new file mode 100644 index 0000000000..77fcdeb37e --- /dev/null +++ b/files/pt-br/web/api/animationevent/animationevent/index.html @@ -0,0 +1,134 @@ +--- +title: AnimationEvent() +slug: Web/API/AnimationEvent/AnimationEvent +tags: + - AnimationEvent + - Apps + - CSSOM + - Experimental + - Referencia +translation_of: Web/API/AnimationEvent/AnimationEvent +--- +

{{APIRef("Web Animations API")}}{{SeeCompatTable}}

+ +

O construtor AnimationEvent()retorna o recente criado {{domxref("AnimationEvent")}}, representando um evento em relação a animação.

+ +

Síntaxe

+ +
animationEvent = new AnimationEvent(type, {animationName: aPropertyName,
+                                           elapsedTime  : aFloat,
+                                           pseudoElement: aPseudoElementName});
+
+ +

Argumentos

+ +

O construtor AnimationEvent() também herda argumentos do {{domxref("Event.Event", "Event()")}}.

+ +
+
type
+
Um {{domxref("DOMString")}} representando o nome do tipo de AnimationEvent. É caso sensitivo e pode ser: 'animationstart', 'animationend', ou 'animationiteration'.
+
animationName {{optional_inline}}
+
Um{{domxref("DOMString")}} contendo o valor do {{cssxref("animation-name")}} propriedade CSS associada com a transição. É por padrão "".
+
elapsedTime {{optional_inline}}
+
Um ponto flutuante dando a quantidade de tempo que a animação esteve rodando, em segundos, quando o evento termina, excluindo qualquer tempo que ela passou pausada. Para um evento "animationstart", elapsedTime é 0.0 a não ser que haja um valor negativo para animation-delay, nesse caso o evento terminará com elapsedTime contendo  (-1 * delay). É por padrão 0.0.
+
pseudoElement {{optional_inline}}
+
É um {{domxref("DOMString")}}, começando com"::", contendo o nome do pseudo-element que a animação roda. Se a animação não roda em um pseudo-elementomas em um elemento, então temos um string vazio "" .É por padrão ""
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçõesEstadoComentário
{{ SpecName('CSS3 Animations', '#AnimationEvent-interface', 'AnimationEvent()') }}{{ Spec2('CSS3 Animations')}}Initial definition.
+ +

Compatibilidade com os Navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(43.0)}}{{ CompatGeckoDesktop("23.0") }}{{CompatNo}}{{CompatNo}}{{CompatNo}}
pseudoElement{{CompatNo}}{{ CompatGeckoDesktop("23.0") }} +

{{CompatNo}}

+
{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{ CompatGeckoMobile("23.0") }}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatChrome(43.0)}}
pseudoElement{{CompatNo}}{{ CompatGeckoMobile("23.0") }}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

Veja também 

+ + diff --git a/files/pt-br/web/api/animationevent/animationname/index.html b/files/pt-br/web/api/animationevent/animationname/index.html new file mode 100644 index 0000000000..62a739e4e2 --- /dev/null +++ b/files/pt-br/web/api/animationevent/animationname/index.html @@ -0,0 +1,102 @@ +--- +title: AnimationEvent.animationName +slug: Web/API/AnimationEvent/animationName +tags: + - AnimationEvent + - Animação Web + - Apps + - CSSOM + - Propriedade + - Referencia +translation_of: Web/API/AnimationEvent/animationName +--- +

{{SeeCompatTable}}{{ apiref("Web Animations API") }}

+ +

AnimationEvent.animationName é uma propriedade só de leitura do{{domxref("DOMString")}} contendo o valor de {{cssxref("animation-name")}} propriedade CSS relacionada com a trasição.

+ +

Síntaxe

+ +
name = AnimationEvent.animationName
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{ SpecName('CSS3 Animations', '#AnimationEvent-animationName', 'AnimationEvent.animationName') }}{{ Spec2('CSS3 Animations')}}Initial definition.
+ +

Compatibilidade com os Navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{ CompatGeckoDesktop("6.0") }}10.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+ +

 

+ +

 

+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(43.0)}}
+
+ +

See also

+ + diff --git a/files/pt-br/web/api/animationevent/elapsedtime/index.html b/files/pt-br/web/api/animationevent/elapsedtime/index.html new file mode 100644 index 0000000000..4d04b30c90 --- /dev/null +++ b/files/pt-br/web/api/animationevent/elapsedtime/index.html @@ -0,0 +1,103 @@ +--- +title: AnimationEvent.elapsedTime +slug: Web/API/AnimationEvent/elapsedTime +tags: + - AnimationEvent + - Animações Web + - Apps + - CSSOM + - Experimental + - Propriedade + - Referencia +translation_of: Web/API/AnimationEvent/elapsedTime +--- +

{{SeeCompatTable}}{{ apiref("Web Animations API") }}

+ +

Sumário

+ +

AnimationEvent.elapsedTime é uma propriedade só de leitura com um ponto flutuante dando a quantidade de tempo que animação esteve rodando, em segundos, quando o evento termina, excluirá o tempo em que ela esteve em pausa. Para um evento "animationstart" , elapsedTime é 0.0 a não ser que tenha um valor negativo para {{cssxref("animation-delay")}}, nesse caso o evento irá terminar com elapsedTime contendo (-1 * delay).

+ +

Síntaxe

+ +
time = AnimationEvent.elapsedTime
+ +

Especificações

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSS3 Animations', '#AnimationEvent-elapsedTime', 'AnimationEvent.elapsedTime') }}{{ Spec2('CSS3 Animations')}}Initial definition.
+ +

Compatibilidade com os Navegadores

+ +

{{ CompatibilityTable }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{ CompatGeckoDesktop("6.0") }}10.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatVersionUnknown}}{{ CompatGeckoMobile("6.0") }}10.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatChrome(43.0)}}
+
+ +

 

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/animationevent/index.html b/files/pt-br/web/api/animationevent/index.html new file mode 100644 index 0000000000..c2abeb0bf6 --- /dev/null +++ b/files/pt-br/web/api/animationevent/index.html @@ -0,0 +1,194 @@ +--- +title: AnimationEvent +slug: Web/API/AnimationEvent +tags: + - API + - Animação Web + - Experimental + - Expérimental(2) + - Interface + - NeedsTranslation + - Reference + - Referencia + - Référence(2) + - TopicStub +translation_of: Web/API/AnimationEvent +--- +

{{SeeCompatTable}}{{APIRef("Web Animations API")}}

+ +

A interface AnimationEvent  representa eventos provendo informações relacionadas a animações.

+ +

{{InheritanceDiagram}}

+ +

Propriedades

+ +

Também propriedades herdadas pelo pai {{domxref("Event")}}.

+ +
+
{{domxref("AnimationEvent.animationName")}} {{readonlyInline}}
+
O {{domxref("DOMString")}} contém o valor do {{cssxref("animation-name")}} propriedade CSS associada com a transição.
+
{{domxref("AnimationEvent.elapsedTime")}} {{readonlyInline}}
+
É um ponto flutuante dado pela quantidade de tempo que a animação está rodando, em segundos, quando esse evento termina, excluindo o tempo em que animação esteve pausada. Para o evento "animationstart", elapsedTime é 0.0 a não ser que haja um valor negativo para {{cssxref("animation-delay")}}, nesse caso o evento terminará com elapsedTime contendo  (-1 * delay).
+
{{domxref("AnimationEvent.pseudoElement")}} {{readonlyInline}}
+
Um {{domxref("DOMString")}} começa com  '::', contendo o nome do pseudo-elemento onde a animação roda. Se a animação não rodar no pseudo-elemento mas no elemento, então teremos um string vazio ' '.
+
+ +

Constructores

+ +
+
{{domxref("AnimationEvent.AnimationEvent", "AnimationEvent()")}}
+
Cria um evento AnimationEvent com os dados parâmetros.
+
+ +

Métodos

+ +

Também herda métodos do pai {{domxref("Event")}}.

+ +
+
{{domxref("AnimationEvent.initAnimationEvent()")}} {{non-standard_inline}}{{deprecated_inline}}
+
Inicializa um AnimationEvent criado usando diminuído {{domxref("Document.createEvent()", "Document.createEvent(\"AnimationEvent\")")}} método.
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{ SpecName('CSS3 Animations', '#AnimationEvent-interface', 'AnimationEvent') }}{{ Spec2('CSS3 Animations') }}Definição inicial.
+ +

Compatibilidade com o Navegador

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support +

1.0 {{ property_prefix("webkit") }}

+ +

{{CompatChrome(43.0)}}

+
{{ CompatGeckoDesktop("6.0") }}10.012 {{ property_prefix("o") }}
+ 12.10
+ 15.0 {{ property_prefix("webkit") }}
4.0 {{ property_prefix("webkit") }}
AnimationEvent() constructor +

{{CompatChrome(43.0)}}

+
{{ CompatGeckoDesktop("23.0") }}{{CompatNo}}{{CompatNo}}{{CompatNo}}
initAnimationEvent() {{non-standard_inline}}{{deprecated_inline}}1.0{{ CompatGeckoDesktop("6.0") }}
+ Removed in {{ CompatGeckoDesktop("23.0") }}
10.0124.0
pseudoelement{{CompatNo}}{{ CompatGeckoDesktop("23.0") }}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+

 

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatVersionUnknown}}{{ property_prefix("webkit") }}{{ CompatGeckoMobile("6.0") }}10.012 {{ property_prefix("o") }}
+ 12.10
+ 15.0 {{ property_prefix("webkit") }}
{{CompatVersionUnknown}}{{ property_prefix("webkit") }}{{CompatChrome(43.0)}}
AnimationEvent() constructor{{CompatNo}}{{ CompatGeckoMobile("23.0") }}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatChrome(43.0)}}
initAnimationEvent() {{non-standard_inline}}{{deprecated_inline}}{{CompatVersionUnknown}}{{ CompatGeckoMobile("6.0") }}
+ Removed in {{ CompatGeckoMobile("23.0") }}
10.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}
pseudoelement{{CompatNo}}{{ CompatGeckoMobile("23.0") }}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

 

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/animationevent/initanimationevent/index.html b/files/pt-br/web/api/animationevent/initanimationevent/index.html new file mode 100644 index 0000000000..e9b0819b98 --- /dev/null +++ b/files/pt-br/web/api/animationevent/initanimationevent/index.html @@ -0,0 +1,134 @@ +--- +title: AnimationEvent.initAnimationEvent() +slug: Web/API/AnimationEvent/initAnimationEvent +tags: + - AnimationEvent + - Apps + - CSSOM + - Método(2) + - Não-padrão + - Obsolento + - Web Animations +translation_of: Web/API/AnimationEvent/initAnimationEvent +--- +

{{obsolete_header}}{{non-standard_header}}{{ apiref("Web Animations API") }}

+ +

Sumário

+ +

AnimationEvent.initAnimationEvent() é um método iniciado com o evento da animção criando um depreciativo {{domxref("Document.createEvent()", "Document.createEvent(\"AnimationEvent\")")}} método.

+ +

AnimationEvent criado desse modo não é confiável.

+ +
+

Note: Durante o processo de padronização, esse método foi removido das especificações. É que ele foi depreciado e esse processo foi removido da maioria das implementações . Não use este método; ao invés, use o construtor padrão, {{domxref("AnimationEvent.AnimationEvent", "AnimationEvent()")}}, para criar um sintético {{domxref("AnimationEvent")}}.

+
+ +

Syntax

+ +
animationEvent.initAnimationEvent(typeArg, canBubbleArg, cancelableArg, animationNameArg, elapsedTimeArg);
+ +

Parâmetros

+ +
+
typeArg
+
Um {{domxref("DOMString")}} identificado com um tipo específico de evento animação que ocorreu. Os seguintes valores são aceitados: + + + + + + + + + + + + + + + + + + + + + +
ValorSignificado
animationstartA animação começou.
animationendA animação terminou.
animationiterationA iteração corrente se completou.
+
+
canBubbleArg
+
Uma {{domxref("Boolean")}} bandeira indicando se o evento pode ser bolha (true) ou não (false).
+
cancelableArg
+
Uma {{domxref("Boolean")}} bandeira indicando se o evento associado pode ser evitado (true) ou não (false).
+
animationNameArg
+
Um {{domxref("DOMString")}} contendo o valor do{{cssxref("animation-name")}} propriedade CSS associada com a transição.
+
elapsedTimeArg
+
Um ponto flutuante indicando a quantidade de tempo que a animação esteve rodando, em segundos, com o tempo do evento terminar, excluirá-se o tempo em que a animação esteve em pausa.Para um "animationstart" evento, elapsedTime é 0.0 a não ser que haja um valor negativo para animation-delay, nesse caso o evento irá terminar com elapsedTime contendo (-1 * delay).
+
+ +

Especificações

+ +

Esse método é não-padrão e não é parte de qualquer especificação, no entanto ele esteve presente nos primeiros rascunhos de {{SpecName("CSS3 Animations")}}.

+ +

Compatibilidade com os Navegadores

+ +

{{ CompatibilityTable }}

+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{ CompatGeckoDesktop("6.0") }}
+ Removed in {{ CompatGeckoDesktop("23.0") }}
10.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+ +

 

+ +

 

+
+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{ CompatGeckoMobile("6.0") }}
+ Removed in {{ CompatGeckoMobile("23.0") }}
10.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

See also

+ + diff --git a/files/pt-br/web/api/animationevent/pseudoelement/index.html b/files/pt-br/web/api/animationevent/pseudoelement/index.html new file mode 100644 index 0000000000..0e68a22532 --- /dev/null +++ b/files/pt-br/web/api/animationevent/pseudoelement/index.html @@ -0,0 +1,102 @@ +--- +title: AnimationEvent.pseudoElement +slug: Web/API/AnimationEvent/pseudoElement +tags: + - AnimationEvent + - Animação Web + - Apps + - CSSOM + - Propriedade + - Referencia +translation_of: Web/API/AnimationEvent/pseudoElement +--- +

{{SeeCompatTable}}{{ apiref("Web Animations API") }}

+ +

Sumário

+ +

AnimationEvent.pseudoElement é uma propriedade só de leitura do {{domxref("DOMString")}}, começando com '::', contendo o nome do pseudo-element em que a animação roda. Se a animação não roda em um pseudo-elemento mas em um elemento, então temos uma string vazia : ''.

+ +

Síntaxe

+ +
name = AnimationEvent.pseudoElement
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{ SpecName('CSS3 Animations', '#AnimationEvent-pseudoElement', 'AnimationEvent.pseudoElement') }}{{ Spec2('CSS3 Animations')}}Initial definition.
+ +

Compatibilidade com os Navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatNo}}{{ CompatGeckoDesktop("23.0") }}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+

 

+ +

 

+ + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{ CompatGeckoMobile("23.0") }}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

See also

+ + diff --git a/files/pt-br/web/api/api_de_desempenho/index.html b/files/pt-br/web/api/api_de_desempenho/index.html new file mode 100644 index 0000000000..1b6997e293 --- /dev/null +++ b/files/pt-br/web/api/api_de_desempenho/index.html @@ -0,0 +1,138 @@ +--- +title: API de Desempenho +slug: Web/API/API_de_Desempenho +translation_of: Web/API/Performance_API +--- +
{{DefaultAPISidebar("High Resolution Time")}}
+ +

The High Resolution Time standard defines a {{domxref("Performance")}} interface that supports client-side latency measurements within applications. The {{domxref("Performance")}} interfaces are considered high resolution because they are accurate to a thousandth of a millisecond (subject to hardware or software constraints). The interfaces support a number of use cases including calculating frame-rates (potentially important in animations) and benchmarking (such as the time to load a resource).

+ +

Since a platform's system clock is subject to various skews (such as NTP adjustments), the interfaces support a monotonic clock i.e. a clock that is always increasing. As such, the Performance API defines a {{domxref("DOMHighResTimeStamp")}} type rather than using the {{jsxref("Date.now","Date.now()")}} interface.

+ +

DOMHighResTimeStamp

+ +

The {{domxref("DOMHighResTimeStamp")}} type, as its name implies, represents a high resolution point in time. This type is a double and is used by the performance interfaces. The value could be a discrete point in time or the difference in time between two discrete points in time.

+ +

The unit of DOMHighResTimeStamp is milliseconds and should be accurate to 5 µs (microseconds). However, If the browser is unable to provide a time value accurate to 5 microseconds (because, for example, due to hardware or software constraints), the browser can represent the value as a time in milliseconds accurate to a millisecond.

+ +

Methods

+ +

The {{domxref("Performance")}} interface has two methods. The {{domxref("Performance.now","now()")}} method returns a {{domxref("DOMHighResTimeStamp")}} whose value that depends on the {{domxref("PerformanceTiming.navigationStart","navigation start")}} and scope. If the scope is a window, the value is the time the browser context was created and if the scope is a {{domxref("Worker","worker")}}, the value is the time the worker was created.

+ +

The {{domxref("Performance.toJSON","toJSON()")}} method returns a serialization of the {{domxref("Performance")}} object, for those attributes that can be serialized.

+ +

Properties

+ +

The {{domxref("Performance")}} interface has two properties. The {{domxref("Performance.timing","timing")}} property returns a {{domxref("PerformanceTiming")}} object containing latency-related performance information such as the start of navigation time, start and end times for redirects, start and end times for responses, etc.

+ +

The {{domxref("Performance.navigation","navigation")}} property returns a {{domxref("PerformanceNavigation")}} object representing the type of navigation that occurs in the given browsing context, such as the page was navigated to from history, the page was navigated to by following a link, etc.

+ +

Interfaces

+ +
+
{{domxref('Performance')}}
+
Provides methods and properties containing timing-related performance information for the given page.
+
{{domxref('PerformanceEntry')}}
+
Provides methods and properties the encapsulate a single performance metric that is part of the performance timeline.
+
{{domxref('PerformanceFrameTiming')}}
+
Provides methods and properties containing frame timing data about the browser's event loop.
+
{{domxref('PerformanceMark')}}
+
An abstract interface for performance entries with an entry type of "mark". Entries of this type are created by calling performance.mark() to add a named DOMHighResTimeStamp (the mark) to the browser's performance timeline.
+
{{domxref('PerformanceMeasure')}}
+
An abstract interface for performance entries with an entry type of "measure". Entries of this type are created by calling performance.measure() to add a namedDOMHighResTimeStamp (the measure) between two marks to the browser's performance timeline.
+
{{domxref('PerformanceNavigationTiming')}}
+
Provides methods and properties to store and retrieve high resolution timestamps or metrics regarding the browser's document navigation events.
+
{{domxref('PerformanceObserver')}}
+
Provides methods and properties used to observe performance measurement events and be notified of new performance entries as they are recorded in the browser's performance timeline.
+
{{domxref('PerformanceResourceTiming')}}
+
Provides methods and properties for retrieving and analyzing detailed network timing data regarding the loading of an application's resources.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Highres Time')}}{{Spec2('Highres Time')}}Initial definition.
{{SpecName('Highres Time Level 2')}}{{Spec2('Highres Time Level 2')}}Adds performance attribute on Window and WorkerGlobalScope.
{{SpecName('Highres Time Level 3')}}{{Spec2('Highres Time Level 3')}}Add timeOrigin property to Performance interface.
{{SpecName('Frame Timing')}}{{Spec2('Frame Timing')}}Adds PerformanceFrameTiming interface.
{{SpecName('Navigation Timing')}}{{Spec2('Navigation Timing')}}Adds the PerformanceTiming and PerformanceNavigation interfaces. Adds timing and navigation properties to the Performance interface.
{{SpecName('Navigation Timing Level 2')}}{{Spec2('Navigation Timing Level 2')}}Adds the PerformanceNavigationTiming interface. Obsolete's the the PerformanceTiming interface, the PerformanceNavigation interface, as well as the timing and navigation properties to the Performance interface.
{{SpecName('Performance Timeline')}}{{Spec2('Performance Timeline')}}Adds the PerformanceEntry interface, the PerformanceEntryList type, as well as the getEntries(), getEntriesByType(), and getEntriesByName() methods on the Performance interface.
{{SpecName('Performance Timeline Level 2')}}{{Spec2('Performance Timeline Level 2')}}Adds serializer to the PerformanceEntry interface as well as adding the PerformanceObserver interface and callback
{{SpecName('Resource Timing')}}{{Spec2('Resource Timing')}}Adds the PerformanceResourceTiming interface. Adds the clearResourceTimings() method, the setResourceTimingBufferSize() method, and the onresourcetimingbufferfull event handler to the Performance interface. Also adds the Timing-Allow-Origin response header.
{{SpecName('Resource Timing 2')}}{{Spec2('Resource Timing 2')}}Adds the nextHopProtocol, workerStart, transferSize, encodedBodySize, and decodedBodySize properties to the PerformanceResourceTiming interface.
{{SpecName('Resource Timing 3')}}{{Spec2('Resource Timing 3')}}
{{SpecName('User Timing')}}{{Spec2('User Timing')}}Adds mark(), clearMarks(), measure() and clearMeasures() methods to the Performance interface. Adds the PerformanceMark and PeformanceMeasure interfaces.
{{SpecName('User Timing Level 2')}}{{Spec2('User Timing Level 2')}}
+ +

Implementation status

+ +

As shown in the {{domxref("Performance")}} interface's Browser Compatibility table, most of these interfaces are broadly implemented by desktop browsers.

+ +

To test your browser's support for the {{domxref("Performance")}} interface, run the perf-api-support application.

+ +

See Also

+ + diff --git a/files/pt-br/web/api/api_push/best_practices/index.html b/files/pt-br/web/api/api_push/best_practices/index.html new file mode 100644 index 0000000000..9b0fafd2b7 --- /dev/null +++ b/files/pt-br/web/api/api_push/best_practices/index.html @@ -0,0 +1,73 @@ +--- +title: Melhores práticas +slug: Web/API/API_Push/Best_Practices +tags: + - Apps + - Iniciante + - Melhores Práticas + - Notificações + - Push API + - Usabilidade +translation_of: Web/API/Push_API/Best_Practices +--- +

{{draft}}

+ +

Este artigo proporciona um compilado das melhores práticas a serem usadas enquanto estiver desenvolvendo websites e aplicações que usem Notificações push para engajamento de usuários.

+ +
+

“Se feito de uma maneira correta, as notificações ajudam os usuarios, se não, so irritam.” — Conversa entre dois desenvolvedores a respeito da etica das notificações push.

+
+ +

Visão Geral do web push notifications

+ +

Notificações Web Push (criadas usando uma combinação das APIs de Notificações, Push e Service Worker) são parte de um movimento crescente em que desenvolvedores e comerciantes estão usando para conseguir atenção para seus sites. Uma procura rápida pelo termo "web push notifications", irá resultar em vários artigos, em que especialistas em marketing que acreditam que deve-se usar a API de Push para recapturar a atenção de pessoas que saíram de seu site para que possam terminar o que estavam fazendo, por exemplo, uma compra, ou então enviar as últimas notícias e até recomendação de produtos

+ +

O Lado obscuro

+ +

Essa novidade oferece uma oportunidade nova e inexplorada para sites empresariais chegarem aos seus consumidores finais. Seu usuário trocou de aba para responder um email? Consiga-os de volta com uma oferta que expira em um tempo limitado ou oferecendo frete grátis, o qual ele não vai poder ignorar

+ +

Mas sério, qual o melhor uso das notificações push? Ou é apenas uma nova interação dos bons e velhos pop-ups?

+ +
+

O envio de notificações push não corre o risco de acabar na pasta de spam. Nem pode ser bloqueado por bloqueadores de anúncios. Ele aparece na sua área de trabalho, mesmo quando o site está fechado. No celular, ele aparece na barra de notificações, assim como as notificações por push do aplicativo, mesmo quando o navegador não está em execução.” — um site de marketing anonimo

+
+ +

Bons usos das notificações

+ +

Mas há também um lado bom no que se diz respeito as notificações por push. Digamos que você e sua equipe usem normalmente um programa de bate-papo para se comunicar, mas hoje você está feliz e saltitante trabalhando e surge um problema. Digamos que seu gerente tenha encontrado um problema nas aprovações e queira receber seu feedback sobre algo antes que ela prossiga.

+ +

Neste documento, falaremos sobre o uso correto das notificações por push da web. Às vezes, eles podem eliminar a frustração e o aborrecimento e, às vezes, causá-los. Cabe a você, como desenvolvedor, fazer recomendações (e decisões) sábias sobre o uso de notificações por push.

+ +

O que se espera alcançar com as notificações push?

+ +

Como tudo, com grande poder vem uma grande responsabilidade. Toda notificação push devem ser úteis e sensíveis ao tempo, o usuário sempre deve fornecer a permissão antes de recebe-la primeiro e deve-se oferecer uma maneira fácil de optar por não receber mais no futuro.

+ +

Temos que responder algumas perguntas basicas para verificar se as notificações são necessarias:

+ + + +

Além da questão de saber se uma notificação por push é necessária, existem muitas variedades de notificações por push, variando de casual e efêmera a persistente e exigente.

+ +

Aconselhamos que você use as notificações que exigem uma interação de forma conciente e com moderação, pois estas podem irritar seu usuario e afasta-lo. Suas notificações devem ser acolhedoras, não hostis.

+ +

Gerando confiança

+ +

Alguns estudos mostraram que até 60% das notificações por push não chegam ao usuário final. Permitir que seu usuario receba notificações por push em tempo real exige confiança, por parte do aplicativo. Você pode criar confiança ao ter um site bem projetado que forneça um bom conteúdo e que mostre respeito pelo usuário alem de um valor claro para que o usuario aceite as notificações push.

+ +

Mitigações dos navegadores

+ +

Por causa dos abusos da utilização das notificações por push no passado, os desenvolvedores de navegadores começaram a implementar estratégias para ajudar a mitigar esse problema. Por exemplo, o Safari 12.1 agora exige - e outros navegadores já o fazem ou estão planejando[1] fazer—que o usuário interaja com a página de alguma forma antes que ela possa solicitar permissão para executar notificações por push, assim como já acontece com os popups. Isso pelo menos impede que o usuário receba espontaneamente essa pergunta em páginas da Web que apenas olharam de uma só vez, raramente ou nunca mais.

+ +

[1] No caso do Firefox, veja {{bug(1524619)}}, podemos observar que Firefox 68 implementa isso, desabilitado por padrão, usando a preferência dom.webnotifications.requireuserinteraction.

+ +

Veja também

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

A API Push torna possível que aplicações web recebam mensagens enviadas a elas de um servidor, indepententemente de aplicação estar ou não em primeiro plano, ou até mesmo carregada, em um agente de usuário. Isso permite que desenvolvedores entreguem notificações e atualizações assíncronas a usuários que optarem por elas, resultando num melhor engajamento com conteúdo novo oportuno.

+ +
+

Nota: Esta documentação cobre a especificação W3C da API Push; se você procura pela documentação do sistema de notificação proprietária do mecanismo push, veja Simple Push.

+
+ +

Conceitos e uso de Push

+ +

Para uma aplicação receber mensagens push, ela precisa ter um service worker ativo. Quando o service worker está ativo, ele pode se inscrever para utilizar notificações push {{domxref("PushManager.subscribe()")}}.

+ +

O resultado de {{domxref("PushSubscription")}} inclui toda informação que a aplicação precisa para receber uma mensagem push: um endpoint e a chave encriptada necessária para o envio de dados.

+ +

O service worker será iniciado conforme o necessário para lidar com as mensagens recebidas, que são entregues ao manipulador de evento {{domxref("ServiceWorkerGlobalScope.onpush")}} . Isto permite que a aplicação reaja a cada mensagem recebida, por exemplo para exibir a notificação ao usuário (usando {{domxref("ServiceWorkerRegistration.showNotification()")}}.)

+ +

Cada assinatura é única para um service worker.  O endpoint para a assinatura é uma capability URL única: o conhecimento do endpoint é tudo que é necessário para enviar uma mensagem para sua aplicação. A URL do endpoint precisa ser mantida em segredo, ou outras aplicações estranhas poderão enviar mensagens push para a sua aplicação.

+ +

A ativação de um service worker para entregar mensagens push pode resultar em um aumento de uso de recursos, particularmente de bateria. Diferentes navegadores tem diferentes formas para lidar com isso — atualmente não existe uma forma padrão. Firefox permite um número limitado (cota) de mensagens push para serem enviadas para uma aplicação, embora as mensagens Push que gerem notificações são isentas deste limite.  O limite é atualizado a cada site visitado. Numa comparação, Chrome não aplica nenhum limite, mas requer que cada mensagem push exiba uma notificação.

+ +
+

Nota: A partir do Gecko 44, a cota permitida de mensagens push por aplicação não é incrementada quando uma nova notificação é disparada quando outra está visível, por um período de três segundos. Isso lida com casos em que várias notificações são recebidas ao mesmo tempo, mas nem todas estão visíveis.

+
+ +
+

Nota: Chrome atualmente requer que você crie um projeto no Google Cloud Messaging para enviar mensagens push e use um número do projeto e chave da API para o envio de notificações push. Isto também requer um app manifest com alguns parâmetros especiais para usar o serviço. Essa restrição deverá ser removida no futuro.

+
+ +

Interfaces

+ +
+
{{domxref("PushEvent")}}
+
Representa uma ação push enviada para o global scope de um {{domxref("ServiceWorker")}}. Ele contém informações enviadas de uma aplicação para um {{domxref("PushSubscription")}}.
+
{{domxref("PushManager")}}
+
Fornece uma forma de receber notificações de servidor third-party bem como solicitar URL para notificações push. Essa interface substitui a funcionalidade oferecida que está obsoleta {{domxref("PushRegistrationManager")}} interface.
+
{{domxref("PushMessageData")}}
+
Fornece acesso aos dados push enviados por um servidor, e inclui métodos para manipular os dados recebidos.
+
{{domxref("PushSubscription")}}
+
Fornece a URL de assinatura do endpoint e permite o cancelamento da assinatura de um serviço push.
+
+ +

Service worker additions

+ +

As seguintes informações adicionais para a Service Worker API foram especificadas na Push API spec, para fornecer um ponto de entrada para usar mensagens Push, e para monitorar e responder os eventos de envio e assinatura.

+ +
+
{{domxref("ServiceWorkerRegistration.pushManager")}} {{readonlyinline}}
+
Retorna uma referência para a interface {{domxref("PushManager")}} para administrar assinaturas push incluindo subscrever, obter uma assinatura ativa e acessar o status de permissão de envio. Este é o ponto de entrada para usar mensagens Push.
+
{{domxref("ServiceWorkerGlobalScope.onpush")}}
+
Um manipulador de eventos disparado sempre que um evento  {{Event("push")}} ocorre; isto é, sempre que uma mensagem do servidor de envio for recebida.
+
{{domxref("ServiceWorkerGlobalScope.onpushsubscriptionchange")}}
+
Um manipulador de eventos disparado sempre que um evento  {{Event("pushsubscriptionchange")}} ocorre; por exemplo, quando uma assinatura push está inválida, ou está prestes a ser invalidada (ex. quando um serviço push service define um tempo de expiração.)
+
+ +

Especificações

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

Compatibilidade em Browsers

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

[1] Atualmente disponível apenas nas versões desktop do Firefox; ainda, mensagens push são encaminhadas apenas quando o Firefox está em execução.

+ +

[2] Ainda não implementado. Veja Microsoft Edge status information.

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/api_web_audio/index.html b/files/pt-br/web/api/api_web_audio/index.html new file mode 100644 index 0000000000..8f582eb524 --- /dev/null +++ b/files/pt-br/web/api/api_web_audio/index.html @@ -0,0 +1,480 @@ +--- +title: API Web Áudio +slug: Web/API/API_Web_Audio +tags: + - Web Audio API + - api de áudio + - áudio api + - áudio web +translation_of: Web/API/Web_Audio_API +--- +
+

A API de áudio da web disponibiliza um poderoso e versátil sistema de controle de áudio para a Web, permitindo aos desenvolvedores escolher arquivos de áudio, adicionar efeitos a estes arquivos, criar reprodutores de áudio, aplicar spatial effects (como panning) e muito mais.

+
+ +

Web audio: conceitos e uso

+ +

A API de Web audio envolve manipulação de operações com áudio dentro de um contexto de áudio, e foi desenvolvida para permitir o roteamento modular. Operações básicas de áudio são feitas com audio nodes (nós de áudio), que são ligados para formar gráficos de roteamento de áudio. Várias fontes - com diferentes tipos de layout de canal - são suportados mesmo em um único contexto. Este design modular permite flexibilidade para criar funções de áudio complexas com efeitos dinâmicos.

+ +

Audio nodes são ligados pelas suas entradas e saídas, formando uma cadeia que começa com uma ou mais fontes, passa por um ou mais nodes e então acaba em um destino (embora você não tenha que fornecer um destino, por exemplo, se você quiser apenas visualizar alguns dados de áudio). Um fluxo de trabalho simples, com Web áudio, seria algo parecido com isso:

+ +
    +
  1. Crie um contexto de áudio
  2. +
  3. Dentro do contexto, crie fontes de áudio — como <audio>, oscilador, stream
  4. +
  5. Crie efeitos de áudio, como reverb, biquad filter, panner, compressor
  6. +
  7. Escolha o destino final de áudio, por exemplo os auto-falantes de seu sistema
  8. +
  9. Conecte as fontes de áudio com os efeitos, e os efeitos com o destino.
  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.

+ +

O sincronismo é controlado com alta precisão e baixa latência, permitindo aos desenvolvedores escrever códigos que respondam com precisão a eventos e capazes de gerar exemplos específicos, mesmo com uma alta taxa de amostragem. Dessa forma, aplicações como baterias eletrônicas e seqüenciadores estarão facilmente ao alcance dos desenvolvedores.

+ +

A API de Web Audio também permite o controle de como o áudio será ordenado. Usando um sistema baseado em um modelo de source-listener, a API permite controlar os painéis de modelo para serem usados e tratados com atenuação de distância induzida ou doppler shift induzido por uma fonte em movimento (ou um ouvinte em movimento).

+ +
+

Nota: Você pode ver mais detalhes sobre a teoria da API de Web Audio em nosso artigo Basic concepts behind Web Audio API.

+
+ +

Web Audio: Interfaces da API

+ +

A API de Web Audio possui um total de 28 interfaces e eventos associados, que nós dividimos e categorizamos em 9 funcionalidades.

+ +

Definições gerais de grafos de áudio (audio graph)

+ +

Definições gerais que moldam os grafos de áudio no uso da API de Web Audio.

+ +
+
{{domxref("AudioContext")}}
+
A interface AudioContext representa um grafo de processamento de áudio construído a partir de módulos de áudio ligados entre si, cada um representado por um {{domxref("AudioNode")}}. Um contexto de áudio (audio context) controla a criação dosnós que ele contém e a execução do processamento de áudio, ou a decodificação. Como tudo acontece dentro de um contexto, você deve criar um AudioContext antes de fazer qualquer outra coisa.
+
{{domxref("AudioNode")}}
+
A interface AudioNode representa um módulo de processamento de áudio como uma fonte de áudio (por exemplo, um HTML {{HTMLElement("áudio")}} ou um elemento {{HTMLElement("vídeo")}}), destino de áudio, módulo de processamento intermediário (por exemplo, um filtro como {{domxref("BiquadFilterNode")}}, ou controle de volume, como {{domxref("GainNode")}}).
+
{{domxref("AudioParam")}}
+
A interface AudioParam representa um parâmetro relacionado ao áudio, como um parâmetro de um {{domxref("AudioNode")}}. Ele pode ser configurado com um valor específico ou uma mudança de valor, e pode ser programado para "acontecer" em um momento específico e seguindo um padrão específico.
+
{{event("ended_(Web_Audio)", "ended")}} (event)
+
O evento ended é disparado quando a reprodução parou porque o fim da mídia foi atingido.
+
+ +

Definindo fontes de áudio

+ +

Interfaces que definem fontes de áudio para uso na API de Web Audio.

+ +
+
{{domxref("OscillatorNode")}}
+
A interface OscillatorNode representa uma onda senoidal. Esta interface é um módulo de processamento de áudio que gera uma onda senoidal com determinada frequência.
+
{{domxref("AudioBuffer")}}
+
A interface AudioBuffer representa uma pequena porção de áudio armazenada na memória, criada a partir de um arquivo de áudio usando o método {{ domxref("AudioContext.decodeAudioData()") }}, ou criado com os dados brutos usando o método {{ domxref("AudioContext.createBuffer()") }}. Uma vez decodificado neste formato o áudio pode ser colocada em um {{ domxref("AudioBufferSourceNode") }}.
+
{{domxref("AudioBufferSourceNode")}}
+
A interface AudioBufferSourceNode representa uma fonte de áudio que consiste em dados de áudio na memória, armazenados em um {{domxref ("AudioBuffer")}}. É um {{domxref ("AudioNode")}} que atua como uma fonte de áudio.
+
{{domxref("MediaElementAudioSourceNode")}}
+
A interface MediaElementAudioSourceNode  representa uma fonte de audio consiste de um HTML5 {{ htmlelement("audio") }} ou {{ htmlelement("video") }} elemento. É uma {{domxref("AudioNode")}} que atua como uma fonte de áudio.
+
{{domxref("MediaStreamAudioSourceNode")}}
+
The MediaStreamAudioSourceNode interface represents an audio source consisting of a WebRTC {{domxref("MediaStream")}} (such as a webcam or microphone.) It is an {{domxref("AudioNode")}} that acts as an audio source.
+
+ +

Definindo filtros de efeitos de áudio

+ +

Interfaces para definição de efeitos que você deseja aplicar em suas fontes de áudio.

+ +
+
{{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 AudioBuffer, 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("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")}}
+
Used to define a periodic waveform that can be used to shape the output of an {{ domxref("OscillatorNode") }}.
+
+ +

Definindo destinos de áudio

+ +

Uma vez que você tenha feito o processamento do seu áudio, estas interfaces definirão aonde será a saída do áudio.

+ +
+
{{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 MediaElementAudioSourceNode 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 MediaStream obtained from {{ domxref("Navigator.getUserMedia") }}. It is an {{domxref("AudioNode")}} that acts as an audio destination.
+
+ +

Análise dos dados e visualização

+ +

Se você deseja extrair tempo, frequencia e outras informações do seu áudio, o AnalyserNode é o que você necessita.

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

Dividindo e mesclando canais de áudio

+ +

Para dividir e mesclar canais de áudio, você utilizará essas 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 outputs. 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.
+
+ +

Processamento de áudio por JavaScript

+ +

Se você quiser usar um script externo para processar sua fonte de áudio, Node e eventos abaixo tornarão isto possível.

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

Áudio offline

+ +

Manipular áudio offline é possível com estas interfaces.

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

Interfaces obsoletas

+ +

As interfaces a seguir foram definidas em versões antigas das especificações da API de Web Audio, mas agora elas estão obsoletas e serão substituidas por outras 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

+ +

Este exemplo mostra uma grande variedade de funções da API de Web Audio que podem ser utilizadas. Você pode ver este código em ação na demo Voice-change-o-matic (também verificar o código-fonte completo no Github) - esta é uma demonstração de um modificador de voz de brinquedo experimental; aconselhamos manter seus alto-falantes baixo ao utilizá-lo, pelo menos para começar!

+ +

As linhas API de Web Audio estão destacadas; se você quiser encontrar mais informações sobre os diferentes métodos, faça uma busca através das páginas de referência.

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

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('Web Audio API')}}{{Spec2('Web Audio API')}} 
+ +

Compatibilidade de navegadores

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

 

+ +

Veja também

+ + + + diff --git a/files/pt-br/web/api/api_web_audio/sintetizador_simples/index.html b/files/pt-br/web/api/api_web_audio/sintetizador_simples/index.html new file mode 100644 index 0000000000..b0fdf2a0c4 --- /dev/null +++ b/files/pt-br/web/api/api_web_audio/sintetizador_simples/index.html @@ -0,0 +1,579 @@ +--- +title: 'Tutorial e exemplo: Teclado de Sintetizador Simples' +slug: Web/API/API_Web_Audio/Sintetizador_simples +tags: + - Audio + - Exemplo + - Guía + - Media + - Oscilador + - Piano + - Sintetizador + - Tutorial + - Web Audio API +translation_of: Web/API/Web_Audio_API/Simple_synth +--- +
{{DefaultAPISidebar("Web Audio API")}}
+ +

Este artigo apresenta o código e uma demonstração funcional de um teclado que você pode tocar usando seu mouse. O teclado lhe permite alternar entre formas de onda padrões e customizadas. Esse exemplo utiliza das seguintes interfaces de Web API: {{domxref("AudioContext")}}, {{domxref("OscillatorNode")}}, {{domxref("PeriodicWave")}}, e {{domxref("GainNode")}}.

+ +

Já que {{domxref("OscillatorNode")}} é baseado no {{domxref("AudioScheduledSourceNode")}}, isso até certo ponto também é um exemplo pra isto.

+ +

O Teclado Visual

+ +

HTML

+ +

Existem três componentes primários para o display do nosso teclado virtual. O primeito do qual é o teclado musical em si. Nós extraimos em um par de elementos {{HTMLElement("div")}} aninhados para permitir a rolagem horizontal caso as teclas não encaixem na tela.

+ +

O Teclado

+ +

Primeiro, criamos o espaço no qual construiremos o teclado. Estaremos construindo o teclado programaticamente, considerando que ao fazer desse jeito teremos a flexibilidade de configurar cada tecla conforme determinamos as informações apropriadas para tecla correspondente. No nosso caso, pegamos a frequência de cada tecla através de uma tabela, mas poderia ser calculado de forma algoritmica também.

+ +
<div class="container">
+  <div class="keyboard"></div>
+</div>
+
+ +

O {{HTMLElement("div")}} nomeado de "container" é a barra de rolagem que permite o teclado ser rolado horizontalmente se for largo demais para o espaço disponivel. As teclas em si serão inseridas no bloco de classe "keyboard".

+ +

A barra de opções

+ +

Abaixo do teclado, colocaremos alguns controles para configurar o camada. Por enquanto, teremos dois controles: Um para controlar o volume e outro para selecionar a forma de onda periodica usada ao gerar as notas.

+ +
O controle de volume
+ +

Primeiro criamos o <div> para conter a barra de opções, para ser personalizado conforme preciso. Então estabelecemos uma caixa que será apresentada no lado esquerdo da barra e colocar um rotulo e um elemento {{HTMLElement("input")}} do tipo "range". O elemento range será tipicamente apresentado como o controle da barra de rolagem ; configuramos ele para permitir qualquer valor entre 0.0 e 1.0 em cada posição.

+ +
<div class="settingsBar">
+  <div class="left">
+    <span>Volume: </span>
+    <input type="range" min="0.0" max="1.0" step="0.01"
+        value="0.5" list="volumes" name="volume">
+    <datalist id="volumes">
+      <option value="0.0" label="Mute">
+      <option value="1.0" label="100%">
+    </datalist>
+  </div>
+
+ +

Especificamos um valor padrão de 0.5, e provemos um elemento {{HTMLElement("datalist")}} no qual é conectado ao range usando o atributo {{htmlattrxref("name")}} para achar uma lista de opções cujo ID encaixa; nesse caso, o conjunto de informações é nomeado de "volume". isso nos permite prover um conjunto de valores comuns e strings especiais que o browser pode de forma opcional escolher mostrar de alguma maneira; e então atribuimos nomes aos valores 0.0 ("Mute") e 1.0 ("100%").

+ +
A seleção de forma de onda
+ +

E no lado da barra de configurações, colocamos um rótulo e um elemento {{HTMLElement("select")}} nomeado de "waveform" cujas opções correspondem as formas de onda disponiveis.

+ +
  <div class="right">
+    <span>Current waveform: </span>
+    <select name="waveform">
+      <option value="sine">Sine</option>
+      <option value="square" selected>Square</option>
+      <option value="sawtooth">Sawtooth</option>
+      <option value="triangle">Triangle</option>
+      <option value="custom">Custom</option>
+    </select>
+  </div>
+</div>
+ + + +

JavaScript

+ +

O código em JavaScript começa inicializando algumas váriaveis.

+ +
let audioContext = new (window.AudioContext || window.webkitAudioContext)();
+let oscList = [];
+let masterGainNode = null;
+
+ +
    +
  1. audioContext é colocado para referenciar o objeto global {{domxref("AudioContext")}} (ou webkitAudioContext se  necessário).
  2. +
  3. oscillators está colocado para conter uma lista de todos os osciladores atualmente tocando. Ele começa nulo, afinal não há nenhum oscilador tocando ainda.
  4. +
  5. masterGainNode é colocado como nulo; durante o processo de setup, ele será configurado para contar um {{domxref("GainNode")}} no quall todos os osciladores irão se conectar para permitir o volume geral a ser controlado por apenas uma barra de rolagem.
  6. +
+ +
let keyboard = document.querySelector(".keyboard");
+let wavePicker = document.querySelector("select[name='waveform']");
+let volumeControl = document.querySelector("input[name='volume']");
+
+ +

Referencias aos elementos que precisaremos acessar são obtidas através dp:

+ + + +
let noteFreq = null;
+let customWaveform = null;
+let sineTerms = null;
+let cosineTerms = null;
+
+ +

Enfim, variaveis globais que serão usadas quando as formas de onda são criadas:

+ + + +

Criando a tabela de notas

+ +

A função createNoteTable() constrói a matriz noteFreq para conter uma matriz de objetos representando cada oitava. Cada oitava, possui uma propriedade para cada nota nessa oitava; O nome dessa propriedade é o nome da nota (utilizando da notação em inglês, como "C" para representar "dó"), e o valor é a frequência, em Hertz, daquela nota.

+ +
function createNoteTable() {
+  let noteFreq = [];
+  for (let i=0; i< 9; i++) {
+    noteFreq[i] = [];
+  }
+
+  noteFreq[0]["A"] = 27.500000000000000;
+  noteFreq[0]["A#"] = 29.135235094880619;
+  noteFreq[0]["B"] = 30.867706328507756;
+
+  noteFreq[1]["C"] = 32.703195662574829;
+  noteFreq[1]["C#"] = 34.647828872109012;
+  noteFreq[1]["D"] = 36.708095989675945;
+  noteFreq[1]["D#"] = 38.890872965260113;
+  noteFreq[1]["E"] = 41.203444614108741;
+  noteFreq[1]["F"] = 43.653528929125485;
+  noteFreq[1]["F#"] = 46.249302838954299;
+  noteFreq[1]["G"] = 48.999429497718661;
+  noteFreq[1]["G#"] = 51.913087197493142;
+  noteFreq[1]["A"] = 55.000000000000000;
+  noteFreq[1]["A#"] = 58.270470189761239;
+  noteFreq[1]["B"] = 61.735412657015513;
+
+ +

... várias oitavas não mostradas para manter breve ...

+ + + +
  noteFreq[7]["C"] = 2093.004522404789077;
+  noteFreq[7]["C#"] = 2217.461047814976769;
+  noteFreq[7]["D"] = 2349.318143339260482;
+  noteFreq[7]["D#"] = 2489.015869776647285;
+  noteFreq[7]["E"] = 2637.020455302959437;
+  noteFreq[7]["F"] = 2793.825851464031075;
+  noteFreq[7]["F#"] = 2959.955381693075191;
+  noteFreq[7]["G"] = 3135.963487853994352;
+  noteFreq[7]["G#"] = 3322.437580639561108;
+  noteFreq[7]["A"] = 3520.000000000000000;
+  noteFreq[7]["A#"] = 3729.310092144719331;
+  noteFreq[7]["B"] = 3951.066410048992894;
+
+  noteFreq[8]["C"] = 4186.009044809578154;
+  return noteFreq;
+}
+
+ +

O resultado é uma matriz, noteFreq, com um objeto para cada oitava. Cada objeto de oitava tem propriedades nomeadas nela onde a propriedade é o nome da nota com a notação em inglês (Como "C" para representar "dó") e o valor da propriedade é a frequência da nota em Hertz.. o objeto resultando se parece com isso:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
OctaveNotes
0"A" ⇒ 27.5"A#" ⇒ 29.14"B" ⇒ 30.87
1"C" ⇒ 32.70"C#" ⇒ 34.65"D" ⇒ 36.71"D#" ⇒ 38.89"E" ⇒ 41.20"F" ⇒ 43.65"F#" ⇒ 46.25"G" ⇒ 49"G#" ⇒ 51.9"A" ⇒ 55"A#" ⇒ 58.27"B" ⇒ 61.74
2. . .
+ +

Com esta tabela no lugar, podemos descobrir a frequência para uma dada nota em uma oitava particular relativamente fácil. Se queremos a frequência pra nota G# na primeira oitava, nós simplesmente usamos  noteFreq[1]["G#"] e conseguimos o valor 51.9 como resultado.

+ +
+

Os valores na tabela de exemplo acima foram arredondados para duas casas decimais.

+
+ + + +

Construindo o teclado

+ +

A função setup() é responsavel por construir o teclado e preparar a aplicação para tocar a música.

+ +
function setup() {
+  noteFreq = createNoteTable();
+
+  volumeControl.addEventListener("change", changeVolume, false);
+
+  masterGainNode = audioContext.createGain();
+  masterGainNode.connect(audioContext.destination);
+  masterGainNode.gain.value = volumeControl.value;
+
+  // Create the keys; skip any that are sharp or flat; for
+  // our purposes we don't need them. Each octave is inserted
+  // into a <div> of class "octave".
+
+  noteFreq.forEach(function(keys, idx) {
+    let keyList = Object.entries(keys);
+    let octaveElem = document.createElement("div");
+    octaveElem.className = "octave";
+
+    keyList.forEach(function(key) {
+      if (key[0].length == 1) {
+        octaveElem.appendChild(createKey(key[0], idx, key[1]));
+      }
+    });
+
+    keyboard.appendChild(octaveElem);
+  });
+
+  document.querySelector("div[data-note='B'][data-octave='5']").scrollIntoView(false);
+
+  sineTerms = new Float32Array([0, 0, 1, 0, 1]);
+  cosineTerms = new Float32Array(sineTerms.length);
+  customWaveform = audioContext.createPeriodicWave(cosineTerms, sineTerms);
+
+  for (i=0; i<9; i++) {
+      oscList[i] = {};
+  }
+}
+
+setup();
+ +
    +
  1. A tabela que mapeia o nome e oitavas das notas para suas respectivas frequências é criado ao chamar createNoteTable().
  2. +
  3. Um manipulador de eventos é estabelecido ao chamar nosso velho amigo {{domxref("EventTarget.addEventListener", "addEventListener()")}} para cuidar dos eventos do {{event("change")}} no controle de ganho geral. Isso vai simplesmente atualizar o módulo de ganho de volume para o novo valor.
  4. +
  5. Em seguida, nós replicamos cada oitava na tabela de frequências das notas. Para cada oitava, usamos {{jsxref("Object.entries()")}} para conseguir uma lista de notas daquela oitava.
  6. +
  7. Criar um {{HTMLElement("div")}} para contar as notas daquela oitava (para ter um pouco de espaço entre as oitavas), e mudar o nome de classe para "octave".
  8. +
  9. Para cada tecla na oitava, checamos para ver se o nome daquela nota há mais de um caractere. Nós pulamos essas, pois estamos deixando notas sustenidas de fora deste exemplo. Do contrário, chamamos createKey(), especificando uma string, oitava, e frequência. O elemento retornado é anexado na elemento da oitava criada no passo 4.
  10. +
  11. Quando o elemento da oitava é construido, é então anexada ao teclado.
  12. +
  13. Uma vez que o teclado foi construido, nós rolamos para nota "B" na quinta oitava; isso tem o efeito de garantir que o C médio é visivel junto das notas ao redor.
  14. +
  15. Então uma forma de onda customizada é construida usando {{domxref("AudioContext.createPeriodicWave()")}}. Essa forma de onda será usada toda vez que o usuário selecionar "Custom" da seleção de formas de onda.
  16. +
  17. Enfim, a lista de osciladores é iniciada para garantir que está pronta para receber informação identificando quais osciladores estão associados com que teclas.
  18. +
+ +

Criando uma tecla

+ +

A função createKey()  é chamada toda vez que queremos que uma tecla seja apresentada no nosso teclado virtual. Ela cria elementos da tecla e seu rótulo, adiciona informação dos atributos ao elemento para uso posterior, e coloca modificadores de eventos para os eventos que nos importam.

+ +
function createKey(note, octave, freq) {
+  let keyElement = document.createElement("div");
+  let labelElement = document.createElement("div");
+
+  keyElement.className = "key";
+  keyElement.dataset["octave"] = octave;
+  keyElement.dataset["note"] = note;
+  keyElement.dataset["frequency"] = freq;
+
+  labelElement.innerHTML = note + "<sub>" + octave + "</sub>";
+  keyElement.appendChild(labelElement);
+
+  keyElement.addEventListener("mousedown", notePressed, false);
+  keyElement.addEventListener("mouseup", noteReleased, false);
+  keyElement.addEventListener("mouseover", notePressed, false);
+  keyElement.addEventListener("mouseleave", noteReleased, false);
+
+  return keyElement;
+}
+
+ +

Após criar  os elementos representando as teclas e seus rótulos, nós configuramos o elemento das teclas ao configurar sua classe para "key" (Que estabelece a aparência). Então adicionamos atributos {{htmlattrxref("data-*")}}  que contém a string da oitava da nota (attribute data-octave), representando a nota a ser tocada (attribute data-note), e frequência (attribute data-frequency) em Hertz. Isso irá nos permitir facilmente pegar informação conforme necessário ao cuidar de eventos.

+ +

Fazendo música

+ +

Tocando um tom

+ +

O trabalho da função playTone() é tocar um tom em uma dada frequência. Isso será usado pelo modificador para eventos acionados nas teclas do teclado, para que toquem as notas apropriadas.

+ +
function playTone(freq) {
+  let osc = audioContext.createOscillator();
+  osc.connect(masterGainNode);
+
+  let type = wavePicker.options[wavePicker.selectedIndex].value;
+
+  if (type == "custom") {
+    osc.setPeriodicWave(customWaveform);
+  } else {
+    osc.type = type;
+  }
+
+  osc.frequency.value = freq;
+  osc.start();
+
+  return osc;
+}
+
+ +

playTone() começa criando um novo {{domxref("OscillatorNode")}} ao chamar o método {{domxref("AudioContext.createOscillator()")}}. Então conectamos ele para o módulo de ganha geral ao chamar o novo método de osciladores {{domxref("OscillatorNode.connect()")}} method;, Que determina ao oscilador onde ele irá mandar seu output. Ao fazer isso, mudar o valor do ganho do módulo de ganho geral irá mudar o volume de todos os toms gerados.

+ +

Então conseguimos o tipo de forma de onda para usar ao checar o valor do controle de seleção de formas de onda na barra de opções. Se o usuário estiver colocado como "custom", chamamos {{domxref("OscillatorNode.setPeriodicWave()")}} para configurar os osciladores para usar nossa forma de onda customizada. Fazer isso automáticamente coloca o {{domxref("OscillatorNode.type", "type")}} do oscilador como custom. Se qualquer outro tipo de forma de onda é selecionado na seleção de formas de ondas, nós simplesmente colocamos os tipos de osciladores no valor da seleção, esse valor será um entre sine, square, triangle, e sawtooth.

+ +

A frequência do oscilador é colocada no valor especificado no paramêtro freq ao colocar o valor dos objetos {{domxref("Oscillator.frequency")}} {{domxref("AudioParam")}} . Então, enfim, o oscilador é iniciado e começa a produzir sons ao chamar o método {{domxref("AudioScheduledSourceNode.start()")}} .

+ +

Tocando um tom

+ +

Quando o evento {{event("mousedown")}} ou {{domxref("mouseover")}} ocorre em uma tecla, queremos que toque a nota correspondente. A função notePressed() é usada como o modificador de eventos para esses eventos.

+ +
function notePressed(event) {
+  if (event.buttons & 1) {
+    let dataset = event.target.dataset;
+
+    if (!dataset["pressed"]) {
+      let octave = +dataset["octave"];
+      oscList[octave][dataset["note"]] = playTone(dataset["frequency"]);
+      dataset["pressed"] = "yes";
+    }
+  }
+}
+
+ +

Começamos checando se o botão esquerdo do mouse é pressionado, por dois motivos. Primeiro, queremos que apenas o botão esquerdo acione as notas. Segundo, e mais importante, estamos usando isso para cuidar do {{event("mouseover")}} para casos onde o usuário arrasta de tecla a tecla, e só queremos tocar uma nota se o mouse estiver pressionado quando entrar no elemento.

+ +

Se o botão do mouse estiver de fato sendo pressionado, recebemos o atributo de tecla pressionada {{htmlattrxref("dataset")}} ; isso torna fácil o acesso das informações de atributo customizadas no elemento. Procuramos por um atributo data-pressed ; caso não haja um(o que indica que a nota não está tocando ainda), chamamos playTone() para começar a tocar a nota, passando no valor dos elementos do atributo data-frequency. O valor retornado do oscilador é guardado no oscList para refêrencia futura, e data-pressed é colocado como yes para indicar que a nota está tocando para que não iniciemos novamente na próxima vez que isso for chamado.

+ +

Parando um tom

+ +

A função noteReleased() é o modificador de eventos chamado quando o usuário solta o botão do mouse ou move o mouse para fora da tecla que ele está tocando.

+ +
function noteReleased(event) {
+  let dataset = event.target.dataset;
+
+  if (dataset && dataset["pressed"]) {
+    let octave = +dataset["octave"];
+    oscList[octave][dataset["note"]].stop();
+    delete oscList[octave][dataset["note"]];
+    delete dataset["pressed"];
+  }
+}
+
+ +

noteReleased() usa os atributos customizados data-octave and data-note  para procurar os osciladores das teclas, e então chama o método de oscilador {{domxref("AudioScheduledSourceNode.stop", "stop()")}} para parar de tocar a nota. Finalmente, a entrada oscList para nota é limpa e o atributo data-pressed é removido do elemento da tecla (como identificado pelo {{domxref("event.target")}}), para indicar que a nota não está tocando no momento.

+ +

Mudando o volume geral

+ +

A barra de rolagem do volume na barra de opções dá uma simples interface para mudar o valor do ganho no módulo de ganho geral, então mudando o volume de todas as notas sendo tocadas. O metódo changeVolume() é o modificador do evento {{event("change")}} na barra de rolagem.

+ +
function changeVolume(event) {
+  masterGainNode.gain.value = volumeControl.value
+}
+
+ +

Isso simplesmente coloca o valor do módulo de ganho geral gain {{domxref("AudioParam")}} para o novo valor na barra de rolagem.

+ +

Resultado

+ +

Coloque tudo junto, o resultado é um simples e funcional teclado virtual que funciona com o clique:

+ +

{{ EmbedLiveSample('The_video_keyboard', 680, 200) }}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/attr/index.html b/files/pt-br/web/api/attr/index.html new file mode 100644 index 0000000000..683dda4847 --- /dev/null +++ b/files/pt-br/web/api/attr/index.html @@ -0,0 +1,132 @@ +--- +title: Attr +slug: Web/API/Attr +tags: + - API + - DOM + - Gecko DOM + - JavaScript +translation_of: Web/API/Attr +--- +

{{APIRef("DOM")}}
+ Este tipo representa um atributo de elemento DOM como um objeto. Na maioria dos métodos DOM, você provavelmente irá retornar diretamente o atributo como uma string (e.g., {{domxref("Element.getAttribute()")}}, mas certas funções (e.g., {{domxref("Element.getAttributeNode()")}}) ou meios de iteração retornam tipos Attr.

+ +

{{InheritanceDiagram}}

+ +
Aviso: Começando no Gecko 7.0 {{geckoRelease("7.0")}}, os que serão removidos mostram mensagens de aviso no console. Você deve revisar seu código de acordo. Veja métodos e propriedades descontinuadas para uma lista completa.
+ +

Propriedades

+ +

 

+ +
+
{{domxref("Attr.name", "name")}} {{readOnlyInline}}
+
O nome do Atributo.
+
+ +

 

+ +

 

+ +
+
{{domxref("Attr.namespaceURI", "namespaceURI")}} {{readOnlyInline}}
+
Uma {{domxref("DOMString")}} representando o namespace URI do atributo, ou null se não há namespace
+
{{domxref("Attr.localName", "localName")}} {{readOnlyInline}}
+
Uma {{domxref("DOMString")}} representando a parte local do nome qualificado do atributo.
+
{{domxref("Attr.prefix", "prefix")}} {{readOnlyInline}}
+
Uma {{domxref("DOMString")}} representando o prefixo do namespace do atributo ou null se nenhum prefixo foi especificado.
+
{{domxref("Attr.ownerElement", "ownerElement")}} {{readOnlyInline}}
+
+

O elemento que possui o atributo.

+
+
+ +

 

+ +
+

Nota: DOM Level 4 removeu esta propriedade. Foi suposto que como você recebe um objeto Attr de um {{domxref("Element")}}, você já deve saber qual é o elemento associado.
+ Como isto não é sempre verdadeiro em casos como objetos Attr sendo retornados pelo {{domxref("Document.evaluate")}}, o DOM Living Standard reintroduziu a propriedade.

+ +

Gecko mostra uma mensagem de descontinuação começando no Gecko 7.0 {{geckoRelease("7.0")}}. Esta mensagem foi removida novamente no Gecko 49.0 {{geckoRelease("49.0")}}.

+
+ +

Propriedades e métodos descontinuados

+ +

As seguintes propriedades e métodos foram descontinuados. Quando disponíveis, são substituidas adequadamente.

+ +
+
attributes
+
Esta propriedade agora sempre retorna NULL.
+
childNodes
+
Esta propriedade agora sempre retorna NULL.
+
firstChild
+
Esta propriedade agora sempre retorna NULL.
+
lastChild
+
Esta propriedade agora sempre retorna NULL.
+
nextSibling
+
Esta propriedade agora sempre retorna NULL.
+
nodeName
+
Use {{domxref("Attr.name")}} no lugar.
+
nodeType
+
Esta propriedade agora sempre retorna 2 (ATTRIBUTE_NODE).
+
nodeValue
+
Use {{domxref("Attr.value")}} no lugar.
+
ownerDocument
+
Provavelmente você nunca utilizou isto, então você não se importa que isso vai desaparecer.
+
ownerElement
+
Desde que você obtenha o objeto Attr de um {{domxref("Element")}}, você já conhece os elementos associados.
+
parentNode
+
Esta propriedade agora sempre retorna NULL.
+
previousSibling
+
Esta propriedade agora sempre retorna NULL.
+
specified
+
Esta propriedade agora sempre retorna true.
+
textContent
+
Use {{domxref("Attr.value")}} no lugar.
+
+ +

Os seguintes métodos foram reprovados:

+ +
+
appendChild()
+
Modifique o valor de {{domxref("Attr.value")}} no lugar.
+
cloneNode()
+
Provavelmente você nunca utilizou isto, então você não se importa que isso vai desaparecer.
+
createAttribute()
+
Use {{domxref("Element.setAttribute()")}} no lugar.
+
createAttributeNS()
+
Use {{domxref("Element.setAttributeNS()")}} no lugar.
+
getAttributeNode()
+
Use {{domxref("Element.getAttribute()")}} no lugar.
+
getAttributeNodeNS()
+
Use {{domxref("Element.getAttributeNS()")}} no lugar.
+
hasAttributes() {{obsolete_inline("21.0")}}
+
Este método agora sempre retorna false.
+
hasChildNodes()
+
Este método agora sempre retorna false.
+
insertBefore()
+
Modifique o valor de  {{domxref("Attr.value")}} no lugar.
+
isSupported()
+
Provavelmente você nunca utilizou isto, então você não se importa que isso vai desaparecer.
+
isEqualNode()
+
Provavelmente você nunca utilizou isto, então você não se importa que isso vai desaparecer.
+
normalize()
+
Provavelmente você nunca utilizou isto, então você não se importa que isso vai desaparecer.
+
removeAttributeNode()
+
Use {{domxref("Element.removeAttribute()")}} no lugar.
+
removeChild()
+
Modifique o valor de {{domxref("Attr.value")}} no lugar.
+
replaceChild()
+
Modifique o valor de {{domxref("Attr.value")}} no lugar.
+
setAttributeNode()
+
Use {{domxref("Element.setAttribute()")}} no lugar.
+
setAttributeNodeNS()
+
Use {{domxref("Element.setAttributeNS()")}} no lugar.
+
+ +

Especificações

+ + diff --git a/files/pt-br/web/api/attr/localname/index.html b/files/pt-br/web/api/attr/localname/index.html new file mode 100644 index 0000000000..54b7bad202 --- /dev/null +++ b/files/pt-br/web/api/attr/localname/index.html @@ -0,0 +1,133 @@ +--- +title: Attr.localName +slug: Web/API/Attr/localName +tags: + - API + - DOM + - Propriedade + - Referencia +translation_of: Web/API/Attr/localName +--- +
{{APIRef("DOM")}}
+ +

A propriedade read-only Attr.localName retorna a parte do local de um nome qualificado de elemento.

+ +
+

Antes do DOM4 essa API foi definida dentro da interface {{domxref("Node")}}.

+
+ +

Sintaxe

+ +
name = attribute.localName
+
+ +

Valor de retorno

+ +

Uma {{domxref("DOMString")}} representando a parte local do nome qualificado do atributo.

+ +

Exemplo

+ +

O seguinte exemplo mostra "id" em um diálogo de alerta.

+ +

Conteúdo HTML

+ +
<button id="example">Click me</button>
+ +

Conteúdo JavaScript

+ +
const element = document.querySelector("#example");
+element.addEventListener("click", function() {
+  const attribute = element.attributes[0];
+  alert(attribute.localName);
+});
+
+ +

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

+ +

Notas

+ +

O nome local de um atributo é a parte do nome qualificado do atributo the vem depois da vírgula. Nome qualificados são tipicamente utilizados em XML como parte do namespace(s) de um documento XML em particular.

+ +
+

Nota: No {{Gecko("1.9.2")}} e anteriores, a propriedade retorna uma versão em letras maiúsculas do nome local para o atributo DOM do HTML (oposto a atributos XHTML no DOM do XML). Em versões posteriores, em conformidade com o HTML5, a propriedade retorna no caso de armazenamento interno do DOM, que é em letras minúsculas para ambos os atributos HTML no DOM do HTML  e XHTML no DOM do XML.

+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComment
{{SpecName('DOM4', '#interface-attr', 'Attr.localName')}}{{Spec2('DOM4')}}Definição inicial
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
RecursoChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico46.0[1]{{CompatGeckoDesktop("48.0")}}[1]{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatUnknown}}{{CompatGeckoMobile("48.0")}}[1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Essa API foi disponibilizada anteriormente na API {{domxref("Node")}}.

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/audiocontext/currenttime/index.html b/files/pt-br/web/api/audiocontext/currenttime/index.html new file mode 100644 index 0000000000..71f3c9c894 --- /dev/null +++ b/files/pt-br/web/api/audiocontext/currenttime/index.html @@ -0,0 +1,114 @@ +--- +title: AudioContext.currentTime +slug: Web/API/AudioContext/currentTime +tags: + - API + - AudioContext + - Propriedade + - Referencia + - Web Audio API + - currentTime +translation_of: Web/API/BaseAudioContext/currentTime +--- +

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

+ +
+

The currentTime read-only property of the {{ domxref("AudioContext") }} interface returns a double representing an ever-increasing hardware timestamp in seconds that can be used for scheduling audio playback, visualizing timelines, etc. It starts at 0.

+
+ +

Syntax

+ +
var audioCtx = new AudioContext();
+console.log(audioCtx.currentTime);
+
+ +

Exemplo:

+ +
var AudioContext = window.AudioContext || window.webkitAudioContext;
+var audioCtx = new AudioContext();
+// Older webkit/blink browsers require a prefix
+
+...
+
+console.log(audioCtx.currentTime);
+
+ +

Especificações:

+ + + + + + + + + + + + + + +
Especificações:StatusComentario
{{SpecName('Web Audio API', '#widl-AudioContext-currentTime', 'currentTime')}}{{Spec2('Web Audio API')}} 
+ +

Compatibilidade:

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(10.0)}}{{property_prefix("webkit")}}{{CompatGeckoDesktop(25.0)}} {{CompatNo}}15.0{{property_prefix("webkit")}}
+ 22 (unprefixed)
6.0{{property_prefix("webkit")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}26.01.2{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}33.0
+ +

 

+
+ +

Veja também:

+ + diff --git a/files/pt-br/web/api/audiocontext/index.html b/files/pt-br/web/api/audiocontext/index.html new file mode 100644 index 0000000000..12357d799c --- /dev/null +++ b/files/pt-br/web/api/audiocontext/index.html @@ -0,0 +1,258 @@ +--- +title: AudioContext +slug: Web/API/AudioContext +tags: + - API + - Audio + - Interface + - Referencia + - Som + - api de áudio +translation_of: Web/API/AudioContext +--- +

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

+ +
+

A interface AudioContext  representa um grafo de processamento de áudio construído a partir de nós de áudio conectados, cada um representado por um {{domxref("AudioNode")}} Um contexto de áudio controla a criação dos nós que contém e a execução do processamento de áudio, ou decodificação. Você precisa criar um AudioContext antes de fazer qualquer outra coisa, pois tudo acontece dentro de um contexto.

+
+ +

Um AudioContextpode ser um alvo de eventos, portanto, ele implementa a interface {{domxref("EventTarget")}}.

+ +

Construtor

+ +
+
{{domxref("AudioContext.AudioContext", "AudioContext()")}}
+
Cria e retorna um novo objeto AudioContext.
+
+ +

Propriedades

+ +
+
{{domxref("AudioContext.currentTime")}} {{readonlyInline}}
+
+

Retorna um double representando um tempo cada vez maior de hardware em segundos usados ​​para agendamento. Começa em 0.

+
+
{{domxref("AudioContext.destination")}} {{readonlyInline}}
+
Retorna um {{domxref("AudioDestinationNode")}} representando o destino final de todo o áudio no contexto. Pode ser pensado como o dispositivo de renderização de áudio.
+
{{domxref("AudioContext.listener")}} {{readonlyInline}}
+
Retorna o objeto  {{domxref("AudioListener")}}, usado para especialização 3D
+
{{domxref("AudioContext.sampleRate")}} {{readonlyInline}}
+
Retorna um float representando a taxa de amostragem (em amostras por segundo) usado por todos os nós neste contexto. A taxa de amostragem de um {{domxref("AudioContext")}} não pode ser alterada.
+
{{domxref("AudioContext.state")}} {{readonlyInline}}
+
Retorna o estado atual do AudioContext.
+
{{domxref("AudioContext.mozAudioChannelType")}} {{ non-standard_inline() }} {{readonlyInline}}
+
Usado para retornar o canal de áudio que o som toca em um {{domxref("AudioContext")}} irá tocar em um dispositivo do Firefox OS.
+
+ +

Manipuladores de eventos

+ +
+
{{domxref("AudioContext.onstatechange")}}
+
Um manipulador de evento que é executado quando um evento do tipo {{event("statechange")}} dispara. +

Isso ocorre quando o estado AudioContext muda, devido ao chamado de um dos métodos de mudança de estado ({{domxref("AudioContext.suspend")}}, {{domxref("AudioContext.resume")}}, or {{domxref("AudioContext.close")}}).

+
+
+ +

Métodos

+ +

Também implementa métodos a partir da interface {{domxref("EventTarget")}}.

+ +
+
{{domxref("AudioContext.close()")}}
+
+

Fecha o contexto de áudio, liberando todos os recursos de áudio do sistema que ele usa.

+
+
{{domxref("AudioContext.createBuffer()")}}
+
Cria um novo, objeto  {{ domxref("AudioBuffer") }} vázio, que pode ser preenchido por dados e reproduzido através de um {{ domxref("AudioBufferSourceNode") }}.
+
{{domxref("AudioContext.createBufferSource()")}}
+
Cria um {{domxref("AudioBufferSourceNode")}}, que pode ser usado para reproduzir e manipular dados de audio contidos dentro de um objeto {{ domxref("AudioBuffer") }}. {{ domxref("AudioBuffer") }} são criados usando {{domxref("AudioContext.createBuffer")}} ou retornado por {{domxref("AudioContext.decodeAudioData")}} quando decodifica com sucesso uma faixa de áudio.
+
{{domxref("AudioContext.createMediaElementSource()")}}
+
Cria um {{domxref("MediaElementAudioSourceNode")}} associado com um {{domxref("HTMLMediaElement")}}. Isso pode ser usado para reproduzir e manipular o audio This can be used to play and manipulate audio dos elementos  {{HTMLElement("video")}} ou {{HTMLElement("audio")}}.
+
{{domxref("AudioContext.createMediaStreamSource()")}}
+
Cria um {{domxref("MediaStreamAudioSourceNode")}} associado com um {{domxref("MediaStream")}} um fluxo (stream) de áudio que pode vir do microfone local do computador ou de outras fontes.
+
{{domxref("AudioContext.createMediaStreamDestination()")}}
+
Cria um {{domxref("MediaStreamAudioDestinationNode")}} associado com um {{domxref("MediaStream")}} representando um fluxo (stream) de audio que pode ser armazenado em um arquivo local ou enviados para outro computador.
+
{{domxref("AudioContext.createScriptProcessor()")}}
+
Cria um a {{domxref("ScriptProcessorNode")}}, que pode ser usado para processamento de áudio direto via JavaScript.
+
{{domxref("AudioContext.createStereoPanner()")}}
+
Cria um {{domxref("StereoPannerNode")}}, que pode ser usado para aplicar uma panorâmica estéreo para uma fonte de áudio.
+
{{domxref("AudioContext.createAnalyser()")}}
+
Creates an {{domxref("AnalyserNode")}}, which can be used to expose audio time and frequency data and for example to create data visualisations.
+
{{domxref("AudioContext.createBiquadFilter()")}}
+
Cria um {{domxref ("BiquadFilterNode")}}, que representa um filtro de segunda ordem configurável como vários tipos de filtros comuns diferentes: high-pass, low-pass, band-pass, etc.
+
{{domxref("AudioContext.createChannelMerger()")}}
+
Cria um {{domxref ("ChannelMergerNode")}}, que é usado para combinar canais de múltiplos fluxos de áudio em um único fluxo de áudio.
+
{{domxref("AudioContext.createChannelSplitter()")}}
+
Cria um {{domxref ("ChannelSplitterNode")}}, que é usado para acessar os canais individuais de um fluxo de áudio e processá-los separadamente.
+
{{domxref("AudioContext.createConvolver()")}}
+
Cria um {{domxref ("ConvolverNode")}}, que pode ser usado para aplicar efeitos de convolução ao seu gráfico de áudio, por exemplo, um efeito de reverberação.
+
{{domxref("AudioContext.createDelay()")}}
+
+

Cria um {{domxref ("DelayNode")}}, que é usado para atrasar o sinal de áudio recebido por uma certa quantia. Este nó também é útil para criar loops de feedback em um gráfico de API de Web Audio.

+
+
{{domxref("AudioContext.createDynamicsCompressor()")}}
+
Cria um {{domxref("DynamicsCompressorNode")}}, que pode ser usada para aplicar compressão acústica para um sínal de áudio.
+
{{domxref("AudioContext.createGain()")}}
+
Cria um {{domxref ("GainNode")}}, que pode ser usado para controlar o volume total do gráfico de áudio.
+
{{domxref("AudioContext.createIIRFilter()")}}
+
Cria um {{domxref ("IIRFilterNode")}}, que representa um filtro de segunda ordem configurável como vários tipos de filtros comuns diferentes.
+
{{domxref("AudioContext.createOscillator()")}}
+
Cria um {{domxref ("OscillatorNode")}}, uma fonte que representa uma forma de onda periódica. Isso basicamente gera um tom.
+
{{domxref("AudioContext.createPanner()")}}
+
Cria um {{domxref ("PannerNode")}}, que é usado para spatializar um fluxo de áudio recebido no espaço 3D.
+
{{domxref("AudioContext.createPeriodicWave()")}}
+
Cria um {{domxref ("PeriodicWave")}}, usado para definir uma forma de onda periódica que pode ser usada para determinar a saída de um {{domxref ("OscillatorNode")}}.
+
{{domxref("AudioContext.createWaveShaper()")}}
+
Cria um {{domxref ("WaveShaperNode")}}, que é usado para implementar efeitos de distorção não-lineares.
+
{{domxref("AudioContext.createAudioWorker()")}}
+
+

Cria um {{domxref ("AudioWorkerNode")}}, que pode interagir com um segmento de trabalho da Web para gerar, processar ou analisar o áudio diretamente. Isso foi adicionado à especificação em 29 de agosto de 2014, e ainda não foi implementado em nenhum navegador.

+
+
{{domxref("AudioContext.decodeAudioData()")}}
+
Decodifica assincronamente dados de arquivos de áudio contidos em {{domxref("ArrayBuffer")}}. Nesse caso, o ArrayBuffer geralmente é carregado a partir de um atributo de resposta {{domxref("XMLHttpRequest")}}'s definir o responseType para arraybuffer. Esse método funciona apenas em arquivos completos, não fragmentos de arquivos de áudio.
+
{{domxref("AudioContext.resume()")}}
+
Retoma a progressão do tempo em um contexto de áudio que anteriormente foi suspenso.
+
{{domxref("AudioContext.suspend()")}}
+
Suspende a progressão do tempo no contexto de áudio, interrompendo temporariamente o acesso ao hardware de áudio e reduzindo o uso da CPU / bateria no processo.
+
+ +

Métodos obsoletos

+ +
+
{{domxref("AudioContext.createJavaScriptNode()")}}
+
Cria um {{domxref("JavaScriptNode")}}, usado para para processamento de áudio direto via JavaScript. Este método é obsoleto e foi substituído por {{domxref("AudioContext.createScriptProcessor()")}}.
+
{{domxref("AudioContext.createWaveTable()")}}
+
Cria um {{domxref ("WaveTableNode")}}, usado para definir uma forma de onda periódica. Este método é obsoleto e foi substituído por {{domxref ("AudioContext.createPeriodicWave ()")}}.
+
+ +

Exemplos

+ +

Declaração básica de contexto de áudio:

+ +
var audioCtx = new AudioContext();
+ +

Cruzar a variante do navegador:

+ +
var AudioContext = window.AudioContext || window.webkitAudioContext;
+var audioCtx = new AudioContext();
+
+var oscillatorNode = audioCtx.createOscillator();
+var gainNode = audioCtx.createGain();
+var finish = audioCtx.destination;
+// etc.
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('Web Audio API', '#the-audiocontext-interface', 'AudioContext')}}{{Spec2('Web Audio API')}}
+ +

Compatibilidade de navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(10.0)}}{{property_prefix("webkit")}}
+ 35
{{CompatGeckoDesktop(25.0)}} {{CompatNo}}15.0{{property_prefix("webkit")}}
+ 22
6.0{{property_prefix("webkit")}}
createStereoPanner(){{CompatChrome(42.0)}}{{CompatGeckoDesktop(37.0)}} {{CompatNo}}{{CompatNo}}{{CompatNo}}
onstatechange, state, suspend(), resume(){{CompatVersionUnknown}}{{CompatGeckoDesktop(40.0)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatGeckoDesktop(37.0)}} 2.2{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}
createStereoPanner(){{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}
onstatechange, state, suspend(), resume(){{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/audionode/index.html b/files/pt-br/web/api/audionode/index.html new file mode 100644 index 0000000000..8660afb978 --- /dev/null +++ b/files/pt-br/web/api/audionode/index.html @@ -0,0 +1,191 @@ +--- +title: AudioNode +slug: Web/API/AudioNode +translation_of: Web/API/AudioNode +--- +

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

+ +

A interface AudioNode é uma interface genérica para representar um módulo de processamento como uma fonte de áudio (ex. um elemento HTML {{HTMLElement("audio")}} ou {{HTMLElement("video")}} , um {{domxref("OscillatorNode")}}, etc.), um destino do áudio, um módulo intermediário de processamento (ex. um filtro como {{domxref("BiquadFilterNode")}} ou {{domxref("ConvolverNode")}}), ou um controle de volume (como o {{domxref("GainNode")}}).

+ +

AudioNodes participating in an AudioContext create a audio routing graph.

+ +

Um AudioNode tem entradas (inputs) e saídas (outputs), cada uma delas com uma determinada quantidade de canais. Um AudioNode sem nenhuma entrada e uma ou múltiplas saídas é chamado de 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(AudioNode)")}}
+
Allows us to connect one output of this node to one input of another node.
+
{{domxref("AudioNode.connect(AudioParam)")}}
+
Allows us to connect one output of this node to one input of an audio parameter.
+
{{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}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(10.0)}}{{property_prefix("webkit")}}{{CompatGeckoDesktop(25.0)}}{{CompatNo}}15.0{{property_prefix("webkit")}}
+ 22 (unprefixed)
{{CompatVersionUnknown}}
channelCount channelCountMode{{CompatVersionUnknown}} {{property_prefix("webkit")}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}
connect(AudioParam){{CompatVersionUnknown}} {{property_prefix("webkit")}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatUnknown}}25.01.2{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
channelCount
+ channelCountMode
{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
connect(AudioParam){{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

See also

+ + diff --git a/files/pt-br/web/api/background_tasks_api/index.html b/files/pt-br/web/api/background_tasks_api/index.html new file mode 100644 index 0000000000..e5973e9400 --- /dev/null +++ b/files/pt-br/web/api/background_tasks_api/index.html @@ -0,0 +1,509 @@ +--- +title: Background Tasks API +slug: Web/API/Background_Tasks_API +translation_of: Web/API/Background_Tasks_API +--- +
{{DefaultAPISidebar("Tarefas em segundo plano")}}{{draft}}
+ +

The Cooperative Scheduling of Background Tasks API (also referred to as the Background Tasks API or simply the requestIdleCallback() API) provides the ability to queue tasks to be executed automatically by the user agent when it determines that there is free time to do so.

+ +

Conceitos e uso

+ +

The main thread of a Web browser is centered around its event loop. This code draws any pending updates to the {{domxref("Document")}} currently being displayed, runs any JavaScript code the page needs to run, accepts events from input devices, and dispatches those events to the elements that should receive them. In addition, the event loop handles interactions with the operating system, updates to the browser's own user interface, and so forth. It's an extremely busy chunk of code, and your main JavaScript code may run right inside this thread along with all of this. Certainly most if not all code that is capable of making changes to the DOM is running in the main thread, since it's common for user interface changes to only be available to the main thread.

+ +

Because event handling and screen updates are two of the most obvious ways users notice performance issues, it's important for your code to be a good citizen of the Web and help to prevent stalls in the execution of the event loop. In the past, there's been no way to do this reliably other than by writing code that's as efficient as possible and by offloading as much work as possible to workers. {{domxref("Window.requestIdleCallback()")}} makes it possible to become actively engaged in helping to ensure that the browser's event loop runs smoothly, by allowing the browser to tell your code how much time it can safely use without causing the system to lag. If you stay within the limit given, you can make the user's experience much better.

+ +

Getting the most out of idle callbacks

+ +

Because idle callbacks are intended to give your code a way to cooperate with the event loop to ensure that the system is utilized to its full potential without over-tasking it, resulting in lag or other performance problems, you should be thoughtful about how you go about using them.

+ + + +

Falling back to setTimeout

+ +

Because the Background Tasks API is fairly new, your code may need to be able to work on browsers that don't yet support it. You can do so with a simple shim that uses {{domxref("WindowTimers.setTimeout()", "setTimeout()")}} as a fallback option. This isn't a {{Glossary("polyfill")}}, since it's not functionally identical; setTimeout() doesn't let you make use of idle periods, but instead runs your code when possible, leaving us to do the best we can to avoid causing the user to experience performance lag.

+ +
window.requestIdleCallback = window.requestIdleCallback || function(handler) {
+  let startTime = Date.now();
+
+  return setTimeout(function() {
+    handler({
+      didTimeout: false,
+      timeRemaining: function() {
+        return Math.max(0, 50.0 - (Date.now() - startTime));
+      }
+    });
+  }, 1);
+}
+ +

If {{domxref("Window.requestIdleCallback", "window.requestIdleCallback")}} is undefined, we create it here. The function begins by recording the time at which our implementation was called. We'll be using that to compute the value returned by our shim for {{domxref("IdleDeadline.timeRemaining()", "timeRemaining()")}}.

+ +

Then we call {{domxref("WindowTimers.setTimeout", "setTimeout()")}}, passing into it a function which runs the callback passed into our implementation of requestIdleCallback(). The callback is passed an object which conforms to {{domxref("IdleDeadline")}}, with {{domxref("IdleDeadline.didTimeout", "didTimeout")}} set to false and a {{domxref("IdleDeadline.timeRemaining", "timeRemaining()")}} method which is implemented to give the callback 50 milliseconds of time to begin with. Each time timeRemaining() is called, it subtracts the elapsed time from the original 50 milliseconds to determine the amount of time left.

+ +

As a result, while our shim doesn't constrain itself to the amount of idle time left in the current event loop pass like the true requestIdleCallback(), it does at least limit the callback to no more than 50 milliseconds of run time per pass.

+ +

The implementation of our shim for {{domxref("Window.cancelIdleCallback", "cancelIdleCallback()")}} is much simpler:

+ +
window.cancelIdleCallback = window.cancelIdleCallback || function(id) {
+  clearTimeout(id);
+}
+ +

If cancelIdleCallback() isn't defined, this creates one which simply passes the specified callback ID through to {{domxref("WindowTimers.clearTimeout", "clearTimeout()")}}.

+ +

Now your code will work even on browsers that don't support the Background Tasks API, albeit not as efficiently.

+ +

Interfaces

+ +

The Background Tasks API adds only one new interface:

+ +
+
{{domxref("IdleDeadline")}}
+
An object of this type is passed to the idle callback to provide an estimate of how long the idle period is expected to last, as well as whether or not the callback is running because its timeout period has expired.
+
+ +

The {{domxref("Window")}} interface is also augmented by this API to offer the new {{domxref("window.requestIdleCallback", "requestIdleCallback()")}} and {{domxref("window.cancelIdleCallback", "cancelIdleCallback()")}} methods.

+ +

Example

+ +

In this example, we'll take a look at how you can use {{domxref("window.requestIdleCallback", "requestIdleCallback()")}} to run time-consuming, low-priority tasks during time the browser would otherwise be idle. In addition, this example demonstrates how to schedule updates to the document content using {{domxref("window.requestAnimationFrame", "requestAnimationFrame()")}}.

+ +

Below you'll find only the HTML and JavaScript for this example. The CSS is not shown, since it's not particularly crucial to understanding this functionality.

+ +

HTML content

+ +

In order to be oriented about what we're trying to accomplish, let's have a look at the HTML. This establishes a box (ID "Container") that's used to present the progress of an operation (because you never know how long decoding "quantum filament tachyon emissions" will take, after all) as well as a second main box (with the ID "logBox"), which is used to display textual output.

+ +
<p>
+  Demonstration of using <a href="https://developer.mozilla.org/en-US/docs/Web/API/Background_Tasks_API">
+  cooperatively scheduled background tasks</a> using the <code>requestIdleCallback()</code>
+  method.
+</p>
+
+<div class="container">
+  <div class="label">Decoding quantum filament tachyon emissions...</div>
+  <progress id="progress" value="0"></progress>
+  <div class="button" id="startButton">
+    Start
+  </div>
+  <div class="label counter">
+    Task <span id="currentTaskNumber">0</span> of <span id="totalTaskCount">0</span>
+  </div>
+</div>
+
+<div class="logBox">
+  <div class="logHeader">
+    Log
+  </div>
+  <div id="log">
+  </div>
+</div>
+ +

The progress box uses a {{HTMLElement("progress")}} element to show the progress, along with a label with sections that are changed to present numeric information about the progress. In addition, there's a "Start" button (creatively given the ID "startButton"), which the user will use to start the data processing.

+ + + +

JavaScript content

+ +

Now that the document structure is defined, construct the JavaScript code that will do the work. The goal: to be able to add requests to call functions to a queue, with an idle callback that runs those functions whenever the system is idle for long enough a time to make progress.

+ +

Declaração de variáveis

+ +
let taskList = [];
+let totalTaskCount = 0;
+let currentTaskNumber = 0;
+let taskHandle = null;
+
+ +

These variables are used to manage the list of tasks that are waiting to be performed, as well as status information about the task queue and its execution:

+ + + +
let totalTaskCountElem = document.getElementById("totalTaskCount");
+let currentTaskNumberElem = document.getElementById("currentTaskNumber");
+let progressBarElem = document.getElementById("progress");
+let startButtonElem = document.getElementById("startButton");
+let logElem = document.getElementById("log");
+
+ +

Next we have variables which reference the DOM elements we need to interact with. These elements are:

+ + + +
let logFragment = null;
+let statusRefreshScheduled = false;
+
+ +

Finally, we set up a couple of variables for other items:

+ + + + + +

Gerenciando a lista de tarefas

+ +

Next, let's look at the way we manage the tasks that need to be performed. We're going to do this by creating a FIFO queue of tasks, which we'll run as time allows during the idle callback period.

+ +
Enqueueing tasks
+ +

First, we need a function that enqueues tasks for future execution. That function, enqueueTask(), looks like this:

+ +
function enqueueTask(taskHandler, taskData) {
+  taskList.push({
+    handler: taskHandler,
+    data: taskData
+  });
+
+  totalTaskCount++;
+
+  if (!taskHandle) {
+    taskHandle = requestIdleCallback(runTaskQueue, { timeout: 1000 });
+  }
+
+  scheduleStatusRefresh();
+}
+
+ +

enqueueTask() accepts as input two parameters:

+ + + +

To enqueue the task, we push an object onto the taskList array; the object contains the taskHandler and taskData values under the names handler and data, respectively, then increment totalTaskCount, which reflects the total number of tasks which have ever been enqueued (we don't decrement it when tasks are removed from the queue).

+ +

Next, we check to see if we already have an idle callback created; if taskHandle is 0, we know there isn't an idle callback yet, so we call {{domxref("Window.requestIdleCallback", "requestIdleCallback()")}} to create one. It's configured to call a function called runTaskQueue(), which we'll look at shortly, and with a timeout of 1 second, so that it will be run at least once per second even if there isn't any actual idle time available.

+ +
Running tasks
+ +

Our idle callback handler, runTaskQueue(), gets called when the browser determines there's enough idle time available to let us do some work or our timeout of one second expires. This function's job is to run our enqueued tasks.

+ +
function runTaskQueue(deadline) {
+  while ((deadline.timeRemaining() > 0 || deadline.didTimeout) && taskList.length) {
+    let task = taskList.shift();
+    currentTaskNumber++;
+
+    task.handler(task.data);
+    scheduleStatusRefresh();
+  }
+
+  if (taskList.length) {
+    taskHandle = requestIdleCallback(runTaskQueue, { timeout: 1000} );
+  } else {
+    taskHandle = 0;
+  }
+}
+
+ +

runTaskQueue()'s core is a loop which continues as long as there's time left (as determined by checking {{domxref("IdleDeadline.timeRemaining", "deadline.timeRemaining")}}) to be sure it's more than 0 or if the timeout limit was reached ({{domxref("IdleDeadline.didTimeout", "deadline.didTimeout")}} is true), and as long as there are tasks in the task list.

+ +

For each task in the queue that we have time to execute, we do the following:

+ +
    +
  1. We remove the task object from the queue.
  2. +
  3. We increment currentTaskNumber to track how many tasks we've executed.
  4. +
  5. We call the task's handler, task.handler, passing into it the task's data object (task.data).
  6. +
  7. We call a function, scheduleStatusRefresh(), to handle scheduling a screen update to reflect changes to our progress.
  8. +
+ +

When time runs out, if there are still tasks left in the list, we call {{domxref("Window.requestIdleCallback", "requestIdleCallback()")}} again so that we can continue to process the tasks the next time there's idle time available. If the queue is empty, we set taskHandle to 0 to indicate that we don't have a callback scheduled. That way, we'll know to request a callback next time enqueueTask() is called.

+ +

Updating the status display

+ +

One thing we want to be able to do is update our document with log output and progress information. However, you can't safely change the DOM from within an idle callback. Instead, we'll use {{domxref("Window.requestAnimationFrame", "requestAnimationFrame()")}} to ask the browser to call us when it's safe to update the display.

+ +
Scheduling display updates
+ +

DOM changes are scheduled by calling the scheduleStatusRefresh() function.

+ +
function scheduleStatusRefresh() {
+    if (!statusRefreshScheduled) {
+      requestAnimationFrame(updateDisplay);
+      statusRefreshScheduled = true;
+  }
+}
+
+ +

This is a simple function. It checks to see if we've already scheduled a display refresh by checking the value of statusRefreshScheduled. If it's false, we call {{domxref("Window.requestAnimationFrame", "requestAnimationFrame()")}} to schedule a refresh, providing the updateDisplay() function to be called to handle that work.

+ +
Updating the display
+ +

The updateDisplay() function is responsible for drawing the contents of the progress box and the log. It's called by the browser when the DOM is in a safe condition for us to apply changes during the process of rendering the next frame.

+ +
function updateDisplay() {
+  let scrolledToEnd = logElem.scrollHeight - logElem.clientHeight <= logElem.scrollTop + 1;
+
+  if (totalTaskCount) {
+    if (progressBarElem.max != totalTaskCount) {
+      totalTaskCountElem.textContent = totalTaskCount;
+      progressBarElem.max = totalTaskCount;
+    }
+
+    if (progressBarElem.value != currentTaskNumber) {
+      currentTaskNumberElem.textContent = currentTaskNumber;
+      progressBarElem.value = currentTaskNumber;
+    }
+  }
+
+  if (logFragment) {
+    logElem.appendChild(logFragment);
+    logFragment = null;
+  }
+
+  if (scrolledToEnd) {
+      logElem.scrollTop = logElem.scrollHeight - logElem.clientHeight;
+  }
+
+  statusRefreshScheduled = false;
+}
+ +

First, scrolledToEnd is set to true if the text in the log is scrolled to the bottom; otherwise it's set to false. We'll use that to determine if we should update the scroll position to ensure that the log stays at the end when we're done adding content to it.

+ +

Next, we update the progress and status information if any tasks have been enqueued.

+ +
    +
  1. If the current maximum value of the progress bar is different from the current total number of enqueued tasks (totalTaskCount), then we update the contents of the displayed total number of tasks (totalTaskCountElem) and the maximum value of the progress bar, so that it scales properly.
  2. +
  3. We do the same thing with the number of tasks processed so far; if progressBarElem.value is different from the task number currently being processed (currentTaskNumber), then we update the displayed value of the currently-being-processed task and the current value of the progress bar.
  4. +
+ +

Then, if there's text waiting to be added to the log (that is, if logFragment isn't null), we append it to the log element using {{domxref("Node.appendChild", "Element.appendChild()")}} and set logFragment to null so we don't add it again.

+ +

If the log was scrolled to the end when we started, we make sure it still is. Then we set statusRefreshScheduled to false to indicate that we've handled the refresh and that it's safe to request a new one.

+ +

Adding text to the log

+ +

The log() function adds the specified text to the log. Since we don't know at the time log() is called whether or not it's safe to immediately touch the DOM, we will cache the log text until it's safe to update. Above, in the code for updateDisplay(), you can find the code that actually adds the logged text to the log element when the animation frame is being updated.

+ +
function log(text) {
+  if (!logFragment) {
+      logFragment = document.createDocumentFragment();
+  }
+
+  let el = document.createElement("div");
+  el.innerHTML = text;
+  logFragment.appendChild(el);
+}
+
+ +

First, we create a {{domxref("DocumentFragment")}} object named logFragment if one doesn't currently exist. This element is a pseudo-DOM into which we can insert elements without immediately changing the main DOM itself.

+ +

We then create a new {{HTMLElement("div")}} element and set its contents to match the input text. Then we append the new element to the end of the pseudo-DOM in logFragment. logFragment will accumulate log entries until the next time updateDisplay() is called because the DOM for the changes.

+ +

Running tasks

+ +

Now that we've got the task management and display maintenance code done, we can actually start setting up code to run tasks that get work done.

+ +

The task handler

+ +

The function we'll be using as our task handler—that is, the function that will be used as the value of the task object's handler property—is logTaskHandler(). It's a simple function that outputs a bunch of stuff to the log for each task. In your own application, you'd replace this code with whatever task it is you wish to perform during idle time. Just remember that anything you want to do that changes the DOM needs to be handled through {{domxref("Window.requestAnimationFrame", "requestAnimationFrame()")}}.

+ +
function logTaskHandler(data) {
+  log("<strong>Running task #" + currentTaskNumber + "</strong>");
+
+  for (i=0; i<data.count; i+=1) {
+    log((i+1).toString() + ". " + data.text);
+  }
+}
+
+ +

The main program

+ +

Everything is triggered when the user clicks the Start button, which causes the decodeTechnoStuff() function to be called.

+ + + +
function decodeTechnoStuff() {
+  totalTaskCount = 0;
+  currentTaskNumber = 0;
+  updateDisplay();
+
+  let n = getRandomIntInclusive(100, 200);
+
+  for (i=0; i<n; i++) {
+    let taskData = {
+      count: getRandomIntInclusive(75, 150),
+      text: "This text is from task number " + (i+1).toString() + " of " + n
+    };
+
+    enqueueTask(logTaskHandler, taskData);
+  }
+}
+
+document.getElementById("startButton").addEventListener("click", decodeTechnoStuff, false);
+ +

decodeTechnoStuff() starts by zeroing the values of totalTaskCount (the number of tasks added to the queue so far) and currentTaskNumber (the task currently being run), and then calls updateDisplay() to reset the display to its "nothing's happened yet" state.

+ +

This example will create a random number of tasks (between 100 and 200 of them). To do so, we use the getRandomIntInclusive() function that's provided as an example in the documentation for {{jsxref("Math.random()")}} to get the number of tasks to create.

+ +

Then we start a loop to create the actual tasks. For each task, we create an object, taskData, which includes two properties:

+ + + +

Each task is then enqueued by calling enqueueTask(), passing in logTaskHandler() as the handler function and the taskData object as the object to pass into the function when it's called.

+ +
+
+ +

Result

+ +

Below is the actual functioning result of the code above. Try it out, play with it in your browser's developer tools, and experiment with using it in your own code.

+ +

{{ EmbedLiveSample('Example', 600, 700) }}

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Background Tasks")}}{{Spec2("Background Tasks")}}
+ +

Browser compatibility

+ +
+ + +

{{Compat("api.Window.requestIdleCallback")}}

+
+ +

See also

+ + diff --git a/files/pt-br/web/api/batterymanager/charging/index.html b/files/pt-br/web/api/batterymanager/charging/index.html new file mode 100644 index 0000000000..3a079ebc11 --- /dev/null +++ b/files/pt-br/web/api/batterymanager/charging/index.html @@ -0,0 +1,33 @@ +--- +title: BatteryManager.charging +slug: Web/API/BatteryManager/charging +tags: + - API + - Battery API + - Propriedade +translation_of: Web/API/BatteryManager/charging +--- +

{{APIRef("Battery API")}}

+ +

Um valor Booleano que indica se a bateria está sendo ou não carregada no momento.

+ +

Sintaxe

+ +
var charging = navigator.battery.charging
+ +

No retorno, charging indica se a bateria está sendo carregada no momento; se a bateria está carregando (ou se não há bateria), este valor é  true. Caso contrário, o valor é false.

+ +

Especificações

+ +

{{page("/pt-BR/docs/Web/API/BatteryManager","Specifications")}}

+ +

Compatibilidade entre navegadores

+ +

{{page("/pt-BR/docs/Web/API/BatteryManager","Browser_compatibility")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/batterymanager/chargingtime/index.html b/files/pt-br/web/api/batterymanager/chargingtime/index.html new file mode 100644 index 0000000000..3a02666207 --- /dev/null +++ b/files/pt-br/web/api/batterymanager/chargingtime/index.html @@ -0,0 +1,34 @@ +--- +title: BatteryManager.chargingTime +slug: Web/API/BatteryManager/chargingTime +tags: + - API + - Battery API + - Propriedade + - Referencia +translation_of: Web/API/BatteryManager/chargingTime +--- +

{{APIRef("Battery API")}}

+ +

Indica a quantidade de tempo, em segundos, que resta até que a bateria esteja totalmente carregada.

+ +

Sintaxe

+ +
var time = navigator.battery.chargingTime
+ +

No retorno, time é o tempo restante em segundos até que a bateria esteja totalmente carregada, ou 0 se a bateria já estiver com sua carga completa. Se a bateria estiver descarregando (ou se o sistema não é capaz de derminar o tempo restante para o carregamento), este valor é Infinity.

+ +

Especificações

+ +

{{page("/pt-BR/docs/Web/API/BatteryManager","Specifications")}}

+ +

Compatibilidade entre navegadores

+ +

{{page("/pt-BR/docs/Web/API/BatteryManager","Browser_compatibility")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/batterymanager/dischargingtime/index.html b/files/pt-br/web/api/batterymanager/dischargingtime/index.html new file mode 100644 index 0000000000..e5ca6b486c --- /dev/null +++ b/files/pt-br/web/api/batterymanager/dischargingtime/index.html @@ -0,0 +1,34 @@ +--- +title: BatteryManager.dischargingTime +slug: Web/API/BatteryManager/dischargingTime +tags: + - API + - Battery API + - Propriedade + - Referencia +translation_of: Web/API/BatteryManager/dischargingTime +--- +

{{APIRef("Battery API")}}

+ +

Indica a quantidade de tempo, em segundos, que restam até a bateria estar totalmente descarregada.

+ +

Sintaxe

+ +
var time = navigator.battery.dischargingTime
+ +

No retorno, time é o tempo restante em segundos até que a bateria esteja totamente descarregada e o sistema suspenda. Este valor é Infinity se a bateria estiver carregando, ao invés de descarregando, ou se o sistema não for capaz de determinar o tempo restante de carregamento (ou ainda se não existir uma bateria disponível).

+ +

Especificações

+ +

{{page("/pt-BR/docs/Web/API/BatteryManager","Specifications")}}

+ +

Compatibilidade entre navegadores

+ +

{{page("/pt-BR/docs/Web/API/BatteryManager","Browser_compatibility")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/batterymanager/index.html b/files/pt-br/web/api/batterymanager/index.html new file mode 100644 index 0000000000..1febd0d799 --- /dev/null +++ b/files/pt-br/web/api/batterymanager/index.html @@ -0,0 +1,140 @@ +--- +title: BatteryManager +slug: Web/API/BatteryManager +tags: + - API + - Battery API + - Referencia +translation_of: Web/API/BatteryManager +--- +

{{APIRef("Battery API")}}

+ +

Resumo

+ +

A interface BatteryManager fornece maneiras de obter informações sobre o nível de carga da bateria do sistema.

+ +

A propriedade {{domxref("Navigator.battery","navigator.battery")}} retorna uma instância da interface BatteryManager que você pode utilizar para interajir com a API de status da bateria.

+ +

Propriedades

+ +
+
{{domxref("BatteryManager.charging")}} {{ReadOnlyInline}}
+
+

Um valor Booleano que indica se a bateria está sendo carregada no momento.

+
+
{{domxref("BatteryManager.chargingTime")}} {{ReadOnlyInline}}
+
+

Um número representando o tempo restante em segundos até a bateria estar completamente carregada, ou 0 se a carga já estiver completa.

+
+
{{domxref("BatteryManager.dischargingTime")}} {{ReadOnlyInline}}
+
Um número representando o tempo restante em segundos até a bateria estar completamente descarregada e o sistema ser suspenso.
+
{{domxref("BatteryManager.level")}} {{ReadOnlyInline}}
+
Um número representando o nível de carga da bateria do sistema em uma escala de valores entre 0.0 e 1.0.
+
+ +

Eventos

+ +
+
{{domxref("BatteryManager.onchargingchange")}}
+
Tratamento para o evento {{event("chargingchange")}}; Esse evento é enviado quando o status de carregamento da bateria é atualizado.
+
{{domxref("BatteryManager.onchargingtimechange")}}
+
Tratamento para o evento {{event("chargingtimechange")}}; Esse evento é enviado quando o tempo de carregamento da bateria é atualizado.
+
{{domxref("BatteryManager.ondischargingtimechange")}}
+
Tratamento para o evento {{event("dischargingtimechange")}}; Esse evento é enviado quando o tempo de descarregamento da bateria é atualizado.
+
{{domxref("BatteryManager.onlevelchange")}}
+
Tratamento para o evento {{event("levelchange")}}; Esse evento é enviado quando a nível da bateria é atualizado.
+
+ +

Métodos

+ +

Herdado de {{domxref("EventTarget")}}:

+ +

{{page("/pt-BR/docs/Web/API/EventTarget","Métodos")}}

+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('Battery API')}}{{Spec2('Battery API')}}Especificação Inicial.
+ +

Compatibilidade entre navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{ CompatNo() }}
+ Chrome para Android: crbug.com/135863
+ Chrome OS: crbug.com/122593
{{CompatGeckoDesktop("10")}} {{ property_prefix("moz") }} [1]
+ {{CompatGeckoDesktop("16")}} (sem prefixo) [2]
{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeAndroidChrome para AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{ CompatUnknown() }}{{ CompatNo() }}{{CompatGeckoMobile("10")}} {{ property_prefix("moz") }} [1]
+ {{CompatGeckoMobile("16")}} (sem prefixo) [2]
{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +

Notas para o Gecko

+ +

[1] Desabilitado por padrão no Firefox 10.0, mas pode ser habilitado alterando a preferência dom.battery.enabled para true. A partir do Firefox 11.0, mozBattery é habilitado por padrão.

+ +

[2] A Battery API é atualmente suportada no Android, Windows e Linux com UPower instalado. O suporte para MacOS está disponível a partir do Gecko 18.0 {{geckoRelease("18.0")}};

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/batterymanager/level/index.html b/files/pt-br/web/api/batterymanager/level/index.html new file mode 100644 index 0000000000..b8d58c68c6 --- /dev/null +++ b/files/pt-br/web/api/batterymanager/level/index.html @@ -0,0 +1,34 @@ +--- +title: BatteryManager.level +slug: Web/API/BatteryManager/level +tags: + - API + - Battery API + - Propriedade + - Referencia +translation_of: Web/API/BatteryManager/level +--- +

{{APIRef("Battery API")}}

+ +

Indica o nível de carga atual da bateria como um valor entre 0.0 e 1.0.

+ +

Sintaxe

+ +
var level = navigator.battery.level
+ +

No retorno, level é um número representando o nível de carga da bateria do sistema em uma escala de valores entre 0.0 e 1.0. Um valor de 0.0 significa que a bateria está vazia e o sistema está prestes a ser suspenso. Um valor de 1.0 significa que a bateria está cheia. Um valor de 1.0 é também retornado se a implementação não é capaz de determinar o nível de carga ou se o sistema não é alimentado por bateria.

+ +

Especificações

+ +

{{page("/pt-BR/docs/Web/API/BatteryManager","Specifications")}}

+ +

Compatibilidade entre navegadores

+ +

{{page("/pt-BR/docs/Web/API/BatteryManager","Browser_compatibility")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/batterymanager/onchargingchange/index.html b/files/pt-br/web/api/batterymanager/onchargingchange/index.html new file mode 100644 index 0000000000..2a2e687801 --- /dev/null +++ b/files/pt-br/web/api/batterymanager/onchargingchange/index.html @@ -0,0 +1,35 @@ +--- +title: BatteryManager.onchargingchange +slug: Web/API/BatteryManager/onchargingchange +tags: + - API + - Battery API + - Event Handler + - Propriedade + - Referencia +translation_of: Web/API/BatteryManager/onchargingchange +--- +

{{APIRef("Battery API")}}

+ +

Especifica um event listener para receber eventos {{event("chargingchange")}}. Esses eventos ocorrem quando o estado {{domxref("BatteryManager.charging", "charging")}} (carregando) da bateria é atualizado.

+ +

Sintaxe

+ +
navigator.battery.onchargingchange = funcRef
+ +

Onde funcRef é uma função para ser chamada quando o evento {{event("chargingchange")}} ocorre.

+ +

Especificações

+ +

{{page("/pt-BR/docs/Web/API/BatteryManager","Specifications")}}

+ +

Compatibilidade entre navegadores

+ +

{{page("/pt-BR/docs/Web/API/BatteryManager","Browser_compatibility")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/batterymanager/onchargingtimechange/index.html b/files/pt-br/web/api/batterymanager/onchargingtimechange/index.html new file mode 100644 index 0000000000..8c711d75d6 --- /dev/null +++ b/files/pt-br/web/api/batterymanager/onchargingtimechange/index.html @@ -0,0 +1,35 @@ +--- +title: BatteryManager.onchargingtimechange +slug: Web/API/BatteryManager/onchargingtimechange +tags: + - API + - Battery API + - Event Handler + - Propriedade + - Referencia +translation_of: Web/API/BatteryManager/onchargingtimechange +--- +

{{APIRef("Battery API")}}

+ +

Especifica um event listener para receber eventos {{event("chargingtimechange")}}. Esses eventos ocorrem quando a propriedade {{domxref("BatteryManager.chargingTime","chargingTime")}} (tempo de carregamento) da bateria é atualizada.

+ +

Sintaxe

+ +
navigator.battery.onchargingtimechange = funcRef
+ +

Onde funcRef é uma função para ser chamada quando o evento {{event("chargingtimechange")}} ocorre.

+ +

Especificações

+ +

{{page("/pt-BR/docs/Web/API/BatteryManager","Specifications")}}

+ +

Compatibilidade entre navegadores

+ +

{{page("/pt-BR/docs/Web/API/BatteryManager","Browser_compatibility")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/batterymanager/ondischargintimechange/index.html b/files/pt-br/web/api/batterymanager/ondischargintimechange/index.html new file mode 100644 index 0000000000..4f5c402588 --- /dev/null +++ b/files/pt-br/web/api/batterymanager/ondischargintimechange/index.html @@ -0,0 +1,35 @@ +--- +title: BatteryManager.ondischargingtimechange +slug: Web/API/BatteryManager/ondischargintimechange +tags: + - API + - Battery API + - Event Handler + - Propriedade + - Referencia +translation_of: Web/API/BatteryManager/ondischargingtimechange +--- +

{{APIRef("Battery API")}}

+ +

Especifica um event listener para receber eventos {{event("dischargingtimechange")}}. Esses eventos ocorrem quando a propriedade {{domxref("BatteryManager.dischargingTime","dischargingTime")}} (tempo de descarregamento) da bateria é atualizada.

+ +

Sintaxe

+ +
navigator.battery.ondischargingtimechange = funcRef
+ +

Onde funcRef é uma função para ser chamada quando o evento {{event("dischargingtimechange")}} ocorre.

+ +

Especificações

+ +

{{page("/pt-BR/docs/Web/API/BatteryManager","Specifications")}}

+ +

Compatibilidade entre navegadores

+ +

{{page("/pt-BR/docs/Web/API/BatteryManager","Browser_compatibility")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/batterymanager/onlevelchange/index.html b/files/pt-br/web/api/batterymanager/onlevelchange/index.html new file mode 100644 index 0000000000..911d760327 --- /dev/null +++ b/files/pt-br/web/api/batterymanager/onlevelchange/index.html @@ -0,0 +1,35 @@ +--- +title: BatteryManager.onlevelchange +slug: Web/API/BatteryManager/onlevelchange +tags: + - API + - Battery API + - Event Handler + - Propriedade + - Referencia +translation_of: Web/API/BatteryManager/onlevelchange +--- +

{{APIRef("Battery API")}}

+ +

Especifica um event listener para receber eventos {{event("levelchange")}}. Esses eventos ocorrem quando o {{domxref("BatteryManager.level","level")}} (nível) da bateria é atualizado.

+ +

Sintaxe

+ +
navigator.battery.onlevelchange = funcRef
+ +

Onde funcRef é uma função para ser chamada quando o evento {{event("levelchange")}} ocorre.

+ +

Especificações

+ +

{{page("/pt-BR/docs/Web/API/BatteryManager","Specifications")}}

+ +

Compatibilidade entre navegadores

+ +

{{page("/pt-BR/docs/Web/API/BatteryManager","Browser_compatibility")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/biquadfilternode/index.html b/files/pt-br/web/api/biquadfilternode/index.html new file mode 100644 index 0000000000..c23c1eff33 --- /dev/null +++ b/files/pt-br/web/api/biquadfilternode/index.html @@ -0,0 +1,186 @@ +--- +title: BiquadFilterNode +slug: Web/API/BiquadFilterNode +tags: + - API + - BiquadFilterNode + - CompatibilidadeNavegadorCelular + - Interface + - Referencia + - Web Audio API +translation_of: Web/API/BiquadFilterNode +--- +

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

+ +
+

A interface BiquadFilterNode representa um filtro simples de ordem baixa, e é criada utilizando o método {{ domxref("AudioContext.createBiquadFilter()") }} . É o {{domxref("AudioNode")}} que pode representar diferentes tipos de filtros, dispositivo de controle de timbre, e equalizadores gráficos. Um BiquadFilterNode sempre tem exatamente uma entrada e uma saída.

+
+ + + + + + + + + + + + + + + + + + + + + + + + +
Número de entradas1
Número de saídas1
Modo de contagem de canal"max"
Contagem de canal2 (não utilizado no modo de contagem padrão)
Interpretação de canal"speakers"
+ +

Construtor

+ +
+
{{domxref("BiquadFilterNode.BiquadFilterNode", "BiquadFilterNode()")}}
+
Cria uma nova instância de um objeto do tipo BiquadFilterNode.
+
+ +

Propriedades

+ +

Herda as propriedades de seu pai, {{domxref("AudioNode")}}.

+ +
+
{{domxref("BiquadFilterNode.frequency")}}
+
É um a-rate {{domxref("AudioParam")}}, um double que representa a frequência no algoritmo de filtragem atual, medido em hertz (Hz).
+
{{domxref("BiquadFilterNode.detune")}}
+
É um  a-rate {{domxref("AudioParam")}} representando a dessintonização da frequência em cents.
+
{{domxref("BiquadFilterNode.Q")}}
+
É um a-rate {{domxref("AudioParam")}}, um double representando um Q factor, ou fator de qualidade.
+
{{domxref("BiquadFilterNode.gain")}} {{readonlyInline}}
+
É um a-rate {{domxref("AudioParam")}}, um double representando o gain utilizado no algoritmo de filtragem atual.
+
{{domxref("BiquadFilterNode.type")}}
+
É um valor string que define o tipo de algoritmo de filtragem que o nó está implementando.
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
O significado dos diferentes parâmetros de acordo com o tipo de filtro (detune tem o mesmo significado, então não está listado abaixo)
tipoDescriçãofrequênciaQganho
lowpass +

Filtro de resonância lowpass padrão de segunda ordem com 12dB/octave rolloff. Frequências abaixo do ponto de corte passam; frequências acima são atenuadas.

+
A frequência de corte.Indica o quão perto a frequência chegou em relação ao ponto de corte. Quantomaior o valor, maior será a aproximação.Não utilizado
highpassFiltro de resonância highpass padrão de segunda ordem com 12dB/octave rolloff. Frequências abaixo do ponto de corte são atenuadas; frequências acima passam.A frequência de corte.Indica o quão perto a frequência chegou em relação ao ponto de corte. Quantomaior o valor, maior será a aproximação.Não utilizado
bandpassFiltro bandpass padrão de segunda ordem. Frequências fora do dado limite de frequências são atenuadas; frequências dentro do limite passam.O centro de alcance de frequências.Controla a largura da banda de frequência. Quanto maior o valor Q, menor a frequência de banda.Não utilizado
lowshelfFiltro lowshelf padrão de segunda ordem. Frequências menores que a frequência recebem um aumento, ou uma atenuação; frequências maiores não sofrem alterações.O limite superior das frequênicas recebe um aumento ou atenuação.Não utilizadoO aumento, em dB, para ser aplicado; se negativo, ele será uma atenuação.
highshelfFiltro highshelf padrão de segunda ordem. Frequências maiores que a frequência recebem aumento ou atenuação; frequências abaixo disso não sofrem alterações.O limite inferior de frequências recebe aumento ou uma atenuação.Não utilizado +

O aumento, em dB, para ser aplicado; se negativo, ele será uma atenuação.

+
peakingFrequências dentro da faixa de frequencias  recebem aumento ou atenuação; frequências fora da faixa não sofrem alterações.O meio da faixa de frequência recebe um aumento ou uma atenuação.Controla a largura da banda de frequência. Quanto maior o valor Q, menor a frequência de banda.O aumento, em dB, para ser aplicado; se negativo, ele será uma atenuação.
notchFiltro notch padrão, também chamado de filtro band-stop ou band-rejection. É o oposto do filtro de de bandpass: frequências fora da faixa de frequências atribuída passam; frequências de dentro da faixa são atenuadas.O centro de alcance de frequências.Controla a largura da banda de frequência. Quanto maior o valor Q, menor a frequência de banda.Não utilizado
allpassFiltro allpass padrão de segunda ordem. Permite que todas as frequências passem, porém altera a relação de fase entre as diversas frequências.A frequência com o máximo group delay, ou seja, a frequência onde o centro da fase de transição ocorre.Controla o quão apurada a transição é na frequência média. Quanto maior este parâmetro, mais apurada e ampla será a transiçãoNão utilizado
+
+
+ +

Métodos

+ +

Herda os métodos de seu pai, {{domxref("AudioNode")}}.

+ +
+
{{domxref("BiquadFilterNode.getFrequencyResponse()")}}
+
A partir dos parâmetros de configuração do filtro atual, este método calcula a frequência de resposta para frequências especificadas no array de frequências.
+
+ +

Exemplo

+ +

{{page("/en-US/docs/Web/API/AudioContext.createBiquadFilter","Example")}}

+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('Web Audio API', '#the-biquadfilternode-interface', 'BiquadFilterNode')}}{{Spec2('Web Audio API')}} 
+ +

Compatibilidade dos navegadores

+ +
+ + +

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

+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/blob/blob/index.html b/files/pt-br/web/api/blob/blob/index.html new file mode 100644 index 0000000000..fbb8b121c5 --- /dev/null +++ b/files/pt-br/web/api/blob/blob/index.html @@ -0,0 +1,65 @@ +--- +title: Blob +slug: Web/API/Blob/Blob +translation_of: Web/API/Blob/Blob +--- +

{{APIRef("File API")}}

+ +

Blob()

+ +

 

+ +

Retorna um novo objeto Blob criado, cujo o conteúdo consiste na concatenação de um array de valores estabelecidos no parâmetro da função.

+ +

Syntaxe

+ +
var aBlob = new Blob( array[, options]);
+
+ +

Parâmetros

+ + + +

Exemplo

+ +
var aFileParts = ['<a id="a"><b id="b">hey!</b></a>']; // an array consisting of a single DOMString
+var oMyBlob = new Blob(aFileParts, {type : 'text/html'}); // the blob
+ +

Especificação

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

Compatibilidade com navegadores

+ + + +

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

+ +

Veja também

+ + + +

 

diff --git a/files/pt-br/web/api/blob/index.html b/files/pt-br/web/api/blob/index.html new file mode 100644 index 0000000000..f976675a1a --- /dev/null +++ b/files/pt-br/web/api/blob/index.html @@ -0,0 +1,130 @@ +--- +title: Blob +slug: Web/API/Blob +translation_of: Web/API/Blob +--- +

{{ APIRef("File API") }}

+ +

Sumário

+ +

Um objeto Blob representa um objeto do tipo arquivo, com  dados brutos imutáveis. Blobs representam dados que não estão necessariamente em um formato JavaScript nativo. A interface {{ domxref("File") }} é baseada no Blob, herdando funcionalidade blob e expandindo-o para suportar arquivos no sistema do usuário.

+ +

Para construir um Blob a partir de outro objeto ou dado não-blob , utilize o construtor {{domxref("Blob.Blob","Blob()")}}. Para criar um blob que contém um subconjunto de dados de outro blob, use o método {{domxref("Blob.slice()", "slice()")}}. Para obter um objeto Blob de um arquivo no sistema de arquivos do usuário, veja a documentação {{domxref("File")}}.

+ +

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

+ +
+

Nota: O método slice() usava inicialmente length como segundo argumento para indicar o numero de bytes a copiar no novo Blob.  Se você especificou valores de maneira que start + length excederam o tamanho do Blob de origem, o Blob retornado contém dados a partir do início do índice até o final do Blob de origem.

+
+ +
Nota:  Esteja ciente que o método slice() possui prefixos de fornecedores em alguns navegadores e versões: blob.mozSlice() para Firefox 12 e anteriores, e blob.webkitSlice() para Safari. Uma versão antiga do método slice(), sem prefixos de fornecedor, tem semântica diferente, e portanto é obsoleta. O suporta para blob.mozSlice() foi descontinuado a partir do Firefox 30.
+ +

Construtor

+ +
+
{{domxref("Blob.Blob", "Blob(blobParts[, opções])")}}
+
Retorna um novo Blob object cujo conteúdo consiste na concatenação do array de valores passados por parâmentro.
+
+ +

Propriedades

+ +
+
{{domxref("Blob.size")}} {{readonlyinline}}
+
Tamanho em bytes dos dados contidos no objeto Blob.
+
{{domxref("Blob.type")}} {{readonlyinline}}
+
Uma string que indica o MIME type dos dados no Blob. Se o tipo é desconhecido, então retorna uma string vazia.
+
+ +

Métodos

+ +
+
{{domxref("Blob.slice()", "Blob.slice([start[, end[, contentType]]])")}}
+
Retorna um novo  Blob object contendo dados em no intervalo de bytes especificado do Blob de origem.
+
+ +

Exemplos

+ +

Exemplos de uso do construtor Blob

+ +

O código a seguir:

+ +
var aFileParts = ['<a id="a"><b id="b">hey!</b></a>'];
+var oMyBlob = new Blob(aFileParts, {type : 'text/html'}); // o blob
+
+ +

equivale a:

+ +
var oBuilder = new BlobBuilder();
+var aFileParts = ['<a id="a"><b id="b">hey!</b></a>'];
+oBuilder.append(aFileParts[0]);
+var oMyBlob = oBuilder.getBlob('text/xml'); // o blob
+
+ +
+

O {{ domxref("BlobBuilder") }} oferece outra maneira para criar Blobs, mas é depreciado e não deveria mais ser usado.

+
+ +

Exemplo para criar uma URL para uma array tipada usando blob

+ +

O código a seguir:

+ +
var typedArray = GetTheTypedArraySomehow();
+var blob = new Blob([typedArray], {type: 'application/octet-binary'}); // passe um MIME-type útil aqui
+var url = URL.createObjectURL(blob);
+// url será algo do tipo: blob:d3958f5c-0777-0845-9dcf-2cb28783acaf
+// agora você pode usar a URL em qualquer contexto em que URLs regulares podem ser usadas, por exemplo: img.src, etc.
+
+ +

Exemplo de Extração de Dados de Um Blob

+ +

O único jeito de ler o conteúdo de um Blob é usando {{domxref("FileReader")}}. O código a seguir lê o conteudo de um Blob como um Array.

+ +
var reader = new FileReader();
+reader.addEventListener("loadend", function() {
+   // reader.result contém o conteúdo do blob como uma array tipada
+});
+reader.readAsArrayBuffer(blob);
+ +

Ao usar outros métodos de {{domxref("FileReader")}}, é possível ler o conteúdo de um Blob como uma string ou como uma data URL.

+ +

Especificações

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

Compatibilidade de Browser

+ + + +

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

+ +

Notas para Gecko

+ +

Anterior ao Gecko 12.0 {{ geckoRelease("12.0") }}, havia um bug que afetava o comportamento do {{ manch("slice") }}; que não funcionava para as posições start e end fora do intervalo de valores assinados como 64-bit; este bug foi corrigido para dar suporte a valores assinados como 64-bit.

+ +

Chrome Code - Disponibilidade de Escopo

+ +

No escopo JSM, Blob é disponivel sem a necessidade de nada especial.

+ +

No escopo Bootstrap, ele deve ser importado como tal:

+ +
const {Blob, Services} = Cu.import('resource://gre/modules/Services.jsm', {});
+ +

Veja Também

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

A propriedade Blob.size retorna o tamanho em bytes de {{domxref("Blob")}} ou um {{domxref("File")}}.

+ +

Syntaxe

+ +
var sizeInBytes = blob.size
+
+ +

Valor

+ +

Um número.

+ +

Exempl0

+ +
// fileInput é um HTMLInputElement: <input type="file" multiple id="myfileinput">
+var fileInput = document.getElementById("myfileinput");
+
+// files é um objeto FileList (similiar ao 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çãoStatusComentário
{{SpecName('File API', '#dfn-size', 'size')}}{{Spec2('File API')}}Definição inicial.
+ +

Compatibilidade com navegadores

+ +
+ + +

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

+
+ +

Veja também

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

O método Blob.slice() é usado para criar um novo {{domxref("Blob")}} object  contendo os dados no intervalo especificado de bytes da fonte {{domxref("Blob")}}.

+ +
Nota: Esteja ciente de que o método slice () tem prefixos de fornecedores em alguns navegadores e versões: blob.mozSlice () para Firefox 12 e anteriores e blob.webkitSlice () no Safari. Uma versão antiga do método slice (), sem prefixos de fornecedor, tinha uma semântica diferente e é obsoleta
+ +

Sintaxe

+ +
let blob = instanceOfBlob.slice([start [, end [, contentType]]]);
+ +

Parâmetros

+ +
+
start {{optional_inline}}
+
An index into the {{domxref("Blob")}} indicating the first byte to include in the new {{domxref("Blob")}}. If you specify a negative value, it's treated as an offset from the end of the string toward the beginning. For example, -10 would be the 10th from last byte in the {{domxref("Blob")}}. The default value is 0. If you specify a value for start that is larger than the size of the source {{domxref("Blob")}}, the returned {{domxref("Blob")}} has size 0 and contains no data.
+
end {{optional_inline}}
+
An index into the {{domxref("Blob")}} indicating the first byte that will *not* be included in the new {{domxref("Blob")}} (i.e. the byte exactly at this index is not included). If you specify a negative value, it's treated as an offset from the end of the string toward the beginning. For example, -10 would be the 10th from last byte in the {{domxref("Blob")}}. The default value is size.
+
contentType {{optional_inline}}
+
The content type to assign to the new {{domxref("Blob")}}; this will be the value of its type property. The default value is an empty string.
+
+ +

Return value

+ +

A new {{domxref("Blob")}} object containing the specified data from the source {{domxref("Blob")}}.

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("File API", "#dfn-slice", "Blob.slice()")}}{{Spec2("File API")}}Initial definition
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support10 {{property_prefix("webkit")}} [1]
+ 21
{{CompatVersionUnknown}}5 {{property_prefix("moz")}} [1]
+ 13 [2]
1012 [1]5.1 {{property_prefix("webkit")}} [3]
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("13.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] The slice() method had initially taken length as the second argument to indicate the number of bytes to include in the new Blob. If you specified values such that start + length exceeded the size of the source Blob, the returned Blob contained data from the start index to the end of the source Blob. That version of the slice() was implemented in Firefox 4, WebKit, and Opera 11.10. However, since that syntax is differed from Array.slice() and String.slice(), Gecko and WebKit removed support and added support for the new syntax as Blob.slice()/Blob.webkitSlice.

+ +

[2] Prior to Gecko 12.0 {{geckoRelease("12.0")}}, there was a bug that affected the behavior of Blob.slice(); it did not work for start and end positions outside the range of signed 64-bit values; it has now been fixed to support unsigned 64-bit values.

+ +

[3] This was implemented in 534.29.

+ +

See also

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

A propriedade type de um objeto Blob fornece MIME type do arquivo. Ela retorna uma string vazia se o tipo não puder ser determinado.

+ +

Syntaxe

+ +
var mimetype = instanceOfFile.type
+ +

Valor

+ +

Uma string

+ +

Exemplo

+ +
var i, fileInput, files, allowedFileTypes;
+
+// fileInput é um HTMLInputElement: <input type="file" multiple id="myfileinput">
+fileInput = document.getElementById("myfileinput");
+
+// files é um objeto FileList (similiar ao NodeList)
+files = fileInput.files;
+
+// nossa aplicação permite apenas imagens dos tipos *.png, *.jpeg and *.gif
+allowedFileTypes = ["image/png", "image/jpeg", "image/gif"];
+
+for (i = 0; i < files.length; i++) {
+  // Testa se file.type é um tipo de arquivo permitido.
+  if (allowedFileTypes.indexOf(files[i].type) > -1) {
+    // file type é um dos tipos permitidos. Código aqui.
+  }
+});
+
+ +

Especificações

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

Compatibilidade com navegadores

+ +
+ + +

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

+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/body/index.html b/files/pt-br/web/api/body/index.html new file mode 100644 index 0000000000..121e93718b --- /dev/null +++ b/files/pt-br/web/api/body/index.html @@ -0,0 +1,97 @@ +--- +title: Body +slug: Web/API/Body +tags: + - API + - BODY + - Experimental + - Fetch + - Fetch API + - Interface + - NeedsTranslation + - Reference + - TopicStub + - request +translation_of: Web/API/Body +--- +
{{ APIRef("Fetch") }}
+ +

The Body {{glossary("mixin")}} of the Fetch API represents the body of the response/request, allowing you to declare what its content type is and how it should be handled.

+ +

Body is implemented by both {{domxref("Request")}} and {{domxref("Response")}}. This provides these objects with an associated body (a stream), a used flag (initially unset), and a MIME type (initially the empty byte sequence).

+ +

Properties

+ +
+
{{domxref("Body.body")}} {{readonlyInline}}
+
A simple getter used to expose a {{domxref("ReadableStream")}} of the body contents.
+
{{domxref("Body.bodyUsed")}} {{readonlyInline}}
+
A {{jsxref("Boolean")}} that indicates whether the body has been read.
+
+ +

Methods

+ +
+
{{domxref("Body.arrayBuffer()")}}
+
Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with an {{jsxref("ArrayBuffer")}}.
+
{{domxref("Body.blob()")}}
+
Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with a {{domxref("Blob")}}.
+
{{domxref("Body.formData()")}}
+
Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with a {{domxref("FormData")}} object.
+
{{domxref("Body.json()")}}
+
Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with the result of parsing the body text as {{jsxref("JSON")}}.
+
{{domxref("Body.text()")}}
+
Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with a {{domxref("USVString")}} (text). The response is always decoded using UTF-8.
+
+ +

Examples

+ +

The example below uses a simple fetch call to grab an image and display it in an {{htmlelement("img")}} tag. You'll notice that since we are requesting an image, we need to run {{domxref("Body.blob","Body.blob()")}} ({{domxref("Response")}} implements body) to give the response its correct MIME type.

+ +

HTML Content

+ +
<img class="my-image" src="https://wikipedia.org/static/images/project-logos/frwiki-1.5x.png">
+
+ +

JS Content

+ +
const myImage = document.querySelector('.my-image');
+fetch('https://upload.wikimedia.org/wikipedia/commons/7/77/Delete_key1.jpg')
+	.then(res => res.blob())
+	.then(res => {
+		const objectURL = URL.createObjectURL(res);
+		myImage.src = objectURL;
+});
+ +

{{ EmbedLiveSample('Examples', '100%', '250px') }}

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fetch','#body-mixin','Body')}}{{Spec2('Fetch')}}
+ +

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/pt-br/web/api/body/json/index.html b/files/pt-br/web/api/body/json/index.html new file mode 100644 index 0000000000..7ee4482fe5 --- /dev/null +++ b/files/pt-br/web/api/body/json/index.html @@ -0,0 +1,89 @@ +--- +title: Body.json() +slug: Web/API/Body/json +tags: + - API + - Experimental + - Fetch + - JSON + - Referencia +translation_of: Web/API/Body/json +--- +
{{APIRef("Fetch API")}}
+ +

O método json()  do mixin {{DOMxRef("Body")}} usa uma stream do objeto {{DOMxRef("Response")}} para tratar. O método json() retorna uma Promise como resultado do processamento da stream, retornando um objeto {{JSxRef("JSON")}} em caso de sucesso.

+ +

Syntaxe

+ +
response.json().then(data => {
+  // do something with your data
+});
+ +

Parâmetros

+ +

Nenhum.

+ +

Retorno

+ +

Uma {{jsxref("Promise")}} que retorna um objeto Javascript no método resolve(). Pode ser qualquer tipo que pode ser representado com JSON — objeto, array, string, numeral...

+ +

Exemplo

+ +

Em nosso exemplo de fetch em json (teste aqui a busca em json com fetch), nós criamos uma nova requisição usando o constructor de {{DOMxRef("Request.Request", "Request()")}}, e em seguimos a usamos para buscar um arquivo .json. Quando o fetch é bem-sucedido, nós lemos e tratamos a stream com o método json(), lê os valores em forma de objeto retornados como esperado e inserimos na lista para exibir os dados dos produtos.

+ +
const myList = document.querySelector('ul');
+const myRequest = new Request('products.json');
+
+fetch(myRequest)
+  .then(response => response.json())
+  .then(data => {
+    for (const product of data.products) {
+      let listItem = document.createElement('li');
+      listItem.appendChild(
+        document.createElement('strong')
+      ).textContent = product.Name;
+      listItem.append(
+        ` can be found in ${
+          product.Location
+        }. Cost: `
+      );
+      listItem.appendChild(
+        document.createElement('strong')
+      ).textContent = `£${product.Price}`;
+      myList.appendChild(listItem);
+    }
+  })
+  .catch(console.error);
+ +

Especificações

+ + + + + + + + + + + + + + + + +
SpecificaçõesStatusComentários
{{SpecName("Fetch", "#dom-body-json", "Body.json()")}}{{Spec2("Fetch")}}Definição Inicial
+ +

Compatibilidade de Navegador

+ + + +

{{Compat("api.Body.json")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/broadcastchannel/index.html b/files/pt-br/web/api/broadcastchannel/index.html new file mode 100644 index 0000000000..e15c5f23a4 --- /dev/null +++ b/files/pt-br/web/api/broadcastchannel/index.html @@ -0,0 +1,81 @@ +--- +title: BroadcastChannel +slug: Web/API/BroadcastChannel +tags: + - API + - Broadcast Channel API + - Experimental + - HTML API + - Interface + - Reference +translation_of: Web/API/BroadcastChannel +--- +

{{APIRef("Broadcast Channel API")}}

+ +

A interface BroadcastChannel (canal de transmissão) representa um canal com um nome em que qualquer {{glossary("browsing context")}} (contexto de navegação) de uma determinada {{glossary("origin")}} (origem) pode assinar. Permite a comunicação entre diferentes documentos (em diferentes janelas, abas, frames ou iframes) da mesma origin. As mensagens são transmitidas através de um evento {{event("message")}} acionado em todos objetos do tipo BroadcastChannel que estão ouvindo o canal.

+ +

{{AvailableInWorkers}}

+ +

Construtor

+ +
+
{{domxref("BroadcastChannel.BroadcastChannel", "BroadcastChannel()")}}
+
Cria um objeto, no qual faz o vínculo com um canal nomeado.
+
+ +

Propriedades

+ +

Essa interface também herda propriedades de seu pai, {{domxref("EventTarget")}}.

+ +
+
{{domxref("BroadcastChannel.name")}}
+
Retorna um {{domxref("DOMString")}}, o nome do canal.
+
+

Event handlers

+
+
{{domxref("BroadcastChannel.onmessage")}}
+
Uma propriedade {{domxref("EventHandler")}} que específica a função a ser executada quando um evento {{event("message")}} é acionado a este objeto.
+
{{domxref("BroadcastChannel.onmessageerror")}}
+
Uma chamada {{domxref("EventHandler")}} quando um {{domxref("MessageEvent")}} do tipo {{domxref("MessageError")}} é disparado - isto é, quando recebe uma mensagem que não pode ser desserializada.
+
+ +

Métodos

+ +

Essa interface também herda métodos de seu pai, {{domxref("EventTarget")}}.

+ +
+
{{domxref("BroadcastChannel.postMessage()")}}
+
Envia a mensagem, de qualquer tipo de objeto, para cada objeto BroadcastChannel ouvindo o mesmo canal.
+
{{domxref("BroadcastChannel.close()")}}
+
Fecha o objeto do canal, indicando que ele não receberá novas mensagens e eventualmente será descartado.
+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG', "comms.html#broadcastchannel", "BroadcastChannel")}}{{Spec2('HTML WHATWG')}}Definição inicial.
+ +

Compatibilidade entre Navegadores

+ + + +

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

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/cache/index.html b/files/pt-br/web/api/cache/index.html new file mode 100644 index 0000000000..9647fb506e --- /dev/null +++ b/files/pt-br/web/api/cache/index.html @@ -0,0 +1,282 @@ +--- +title: Cache +slug: Web/API/Cache +tags: + - API + - Armazenamento + - Cache + - Experimental + - Interface + - Offline + - Rascunho + - Referencia + - Service Workers +translation_of: Web/API/Cache +--- +

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

+ +

A interface de Cache provê um mecanismo de pares de objeto Request / Response que estão cacheados, por exemplo, como parte do ciclo de vida de um {{domxref("ServiceWorker")}}. Note que a interface do Cache é exposta a escopos de janela como também aos workers. Você não precisa utiliza-la em conjunto com os service workers em si, mesmo que ela esteja definida na especificação dos mesmos.

+ +

Uma origem pode ter múltiplos objetos de cache nomeados. Você é o responsável por implementar como seu script (por exemplo, em um {{domxref("ServiceWorker")}}) trata uma atualização deste Cache. Itens em um Cache não são atualizados a não ser que explicitamente comandados para fazer tal coisa, também não expiram a não ser quando são deletados. Use {{domxref("CacheStorage.open", "CacheStorage.open(cacheName)")}} para abrir um Cache nomeado específico e depois chame qualquer um dos métodos presentes no Cache para manter os objetos cacheados.

+ +

Você é também o responsavel por, periódicamente, limpar as entradas de cache. Cada browser tem um limite fixo do tamanho de armazenamento de cache que cada origem pode utilizar. O browser faz o melhor que pode para gerenciar o espaço em disco, mas ele pode deletar um cache que não devia. Ele também vai, geralmente, deletar todos os dados de uma origem ou nenhum dado da mesma, nunca haverá uma ocasião não atômica onde o browser delete parcialmente os dados.

+ +

Certifique-se de versionar seus caches por nome e usar somente os caches nas versões do script que eles podem seguramente operar. Veja também o artigo sobre remoção de caches antigos para mais informações.

+ +
+

Nota: Implementações iniciais do Cache (tanto no Blink quando no Gecko) resolvem promises de {{domxref("Cache.add")}}, {{domxref("Cache.addAll")}}, e {{domxref("Cache.put")}} somente quando o corpo completo da resposta foi armazenado. Versões mais recentes desta especificação possuem uma melhora de linguagem informando que o browser pode resolver a promise assim que a entrada é registrada no banco de dados, mesmo que o corpo da resposta ainda esteja sendo enviado.

+
+ +
+

Nota: O algoritmo de comparação de chaves depende do cabeçalho VARY no valor. Então, comparar uma nova chave depende tanto de olhar para o valor e para a própria chave para novas entradas no cache.

+
+ +
+

Nota: A API de cache não segue os padrões HTTP de cabeçalhos de Cache.

+
+ +

Métodos

+ +
+
{{domxref("Cache.match", "Cache.match(request, options)")}}
+
Retorna uma {{jsxref("Promise")}} que resolve para a resposta associada com a primeira requisição encontrada no objeto {{domxref("Cache")}}.
+
{{domxref("Cache.matchAll", "Cache.matchAll(request, options)")}}
+
Retorna uma {{jsxref("Promise")}} que resolve para um array com todas as referências encontradas de requisições presentes no objeto {{domxref("Cache")}}.
+
{{domxref("Cache.add", "Cache.add(request)")}}
+
Pega a URL, obtém o resultado da resposta e adiciona o mesmo no cache informado. Esta funcionalidade é equivalente a chamar fetch(), e depois utilizar Cache.put() para adicionar o resultado no cache.
+
{{domxref("Cache.addAll", "Cache.addAll(requests)")}}
+
A partir de um array de URL's, obtém as respostas e adiciona todos os objetos resultantes no cache informado.
+
{{domxref("Cache.put", "Cache.put(request, response)")}}
+
Dado uma requisição e uma resposta, adiciona ambas ao cache informado.
+
{{domxref("Cache.delete", "Cache.delete(request, options)")}}
+
Encontra a entrada do {{domxref("Cache")}} na qual a chave é a requisição e, se encontrada, deleta a entrada do {{domxref("Cache")}} e retorna uma {{jsxref("Promise")}} que se resolve para true. Se nenhuma entrada do {{domxref("Cache")}} for encontrada, ela é resolvida para false.
+
{{domxref("Cache.keys", "Cache.keys(request, options)")}}
+
Retorna uma {{jsxref("Promise")}} que resolve em um array de chaves de {{domxref("Cache")}}.
+
+ +

Exemplos

+ +

Este trecho de código é da amostra de cache seletivo (veja seleção live de cache), ele utiliza {{domxref("CacheStorage.open", "CacheStorage.open(cacheName)")}} para abrir quaisquer objetos {{domxref("Cache")}} com um cabeçalho Content-Type que inicie com font/.

+ +

Então, utilizamos {{domxref("Cache.match", "Cache.match(request, options)")}} para verificar se já existe uma fonte encontrada no cache e, se existir, retorna-la. Caso contrário, o código busca a fonte da rede e utiliza {{domxref("Cache.put","Cache.put(request, response)")}} para adiciona-la ao cache.

+ +

O código gerencia as exceções disparadas pela operação {{domxref("Globalfetch.fetch","fetch()")}}. Note que uma resposta de erro HTTP (como o 404) não vai ativar uma exceção. Será retornado um objeto de resposta padrão que possui seu próprio código de erros.

+ +

O trecho também mostra as melhores práticas de versionamento de caches utilizadas pelo service worker. Mesmo que só estejamos utilizando um cache neste exemplo, a mesma aproximação pode ser utilizada para múltiplos caches. Mapeamos um identificador para um cache específico e versionado. Por fim, o código deleta todos os cache que não estão presentes em CURRENT_CACHES.

+ +

No exemplo, "Caches" é um atributo dos service workers no WorkerGlobalScope. Ele contém o CacheStorage, um objeto pelo qual podemos acessar a API de mesmo nome.

+ +
Nota: No Chrome, visite chrome://inspect/#service-workers e clique no link "inspect" abaixo do service worker registrado para analisar os logs das várias ações que o script "service-worker.js" está executando.
+ +
var CACHE_VERSION = 1;
+
+// Identificador menor para uma versão específica do cache
+var CURRENT_CACHES = {
+  font: 'font-cache-v' + CACHE_VERSION
+};
+
+self.addEventListener('activate', function(event) {
+  var expectedCacheNames = Object.keys(CURRENT_CACHES).map(function(key) {
+    return CURRENT_CACHES[key];
+  });
+
+  // O worker não vai ser tratado como ativo até que a Promise se resolva.
+  event.waitUntil(
+    caches.keys().then(function(cacheNames) {
+      return Promise.all(
+        cacheNames.map(function(cacheName) {
+          if (expectedCacheNames.indexOf(cacheName) == -1) {
+            console.log('Deletando cache expirado:', cacheName);
+
+            return caches.delete(cacheName);
+          }
+        })
+      );
+    })
+  );
+});
+
+self.addEventListener('fetch', function(event) {
+  console.log('Obtendo evento fetch para', event.request.url);
+
+  event.respondWith(
+
+    // Abre o objeto de cache que inicia com 'font'
+    caches.open(CURRENT_CACHES['font']).then(function(cache) {
+      return cache.match(event.request).then(function(response) {
+        if (response) {
+          console.log(' Encontrou resposta em cache:', response);
+
+          return response;
+        }
+      }).catch(function(error) {
+
+        // Trata exceções que vem de match() ou fetch().
+        console.error('  Erro na handler:', error);
+
+        throw error;
+      });
+    })
+  );
+});
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('Service Workers', '#cache', 'Cache')}}{{Spec2('Service Workers')}}Definição inicial
+ +

Tabela de compatibilidade

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
RecursoChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico{{CompatChrome(40.0)}}{{CompatGeckoDesktop(39)}}[1]{{CompatNo}}24{{CompatNo}}
add(){{CompatChrome(44.0)}}{{CompatVersionUnknown}}[1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
addAll(){{CompatChrome(46.0)}}{{CompatVersionUnknown}}[1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
matchAll(){{CompatChrome(47.0)}}{{CompatVersionUnknown}}[1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Requere HTTPS para add(), addAll(), e put(){{CompatChrome(46.0)}}{{CompatVersionUnknown}}[1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
RecursoAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Suporte básico{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile(39)}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatChrome(40.0)}}
add(){{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(44.0)}}
addAll(){{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(46.0)}}
matchAll(){{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(46.0)}}
Requere HTTPS para add(), addAll(), e put(){{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(46.0)}}
+
+ +

[1] Service workers (e Push) foram desabilitados no Firefox 45 & 52 Extended Support Releases (ESR.)

+ +

Ver também

+ + diff --git a/files/pt-br/web/api/cameracontrol/autofocus/index.html b/files/pt-br/web/api/cameracontrol/autofocus/index.html new file mode 100644 index 0000000000..1ce3b547d3 --- /dev/null +++ b/files/pt-br/web/api/cameracontrol/autofocus/index.html @@ -0,0 +1,61 @@ +--- +title: CameraControl.autoFocus() +slug: Web/API/CameraControl/autoFocus +translation_of: Archive/B2G_OS/API/CameraControl/autoFocus +--- +

{{APIRef("Camera API")}}{{ non-standard_header() }}{{B2GOnlyHeader2('privileged')}}

+ +

Resumo

+ +

This method attempts to focus the camera. If the camera is able to attempt to focus, a success callback is issued, regardless of whether or not the focusing attempt succeeds. If unable to attempt to focus, an error callback is performed instead.

+ +

The success or failure of the focus operation is indicated by the value of a parameter passed into the callback function.

+ +

Sintaxe

+ +
CameraControl.autoFocus(onsuccess[, onerror]);
+ +

Parametros

+ +
+
onsuccess
+
A callback function called when a focus attempt is made
+
onerror {{optional_inline()}}
+
An optional callback function that accepts an error string as an input parameter; this is called if it's not possible to attempt to focus the camera.
+
+ +

Exemplo

+ +
function onFocusPossible( success ) {
+  if ( success ) {
+    console.log("The image has been focused");
+  } else {
+    console.log("The image has not been focused");
+  }
+}
+
+function onFocusNotPossible( error ) {
+  console.log("The camera is not able to focus anything");
+  console.log( error );
+}
+
+function onAccessCamera( camera ) {
+  camera.autoFocus(onFocusPossible, onFocusNotPossible);
+};
+
+var options = {
+  camera: navigator.mozCameras.getListOfCameras()[0]
+};
+
+navigator.mozCameras.getCamera(options, onAccessCamera)
+
+ +

Especificações

+ +

Not part of any specification; however, this API should be removed when the WebRTC Capture and Stream API has been implemented.

+ +

Leia mais

+ + diff --git a/files/pt-br/web/api/cameracontrol/index.html b/files/pt-br/web/api/cameracontrol/index.html new file mode 100644 index 0000000000..e0b5bdd2c0 --- /dev/null +++ b/files/pt-br/web/api/cameracontrol/index.html @@ -0,0 +1,108 @@ +--- +title: CameraControl +slug: Web/API/CameraControl +tags: + - API + - B2G + - DOM + - DOM Reference + - Firefox OS + - Graphics + - JavaScript + - NeedsTranslation + - Non-standard + - Reference + - TopicStub + - WebAPI + - camera +translation_of: Archive/B2G_OS/API/CameraControl +--- +

{{APIRef("Camera API")}}

+ +

{{ non-standard_header() }}

+ +

{{B2GOnlyHeader2('privileged')}}

+ +

When you use the {{domxref("CameraManager.getCamera()")}} method to get a reference to a camera, you specify a callback function to be invoked on success. That function receives as a parameter a CameraControl object. You can use its methods and properties to manage and make use of the camera.

+ +

Properties

+ +
+
{{domxref("CameraControl.capabilities")}} {{readonlyinline}}
+
A {{domxref("CameraCapabilities")}} object indicating all the capabilities for the given camera.
+
{{domxref("CameraControl.effect")}}
+
A string defining the effect to be used by the camera (none by default). Its value must be one of the values available in {{domxref("CameraCapabilities.effects")}}.
+
{{domxref("CameraControl.exposureCompensation")}} {{readonlyinline}}
+
A value used to compensate the camera exposure. This attribute is read-only; to change the exposure, you need to call the {{domxref("CameraControl.setExposureCompensation()")}} method.
+
{{domxref("CameraControl.flashMode")}}
+
A string that defines how the flash, if any, is to be used; this is auto by default if the device has a flash, none otherwise. When set, its value must be chosen from the list of options specified by  {{domxref("CameraCapabilities.flashModes")}}.
+
{{domxref("CameraControl.focalLength")}} {{readonlyinline}}
+
A number that express the camera's focal length in millimeters.
+
{{domxref("CameraControl.focusAreas")}}
+
An Array of one or more objects that define where the camera will perform auto-focusing.
+
{{domxref("CameraControl.focusDistanceFar")}} {{readonlyinline}}
+
This value is a distance in meter used with {{domxref("CameraControl.focusDistanceNear")}} to defined the image's depth of field. The value for this property may be Infinity.
+
{{domxref("CameraControl.focusDistanceNear")}} {{readonlyinline}}
+
This value is a distance in meter used with {{domxref("CameraControl.focusDistanceFar")}} to defined the image's depth of field.
+
{{domxref("CameraControl.focusDistanceOptimum")}} {{readonlyinline}}
+
This value is a distance in meter where the subject will appear sharpest.
+
{{domxref("CameraControl.focusMode")}}
+
A string that defines which kind of focus mode the camera should use (auto or fixed by default). Its value must be chosen from {{domxref("CameraCapabilities.focusModes")}}.
+
{{domxref("CameraControl.meteringAreas")}}
+
An Array of one or more objects that define where the camera will perform auto-focusing.
+
{{domxref("CameraControl.onShutter")}}
+
A handler for the camera's "shutter" event, to trigger a shutter sound and/or a visual shutter indicator.
+
{{domxref("CameraControl.onClosed")}}
+
A handler called when a new CameraControl object in the same app takes over the camera.
+
{{domxref("CameraControl.onRecorderStateChange")}}
+
A function to call when the recorder changes state, either because the recording process encountered an error, or because one of the recording limits (see {{domxref("CameraControl.startRecording()")}}) was reached.
+
{{domxref("CameraControl.sceneMode")}}
+
A string that defines which scene mode the camera is to use (auto by default). Its value must be chosen from {{domxref("CameraCapabilities.sceneModes")}}.
+
{{domxref("CameraControl.whiteBalanceMode")}}
+
A string that defines which white balance mode the camera is to use (auto by default). Its value must be chosen from {{domxref("CameraCapabilities.whiteBalanceModes")}}.
+
{{domxref("CameraControl.zoom")}}
+
A number that defines which kind of zoom factor mode the camera is to use (1 by default). Its value must be chosen from {{domxref("CameraCapabilities.zoomRatios")}}.
+
+ +

Methods

+ +
+
{{ domxref("CameraControl.autoFocus()") }}
+
Tells the camera to attempt to focus the image.
+
{{ domxref("CameraControl.getPreviewStream()") }}
+
Gets a video stream from the camera; you can use this in an arbitrary context.
+
{{ domxref("CameraControl.getPreviewStreamVideoMode()") }}
+
Gets a video stream from the camera based on a specific video mode.
+
{{ domxref("CameraControl.release()") }}
+
Releases the camera so that other applications can use it.
+
{{ domxref("CameraControl.resumePreview()") }}
+
Resumes the preview video stream after it's been paused by a call to {{domxref("CameraControl.takePicture()")}}.
+
{{ domxref("CameraControl.setExposureCompensation()") }}
+
Lets you specify the exposure compensation factor.
+
{{ domxref("CameraControl.startRecording()") }}
+
Lets you start recording a video stream.
+
{{ domxref("CameraControl.stopRecording()") }}
+
Lets you stop recording a video stream.
+
{{ domxref("CameraControl.pauseRecording()") }}
+
Pauses the recording of a video stream.
+
{{ domxref("CameraControl.resumeRecording()") }}
+
Resumes the recording of a video stream that has previously been paused.
+
{{ domxref("CameraControl.takePicture()") }}
+
Lets you capture a single image, receiving it as a {{domxref("Blob")}}.
+
+ +

Specification

+ +

{{page("/en-US/docs/Web/API/Navigator.MozCameras","Specification")}}

+ +

Permissions

+ +

{{page("/en-US/docs/Web/API/Navigator.MozCameras","Permissions")}}

+ +

See also

+ + diff --git a/files/pt-br/web/api/canvasrenderingcontext2d/arc/index.html b/files/pt-br/web/api/canvasrenderingcontext2d/arc/index.html new file mode 100644 index 0000000000..763831af7d --- /dev/null +++ b/files/pt-br/web/api/canvasrenderingcontext2d/arc/index.html @@ -0,0 +1,138 @@ +--- +title: CanvasRenderingContext2D.arc() +slug: Web/API/CanvasRenderingContext2D/arc +tags: + - API + - Arco + - Canvas + - CanvasRenderingContext2D + - Circulo + - Method + - Reference +translation_of: Web/API/CanvasRenderingContext2D/arc +--- +
{{APIRef}}
+ +

O método CanvasRenderingContext2D.arc() da API Canvas 2D adiciona um arco circular para o atual sub-caminhoa (sub-path).

+ +

Sintaxe

+ +
void ctx.arc(x, y, raio, anguloInicial, anguloFinal [, antiHorario]);
+
+ +

O método arc() cria um arco circular centralizado em (x, y) com um raio. O caminho inicia-se no anguloInicial, e finaliza no anguloFinal, e é desenhado no sentido antiHoario (o padrão é no sentido horario).

+ +

Parâmetros

+ +
+
x
+
A coordenada horizontal do centro do arco.
+
y
+
A coordenada vertical do centro do arco.
+
raio
+
O raio do arco. Deve ser um valor positivo.
+
anguloInicial
+
O ângulo em radianos em que o arco começa medido a partir do eixo x positivo.
+
anguloFinal
+
O ângulo em que o arco finaliza medido a partir do eixo x positivo.
+
antiHorario {{optional_inline}}
+
Um {{jsxref("Boolean")}} opcional. Se verdadeiro, desenha o arco no sentido anti-horário entre os ângulos inicial e final. O padrão é falso (sentido horário).
+
+ +

Examplos

+ +

Desenhando um círculo completo

+ +

O exemplo desenha um círculo completo com o método arc().

+ +

HTML

+ +
<canvas></canvas>
+
+ +

JavaScript

+ +

O arco recebe 100 como uma coordenada x, e 75 como uma coordenada y e um raio de 50. para fazer um círculo completo, o arco inicia no ângulo 0 (0º) em radianos e finaliza em um ângulo de 2π radianos (360°).

+ +
const canvas = document.querySelector('canvas');
+const ctx = canvas.getContext('2d');
+
+ctx.beginPath();
+ctx.arc(100, 75, 50, 0, 2 * Math.PI);
+ctx.stroke();
+
+ +

Resultado

+ +

{{ EmbedLiveSample('Drawing_a_full_circle', 700, 180) }}

+ +

Diferentes formas demonstradas

+ +

Este exemplo desenha diversas formas para mostrar o que é possível fazer com o método arc().

+ + + +
const canvas = document.querySelector('canvas');
+const ctx = canvas.getContext('2d');
+
+// Draw shapes
+for (let i = 0; i <= 3; i++) {
+  for (let j = 0; j <= 2; j++) {
+    ctx.beginPath();
+    let x             = 25 + j * 50;                 // coordenada x
+    let y             = 25 + i * 50;                 // coordenada y
+    let radius        = 20;                          // raio
+    let startAngle    = 0;                           // angulo inicial
+    let endAngle      = Math.PI + (Math.PI * j) / 2; // angulo final
+    let anticlockwise = i % 2 == 1;                  // sentido anti-horário
+
+    ctx.arc(x, y, radius, startAngle, endAngle, anticlockwise);
+
+    if (i > 1) {
+      ctx.fill();
+    } else {
+      ctx.stroke();
+    }
+  }
+}
+ +

Resultado

+ +

{{ EmbedLiveSample('Different_shapes_demonstrated', 160, 210, "https://mdn.mozillademos.org/files/204/Canvas_arc.png") }}

+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG', "scripting.html#dom-context-2d-arc", "CanvasRenderingContext2D.arc")}}{{Spec2('HTML WHATWG')}}
+ +

Compatibilidade de navegador

+ + + +

{{Compat("api.CanvasRenderingContext2D.arc")}}

+ +

Veja mais

+ + diff --git a/files/pt-br/web/api/canvasrenderingcontext2d/arcto/index.html b/files/pt-br/web/api/canvasrenderingcontext2d/arcto/index.html new file mode 100644 index 0000000000..c4fcdc1e69 --- /dev/null +++ b/files/pt-br/web/api/canvasrenderingcontext2d/arcto/index.html @@ -0,0 +1,147 @@ +--- +title: CanvasRenderingContext2D.arcTo() +slug: Web/API/CanvasRenderingContext2D/arcTo +translation_of: Web/API/CanvasRenderingContext2D/arcTo +--- +
{{APIRef}}
+ +

 

+ +

O método CanvasRenderingContext2D.arcTo() da API 2D do Canvas adiciona um arco ao caminho quando fornecemos seus pontos de controle e raio.

+ +

O arco será parte de um círculo, nunca de uma elipse. Frequentemente é usado para fazer cantos arredoondados.

+ +

Pode-se imaginar o arco como dois segmentos de reta, partindo de um ponto inicial (ponto mais recente definido no caminho) até o primeiro ponto de controle e, em seguida, do primeiro ponto de controle até o segundo ponto de controle. Esses dois segmentos de reta formam um angulo, com o primeiro ponto de controle sendo a curva. Usando arcTo, o ângulo será formado de acordo com o raio fornecido.

+ +

O arco é tangencial ao dois segmentos de reta, e por vezes, pode produzir resultados inesperados se, por exemplo, o raio fornecido for maior que a distância entre o ponto inicial e o primeiro ponto de controle.

+ +

Se o raio fornecido não atingir o ponto inicial (ponto mais recente definido no caminho), o ponto inicial é conectado ao arco por um segmento de reta.

+ +

Sintaxe

+ +
void ctx.arcTo(x1, y1, x2, y2, radius);
+
+ +

Parâmetros

+ +
+
x1
+
coordenada do eixo x para o primeiro ponto de controle.
+
y1
+
coordenada do eixo y para o primeiro ponto de controle.
+
x2
+
coordenada do eixo x para o segundo ponto de controle.
+
y2
+
coordenada do eixo y para o segundo ponto de controle.
+
radius
+
O raio do arco.
+
+ +

Exemplos

+ +

Usando o método arcTo 

+ +

Esse é um trecho simples de código que desenha um arco. O ponto de partida é azul e os pontos de controls são vermelhos.

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById('canvas');
+var ctx = canvas.getContext('2d');
+
+ctx.beginPath();
+ctx.moveTo(150, 20);
+ctx.arcTo(150, 100, 50, 20, 30);
+ctx.lineTo(50, 20)
+ctx.stroke();
+
+ctx.fillStyle = 'blue';
+// starting point
+ctx.fillRect(150, 20, 10, 10);
+
+ctx.fillStyle = 'red';
+// control point one
+ctx.fillRect(150, 100, 10, 10);
+// control point two
+ctx.fillRect(50, 20, 10, 10);
+
+ +

{{ EmbedLiveSample('Using_the_arc_method', 315, 165) }}

+ +

Treinando os parâmetros do  arcTo 

+ +

Altere o código abaixo e veja suas alterações atualizadas na tela:

+ +
+
<canvas id="canvas" class="playable-canvas" height="200" width="400"></canvas>
+<div class="playable-buttons">
+  <input id="edit" type="button" value="Edit" />
+  <input id="reset" type="button" value="Reset" />
+</div>
+<textarea id="code" class="playable-code">
+ctx.beginPath();
+ctx.moveTo(150, 20);
+ctx.arcTo(150,100,50,100,20);
+ctx.stroke();</textarea>
+
+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+var textarea = document.getElementById("code");
+var reset = document.getElementById("reset");
+var edit = document.getElementById("edit");
+var code = textarea.value;
+
+function drawCanvas() {
+  ctx.clearRect(0, 0, canvas.width, canvas.height);
+  eval(textarea.value);
+}
+
+reset.addEventListener("click", function() {
+  textarea.value = code;
+  drawCanvas();
+});
+
+edit.addEventListener("click", function() {
+  textarea.focus();
+})
+
+textarea.addEventListener("input", drawCanvas);
+window.addEventListener("load", drawCanvas);
+
+
+ +

{{ EmbedLiveSample('Trying_the_arcTo_parameters', 700, 360) }}

+ +

Espeficicações

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "scripting.html#dom-context-2d-arcto", "CanvasRenderingContext2D.arcTo")}}{{Spec2('HTML WHATWG')}} 
+ +

Compatibilidade

+ + + +

{{Compat("api.CanvasRenderingContext2D.arcTo")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/canvasrenderingcontext2d/beginpath/index.html b/files/pt-br/web/api/canvasrenderingcontext2d/beginpath/index.html new file mode 100644 index 0000000000..b3ad87ff61 --- /dev/null +++ b/files/pt-br/web/api/canvasrenderingcontext2d/beginpath/index.html @@ -0,0 +1,184 @@ +--- +title: CanvasRenderingContext2D.beginPath() +slug: Web/API/CanvasRenderingContext2D/beginPath +tags: + - API + - Canvas + - CanvasRenderingContext2D + - Referencia + - metodo +translation_of: Web/API/CanvasRenderingContext2D/beginPath +--- +
{{APIRef}}
+ +

O método CanvasRenderingContext2D.beginPath() da API Canvas 2D  inicia um novo caminho (path), esvaziando a lista de sub-caminhos (sub-paths). Use esse método quando você quiser criar um novo path.

+ +

Sintaxe

+ +
void ctx.beginPath();
+
+ +

Exemplos

+ +

Usando o método beginPath

+ +

Isto é só um simples trecho de código que usa o método fillRect.

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById('canvas');
+var ctx = canvas.getContext('2d');
+
+// Primeiro path
+ctx.beginPath();
+ctx.strokeStyle = 'blue';
+ctx.moveTo(20, 20);
+ctx.lineTo(200, 20);
+ctx.stroke();
+
+// Segundo path
+ctx.beginPath();
+ctx.strokeStyle = 'green';
+ctx.moveTo(20, 20);
+ctx.lineTo(120, 120);
+ctx.stroke();
+
+ +

Edite o código abaixo e veja as alterações instantâneas no canvas:

+ +
+
Playable code
+ +
<canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas>
+<div class="playable-buttons">
+  <input id="edit" type="button" value="Edit" />
+  <input id="reset" type="button" value="Reset" />
+</div>
+<textarea id="code" class="playable-code" style="height:200px">
+// First path
+ctx.beginPath();
+ctx.strokeStyle = 'blue';
+ctx.moveTo(20,20);
+ctx.lineTo(200,20);
+ctx.stroke();
+
+// Second path
+ctx.beginPath();
+ctx.strokeStyle = 'green';
+ctx.moveTo(20,20);
+ctx.lineTo(120, 120);
+ctx.stroke();</textarea>
+
+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+var textarea = document.getElementById("code");
+var reset = document.getElementById("reset");
+var edit = document.getElementById("edit");
+var code = textarea.value;
+
+function drawCanvas() {
+  ctx.clearRect(0, 0, canvas.width, canvas.height);
+  eval(textarea.value);
+}
+
+reset.addEventListener("click", function() {
+  textarea.value = code;
+  drawCanvas();
+});
+
+edit.addEventListener("click", function() {
+  textarea.focus();
+})
+
+textarea.addEventListener("input", drawCanvas);
+window.addEventListener("load", drawCanvas);
+
+
+ +

{{ EmbedLiveSample('Playable_code', 700, 460) }}

+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('HTML WHATWG', "scripting.html#dom-context-2d-beginpath", "CanvasRenderingContext2D.beginPath")}}{{Spec2('HTML WHATWG')}} 
+ +

Compatibilidade em Navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome para AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/canvasrenderingcontext2d/clearrect/index.html b/files/pt-br/web/api/canvasrenderingcontext2d/clearrect/index.html new file mode 100644 index 0000000000..ec1be69b57 --- /dev/null +++ b/files/pt-br/web/api/canvasrenderingcontext2d/clearrect/index.html @@ -0,0 +1,195 @@ +--- +title: CanvasRenderingContext2D.clearRect() +slug: Web/API/CanvasRenderingContext2D/clearRect +tags: + - API + - Canvas + - CanvasRenderingContext2D + - Referencia + - metodo +translation_of: Web/API/CanvasRenderingContext2D/clearRect +--- +
{{APIRef}}
+ +

O método CanvasRenderingContext2D.clearRect() da API Canvas 2D limpa todos os pixels de um retângulo definido na posição (x, y) e tamanho (width (largura), height (altura)) para uma cor preta transparente, apagando algum conteúdo anterior.

+ +

Sintaxe

+ +
void ctx.clearRect(x, y, width, height);
+
+ +

Parâmetros

+ +
+
x
+
O valor da coordenada x para o ponto inicial do retângulo.
+
y
+
O valor da coordenada y para o ponto inicial do retângulo.
+
width
+
A largura do retângulo.
+
height
+
A altura do retângulo.
+
+ +

Notas de uso

+ +

Um problema comum com clearRect que pode acontecer, é que pode não funcionar corretamente, caso não seja usada alguma propriedade de path. Não esqueça de usar {{domxref("CanvasRenderingContext2D.beginPath", "beginPath()")}} antes de começar um novo frame depois de chamar clearRect.

+ +

Exemplos

+ +

Usando o método clearRect

+ +

Isto é só um simples trecho de código que usa o método clearRect.

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById('canvas');
+var ctx = canvas.getContext('2d');
+
+ctx.beginPath();
+ctx.moveTo(20, 20);
+ctx.lineTo(200, 20);
+ctx.lineTo(120, 120);
+ctx.closePath(); // draws last line of the triangle
+ctx.stroke();
+
+ctx.clearRect(10, 10, 100, 100);
+
+// clear the whole canvas
+// ctx.clearRect(0, 0, canvas.width, canvas.height);
+
+ +

Edite o código abaixo e veja as alterações instantâneas no canvas:

+ +
+
Playable code
+ +
<canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas>
+<div class="playable-buttons">
+  <input id="edit" type="button" value="Edit" />
+  <input id="reset" type="button" value="Reset" />
+</div>
+<textarea id="code" class="playable-code" style="height:140px;">
+ctx.beginPath();
+ctx.moveTo(20,20);
+ctx.lineTo(200,20);
+ctx.lineTo(120,120);
+ctx.closePath(); // draws last line of the triangle
+ctx.stroke();
+
+ctx.clearRect(10, 10, 100, 100);</textarea>
+
+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+var textarea = document.getElementById("code");
+var reset = document.getElementById("reset");
+var edit = document.getElementById("edit");
+var code = textarea.value;
+
+function drawCanvas() {
+  ctx.clearRect(0, 0, canvas.width, canvas.height);
+  eval(textarea.value);
+}
+
+reset.addEventListener("click", function() {
+  textarea.value = code;
+  drawCanvas();
+});
+
+edit.addEventListener("click", function() {
+  textarea.focus();
+})
+
+textarea.addEventListener("input", drawCanvas);
+window.addEventListener("load", drawCanvas);
+
+
+ +

{{ EmbedLiveSample('Playable_code', 700, 400) }}

+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('HTML WHATWG', "scripting.html#dom-context-2d-clearrect", "CanvasRenderingContext2D.clearRect")}}{{Spec2('HTML WHATWG')}} 
+ +

Compatibilidade em Navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome para AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/canvasrenderingcontext2d/clip/index.html b/files/pt-br/web/api/canvasrenderingcontext2d/clip/index.html new file mode 100644 index 0000000000..780ba3cd58 --- /dev/null +++ b/files/pt-br/web/api/canvasrenderingcontext2d/clip/index.html @@ -0,0 +1,195 @@ +--- +title: CanvasRenderingContext2D.clip() +slug: Web/API/CanvasRenderingContext2D/clip +translation_of: Web/API/CanvasRenderingContext2D/clip +--- +
{{APIRef}}
+ +

O método CanvasRenderingContext2D.clip() da API do Canvas 2D transforma o caminho atualmente construido em um caminho atual de recorte.

+ +

Sintaxe

+ +
void ctx.clip();
+void ctx.clip(fillRule);
+void ctx.clip(path, fillRule);
+
+ +

Parâmetros

+ +

+ +
+
fillRule
+
O algoritmo pelo qual determina se um ponto esta dentro de um caminho ou fora de um caminho.
+ Valores Possíveis: + +
+
path
+
Um {{domxref("Path2D")}} caminho para recorte.
+
+ +

Exemplos

+ +

Usando do método de corte

+ +

Isso é só um simples fragmento de código que usa o método de corte para criar uma região de recorte.

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+
+// Cria uma região de recorte
+ctx.arc(100, 100, 75, 0, Math.PI*2, false);
+ctx.clip();
+
+ctx.fillRect(0, 0, 100,100);
+
+ +

Edite o código abaixo e veja suas mudanças atualizadas ao vivo no canvas:

+ +
+
Playable code
+ +
<canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas>
+<div class="playable-buttons">
+  <input id="edit" type="button" value="Edit" />
+  <input id="reset" type="button" value="Reset" />
+</div>
+<textarea id="code" class="playable-code">
+ctx.arc(100, 100, 75, 0, Math.PI*2, false);
+ctx.clip();
+ctx.fillRect(0, 0, 100,100);</textarea>
+
+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+var textarea = document.getElementById("code");
+var reset = document.getElementById("reset");
+var edit = document.getElementById("edit");
+var code = textarea.value;
+
+function drawCanvas() {
+  ctx.clearRect(0, 0, canvas.width, canvas.height);
+  eval(textarea.value);
+}
+
+reset.addEventListener("click", function() {
+  textarea.value = code;
+  drawCanvas();
+});
+
+edit.addEventListener("click", function() {
+  textarea.focus();
+})
+
+textarea.addEventListener("input", drawCanvas);
+window.addEventListener("load", drawCanvas);
+
+
+ +

{{ EmbedLiveSample('Playable_code', 700, 360) }}

+ +
+

Nota: Tenha consciência de que o clip() só funciona com formas adicionadas ao caminho; ele não funciona com uma forma primitiva, como retângulos criados com {{domxref("CanvasRenderingContext2D.fillRect()","fillRect()")}}. Nesse caso você teria que usar {{domxref("CanvasRenderingContext2D.rect()","rect()")}} para desenhar um caminho de forma retângular para ser recortado.

+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('HTML WHATWG', "scripting.html#dom-context-2d-clip", "CanvasRenderingContext2D.clip")}}{{Spec2('HTML WHATWG')}} 
+ +

Compatibilidade com os navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte Básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Parametro do Caminho{{CompatUnknown}}{{ CompatGeckoDesktop(31) }}{{ CompatNo }}{{CompatUnknown}}{{ CompatNo }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome para AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte Básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Parametro do Caminho{{CompatUnknown}}{{CompatUnknown}}{{ CompatGeckoMobile(31) }}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Ver também

+ + diff --git a/files/pt-br/web/api/canvasrenderingcontext2d/closepath/index.html b/files/pt-br/web/api/canvasrenderingcontext2d/closepath/index.html new file mode 100644 index 0000000000..62c72086f7 --- /dev/null +++ b/files/pt-br/web/api/canvasrenderingcontext2d/closepath/index.html @@ -0,0 +1,170 @@ +--- +title: CanvasRenderingContext2D.closePath() +slug: Web/API/CanvasRenderingContext2D/closePath +tags: + - API + - Canvas + - CanvasRenderingContext2D + - Referencia + - metodo +translation_of: Web/API/CanvasRenderingContext2D/closePath +--- +
{{APIRef}}
+ +

O método CanvasRenderingContext2D.closePath() da API Canvas 2D faz o ponto da caneta (pen) mover-se de volta para o início do sub-caminho (sub-path) atual. Tenta adicionar uma nova linha (mas não a desenha realmente) que conecta o ponto atual até o ponto inicial. Se a região (shape) já estiver fechada, ou tem somente um ponto na tela, esta função não funciona.

+ +

Sintaxe

+ +
void ctx.closePath();
+
+ +

Exemplos

+ +

Usando o método beginPath

+ +

Isto é só um simples trecho de código que usa o método fillRect.

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById('canvas');
+var ctx = canvas.getContext('2d');
+
+ctx.beginPath();
+ctx.moveTo(20, 20);
+ctx.lineTo(200, 20);
+ctx.lineTo(120, 120);
+ctx.closePath(); // desenha a última linha do triângulo
+ctx.stroke();
+
+ +

Edite o código abaixo e veja as alterações instantâneas no canvas:

+ +
+
Playable code
+ +
<canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas>
+<div class="playable-buttons">
+  <input id="edit" type="button" value="Edit" />
+  <input id="reset" type="button" value="Reset" />
+</div>
+<textarea id="code" class="playable-code" style="height:140px;">
+ctx.beginPath();
+ctx.moveTo(20,20);
+ctx.lineTo(200,20);
+ctx.lineTo(120,120);
+ctx.closePath(); // draws last line of the triangle
+ctx.stroke();</textarea>
+
+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+var textarea = document.getElementById("code");
+var reset = document.getElementById("reset");
+var edit = document.getElementById("edit");
+var code = textarea.value;
+
+function drawCanvas() {
+  ctx.clearRect(0, 0, canvas.width, canvas.height);
+  eval(textarea.value);
+}
+
+reset.addEventListener("click", function() {
+  textarea.value = code;
+  drawCanvas();
+});
+
+edit.addEventListener("click", function() {
+  textarea.focus();
+})
+
+textarea.addEventListener("input", drawCanvas);
+window.addEventListener("load", drawCanvas);
+
+
+ +

{{ EmbedLiveSample('Playable_code', 700, 400) }}

+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('HTML WHATWG', "scripting.html#dom-context-2d-closepath", "CanvasRenderingContext2D.closePath")}}{{Spec2('HTML WHATWG')}} 
+ +

Compatibilidade em Navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome para AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/canvasrenderingcontext2d/fill/index.html b/files/pt-br/web/api/canvasrenderingcontext2d/fill/index.html new file mode 100644 index 0000000000..0c0c1dd890 --- /dev/null +++ b/files/pt-br/web/api/canvasrenderingcontext2d/fill/index.html @@ -0,0 +1,196 @@ +--- +title: CanvasRenderingContext2D.fill() +slug: Web/API/CanvasRenderingContext2D/fill +tags: + - API + - Canvas + - CanvasRenderingContext2D + - Referencia + - metodo +translation_of: Web/API/CanvasRenderingContext2D/fill +--- +
{{APIRef}}
+ +

O método CanvasRenderingContext2D.fill() da API Canvas 2D preenche um dado path ou o path atual com o estilo atual de preenchimento usando uma regra de controle diferente de zero, ou uma regra par-ímpar.

+ +

Syntax

+ +
void ctx.fill();
+void ctx.fill(fillRule);
+void ctx.fill(path, fillRule);
+
+ +

Parâmetros

+ +
+
fillRule
+
O algoritmo que determina se um ponto está do lado de dentro do path ou do lado fora do path.
+ Possíveis valores: + +
+
path
+
Um path de Path2D para preenchimento.
+
+ +

Exemplos

+ +

Usando o método fill

+ +

Isto é só um simples trecho de código que usa o métod fill para contornar um path.

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById('canvas');
+var ctx = canvas.getContext('2d');
+ctx.rect(10, 10, 100, 100);
+ctx.fill();
+
+ +

Edite o código abaixo e veja as alterações instantâneas no canvas:

+ +
+
Playable code
+ +
<canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas>
+<div class="playable-buttons">
+  <input id="edit" type="button" value="Edit" />
+  <input id="reset" type="button" value="Reset" />
+</div>
+<textarea id="code" class="playable-code">
+ctx.rect(10, 10, 100, 100);
+ctx.fill();</textarea>
+
+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+var textarea = document.getElementById("code");
+var reset = document.getElementById("reset");
+var edit = document.getElementById("edit");
+var code = textarea.value;
+
+function drawCanvas() {
+  ctx.clearRect(0, 0, canvas.width, canvas.height);
+  eval(textarea.value);
+}
+
+reset.addEventListener("click", function() {
+  textarea.value = code;
+  drawCanvas();
+});
+
+edit.addEventListener("click", function() {
+  textarea.focus();
+})
+
+textarea.addEventListener("input", drawCanvas);
+window.addEventListener("load", drawCanvas);
+
+
+ +

{{ EmbedLiveSample('Playable_code', 700, 360) }}

+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('HTML WHATWG', "scripting.html#dom-context-2d-fill", "CanvasRenderingContext2D.fill")}}{{Spec2('HTML WHATWG')}} 
+ +

Compatibilidade em Navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
Suporte para o parâmetro path{{ CompatVersionUnknown() }}{{CompatVersionUnknown}}{{ CompatGeckoDesktop(31) }}{{ CompatNo }}{{ CompatVersionUnknown() }}{{ CompatNo }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
Suporte para o parâmetro path{{ CompatUnknown() }}{{ CompatUnknown() }}{{CompatVersionUnknown}}{{ CompatGeckoMobile(31) }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/canvasrenderingcontext2d/fillrect/index.html b/files/pt-br/web/api/canvasrenderingcontext2d/fillrect/index.html new file mode 100644 index 0000000000..44b57ca77a --- /dev/null +++ b/files/pt-br/web/api/canvasrenderingcontext2d/fillrect/index.html @@ -0,0 +1,179 @@ +--- +title: CanvasRenderingContext2D.fillRect() +slug: Web/API/CanvasRenderingContext2D/fillRect +tags: + - API + - Canvas + - CanvasRenderingContext2D + - Referencia + - metodo +translation_of: Web/API/CanvasRenderingContext2D/fillRect +--- +
{{APIRef}}
+ +

O método CanvasRenderingContext2D.fillRect() da API Canvas 2D desenha um retângulo preenchido na posição (x, y), no qual o tamanho é determinado pela width (largura) e pela height (altura), e cujo o estilo é determinado pelo atributo fillStyle.

+ +

Sintaxe

+ +
void ctx.fillRect(x, y, width, height);
+
+ +

Parâmetros

+ +
+
x
+
O valor da coordenada x para o ponto inicial do retângulo.
+
y
+
O valor da coordenada y para o ponto inicial do retângulo.
+
width
+
A largura do retângulo.
+
height
+
A altura do retângulo.
+
+ +

Exemplos

+ +

Usando o método fillRect

+ +

Isto é só um simples trecho de código que usa o método fillRect.

+ +

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);
+
+// preenche todo o canvas
+// ctx.fillRect(0, 0, canvas.width, canvas.height);
+
+ +

Edite o código abaixo e veja as alterações instantâneas no canvas:

+ +
+
Playable code
+ +
<canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas>
+<div class="playable-buttons">
+  <input id="edit" type="button" value="Edit" />
+  <input id="reset" type="button" value="Reset" />
+</div>
+<textarea id="code" class="playable-code">
+ctx.fillStyle = "green";
+ctx.fillRect(10, 10, 100, 100);</textarea>
+
+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+var textarea = document.getElementById("code");
+var reset = document.getElementById("reset");
+var edit = document.getElementById("edit");
+var code = textarea.value;
+
+function drawCanvas() {
+  ctx.clearRect(0, 0, canvas.width, canvas.height);
+  eval(textarea.value);
+}
+
+reset.addEventListener("click", function() {
+  textarea.value = code;
+  drawCanvas();
+});
+
+edit.addEventListener("click", function() {
+  textarea.focus();
+})
+
+textarea.addEventListener("input", drawCanvas);
+window.addEventListener("load", drawCanvas);
+
+
+ +

{{ EmbedLiveSample('Playable_code', 700, 360) }}

+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('HTML WHATWG', "scripting.html#dom-context-2d-fillrect", "CanvasRenderingContext2D.fillRect")}}{{Spec2('HTML WHATWG')}} 
+ +

Compatibilidade em Navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome para AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/canvasrenderingcontext2d/fillstyle/index.html b/files/pt-br/web/api/canvasrenderingcontext2d/fillstyle/index.html new file mode 100644 index 0000000000..37dd9ba936 --- /dev/null +++ b/files/pt-br/web/api/canvasrenderingcontext2d/fillstyle/index.html @@ -0,0 +1,213 @@ +--- +title: CanvasRenderingContext2D.fillStyle +slug: Web/API/CanvasRenderingContext2D/fillStyle +tags: + - API + - Canvas + - CanvasRenderingContext2D + - Propriedade + - Referencia +translation_of: Web/API/CanvasRenderingContext2D/fillStyle +--- +
{{APIRef}}
+ +

A propriedade CanvasRenderingContext2D.fillStyle da API do Canvas 2D especifica a cor ou o estilo para usar regiões internas. O valor inicial é #000 (preto).

+ +

Veja também o capítulo Aplicando estilos e cores no Canvas Tutorial.

+ +

Sintaxe

+ +
ctx.fillStyle = color;
+ctx.fillStyle = gradient;
+ctx.fillStyle = pattern;
+
+ +

Opções

+ +
+
color
+
Um {{domxref("DOMString")}} passado como um valor de CSS {{cssxref("<color>")}}.
+
gradient
+
Um objeto {{domxref("CanvasGradient")}} (um gradiente linear ou radial).
+
pattern
+
Um objeto {{domxref("CanvasPattern")}} (uma imagem repetitiva).
+
+ +

Examples

+ +

Usando a propriedade fillStyle para definir uma cor diferente

+ +

Isto é apenas um trecho de código simples usando a propriedade fillStyle para definir uma cor diferente.

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById('canvas');
+var ctx = canvas.getContext('2d');
+
+ctx.fillStyle = 'blue';
+ctx.fillRect(10, 10, 100, 100);
+
+ +

Edite o código abaixo e veja as alterações atualizadas na tela:

+ + + +

{{ EmbedLiveSample('Playable_code', 700, 360) }}

+ +

Um exemplo de fillStyle com laços for

+ +

Neste exemplo, nós usamos dois laços for para desenhar uma grade de retângulos, cada um com uma cor diferente. A imagem resultante deve parecer algo como uma captura de tela. Não há nada de espetacular acontecendo aqui. Usamos as duas variáveis i é j para gerar uma cor RGB exclusiva para cada quadrado, e apenas modificamos os valores vermelho e verde. O canal azul tem um valor fixo. Ao modificar os canais, você pode gerar todos os tipos de paletas. Ao aumentar os valores, você pode conseguir algo que pareça com as paletas de cores que o Photoshop usa.

+ + + +
var ctx = document.getElementById('canvas').getContext('2d');
+for (var i = 0; i < 6; i++){
+  for (var j = 0; j < 6; j++){
+    ctx.fillStyle = 'rgb(' + Math.floor(255 - 42.5 * i) + ',' +
+                     Math.floor(255 - 42.5 * j) + ',0)';
+    ctx.fillRect(j * 25, i * 25, 25, 25);
+  }
+}
+
+ +

O resultado fica assim:

+ +

{{EmbedLiveSample("Um_exemplo_de_fillStyle_com_laços_for", 160, 160, "https://mdn.mozillademos.org/files/5417/Canvas_fillstyle.png")}}

+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('HTML WHATWG', "scripting.html#dom-context-2d-fillstyle", "CanvasRenderingContext2D.fillStyle")}}{{Spec2('HTML WHATWG')}} 
+ +

Compatibibidade com o Navegador

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte Básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome para AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte Básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ + + + + +

Veja também

+ + diff --git a/files/pt-br/web/api/canvasrenderingcontext2d/index.html b/files/pt-br/web/api/canvasrenderingcontext2d/index.html new file mode 100644 index 0000000000..38ec19a3e3 --- /dev/null +++ b/files/pt-br/web/api/canvasrenderingcontext2d/index.html @@ -0,0 +1,450 @@ +--- +title: 'Canvas: Contexto de Renderização em "2D"' +slug: Web/API/CanvasRenderingContext2D +tags: + - API + - Canvas + - CanvasRenderingContext2D + - Games + - Graphics + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/API/CanvasRenderingContext2D +--- +
{{APIRef}}
+ +
A interface Canvas Renderização de Contexto de duas Dimensões ( CanvasRenderingContext2D) é usada para desenhar retangulos, textos, imagens e outros objetos na tag ou elemento canvas. Fornece o contexto de renderização em 2D para a superfície de desenho do elemento  {{ HTMLElement("canvas") }}.
+ +
+ +

Para obter um objeto desta interface, chama-se  {{domxref("HTMLCanvasElement.getContext()", "getContext()")}} em um elemento <canvas>, adicionando "2d" como argumento, veja o exemplo abaixo:

+ +
var canvas = document.getElementById('meuCanvas'); // em seu HTML esse elemento se parece com <canvas id="meuCanvas"></canvas>
+var ctx = canvas.getContext('2d');
+
+ +

Agora que você possui o contexto de renderização 2D, você pode desenhar dentro deste canvas. Por exemplo:

+ +
ctx.fillStyle = "rgb(200,0,0)"; // define a cor de preenchimento do retângulo
+ctx.fillRect(10, 10, 55, 50);   // desenha o retângulo na posição 10, 10 com 55 pixels de largura e uma altura de 50
+
+ +

Veja as propriedades e métodos no menu lateral e abaixo. O tutorial canvas tem mais informações, exemplos e recursos.

+ +

Desenhando Retângulos

+ +

Existem três métodos que imediatamente desenham retângulos ao canvas.

+ +
+
{{domxref("CanvasRenderingContext2D.clearRect()")}}
+
Determina todos os pixels no retângulo definido, pelo ponto inicial (x, y) e tamanho (largura, altura) para preto transparente, apagando qualquer conteúdo desenhado anteriormente.
+
{{domxref("CanvasRenderingContext2D.fillRect()")}}
+
Desenha um retângulo preenchido na posição (x, y) com tamanho definido pela largura e altura
+
{{domxref("CanvasRenderingContext2D.strokeRect()")}}
+
Pinta um retângulo o qual possui um ponto inicial em (x, y) e possui um w width(largura) e um h height(altura) dentro da tela(canvas), usando o estilo de traçado(stroke) atual.
+
+ +

Desenhando Textos

+ +

Os métodos seguintes são fornecidos para desenhar texto. Veja também o objeto {{domxref("TextMetrics")}} para propriedades de texto.

+ +
+
{{domxref("CanvasRenderingContext2D.fillText()")}}
+
Desenha(preenche) um texto fornecido, em uma posição fornecida(x,y).
+
{{domxref("CanvasRenderingContext2D.strokeText()")}}
+
Desenha(traçados) um texto fornecido, em uma posição fornecida(x,y).
+
{{domxref("CanvasRenderingContext2D.measureText()")}}
+
Retorna um objeto {{domxref("TextMetrics")}} .
+
+ +

Estilos de linha

+ +

Os seguintes métodos e propriedades, controlam como as linhas são desenhadas.

+ +
+
{{domxref("CanvasRenderingContext2D.lineWidth")}}
+
Largura das linhas. Padrão: 1.0
+
{{domxref("CanvasRenderingContext2D.lineCap")}}
+
Tipos de pontas no final das linhas. Valores possíveis: butt (padrão), round, square.
+
{{domxref("CanvasRenderingContext2D.lineJoin")}}
+
Define o tipo de encontro entre duas linhas. Possíveis valores: round, bevel, miter (default).
+
{{domxref("CanvasRenderingContext2D.miterLimit")}}
+
Relação do limite de esquadria. Padrão: 10.
+
{{domxref("CanvasRenderingContext2D.getLineDash()")}}
+
Retorna a matriz de padrão de traço de linha atual contendo um número par de números não negativos.
+
{{domxref("CanvasRenderingContext2D.setLineDash()")}}
+
Define o padrão de traço de linha atual.
+
{{domxref("CanvasRenderingContext2D.lineDashOffset")}}
+
Especifica onde iniciar uma matriz de traços em uma linha.
+
+ +

Estilos de textos

+ +

As propriedades abaixo controlam a estilização do texto a ser apresentado:

+ +
+
{{domxref("CanvasRenderingContext2D.font")}}
+
Configuração da fonte. Valor padrão: 10px sans-serif.
+
{{domxref("CanvasRenderingContext2D.textAlign")}}
+
Alinhamento do texto. Possíveis valores: start (padrão), end, left, right or center.
+
{{domxref("CanvasRenderingContext2D.textBaseline")}}
+
Configuração de alinhamento da linha de base (Baseline). Possíveis valores: top, hanging, middle, alphabetic (padrão), ideographic, bottom.
+
{{domxref("CanvasRenderingContext2D.direction")}}
+
Direção do texto. Possívels valores: ltr, rtl, inherit (padrão).
+
+ +

Estilos de preenchimento e traço

+ +

O estilo de preenchimento é usado para cores e estilos dentro das formas e o estilo de traço é usado para as linhas ao redor das formas.

+ +
+
{{domxref("CanvasRenderingContext2D.fillStyle")}}
+
Cor ou estilo para usar formas internas. Padrão #000 (preto).
+
{{domxref("CanvasRenderingContext2D.strokeStyle")}}
+
Cor ou estilo a ser usado para as linhas em torno das formas. Padrão: #000 (preto).
+
+ +

Gradientes e padrões

+ +
+
{{domxref("CanvasRenderingContext2D.createLinearGradient()")}}
+
Cria um gradiente linear ao longo da linha fornecida pelas coordenadas representadas pelos parâmetros.
+
{{domxref("CanvasRenderingContext2D.createRadialGradient()")}}
+
Cria um gradiente radial dado pelas coordenadas dos dois círculos representados pelos parâmetros.
+
{{domxref("CanvasRenderingContext2D.createPattern()")}}
+
Cria um padrão usando a imagem especificada (uma {{domxref("CanvasImageSource")}}). Ele repete a fonte nas direções especificadas pelo argumento de repetição. Este método retorna um {{domxref("CanvasPattern")}}.
+
+ +

Sombras

+ +
+
{{domxref("CanvasRenderingContext2D.shadowBlur")}}.
+
Especifica o efeito de desfoque. Padrão: 0.
+
{{domxref("CanvasRenderingContext2D.shadowColor")}}
+
Cor da sombra. Padrão: fully-transparent black (preto totalmente transparente).
+
{{domxref("CanvasRenderingContext2D.shadowOffsetX")}}
+
Distância horizontal em que a sombra será deslocada. Padrão: 0.
+
{{domxref("CanvasRenderingContext2D.shadowOffsetY")}}
+
Distância vertical em que a sombra será deslocada. Padrão: 0.
+
+ +

Caminhos

+ +

Os seguintes métodos podem ser usados para manipular caminhos de desenhos.

+ +
+
{{domxref("CanvasRenderingContext2D.beginPath()")}}
+
Inicia um novo caminho esvaziando a lista de subcaminhos. Chame esse método quando você quiser criar um novo caminho.
+
{{domxref("CanvasRenderingContext2D.closePath()")}}
+
Faz com que a ponta da caneta se mova de volta para o início do subcaminho atual. Ele tenta traçar uma linha reta do ponto atual ao início. Se o desenho já foi fechado ou tem apenas um ponto, este método não faz nada.
+
{{domxref("CanvasRenderingContext2D.moveTo()")}}
+
Move o ponto inicial de um novo subcaminho para as coordenadas (x, y).
+
{{domxref("CanvasRenderingContext2D.lineTo()")}}
+
Conecta o último ponto do caminho atual com as coordenadas (x, y) com linha reta.
+
{{domxref("CanvasRenderingContext2D.bezierCurveTo()")}}
+
Adiciona uma curva de Bézier ao caminho atual.
+
{{domxref("CanvasRenderingContext2D.quadraticCurveTo()")}}
+
Adiciona uma curva de Bézier quadrática ao caminho atual.
+
{{domxref("CanvasRenderingContext2D.arc()")}}
+
Adiciona um arco circular ao caminho atual.
+
{{domxref("CanvasRenderingContext2D.arcTo()")}}
+
Adiciona um arco no caminho atual com os pontos de controle e raio fornecidos, conectado ao ponto anterior por uma linha reta.
+
{{domxref("CanvasRenderingContext2D.ellipse()")}}
+
Adiciona um arco elíptico ao caminho atual.
+
{{domxref("CanvasRenderingContext2D.rect()")}}
+
Cria um caminho de retângulo na posição (x, y) com o tamanho determinado por width e height.
+
+ +

Drawing paths

+ +
+
{{domxref("CanvasRenderingContext2D.fill()")}}
+
Fills the subpaths with the current fill style.
+
{{domxref("CanvasRenderingContext2D.stroke()")}}
+
Strokes the subpaths with the current stroke style.
+
{{domxref("CanvasRenderingContext2D.drawFocusIfNeeded()")}}
+
If a given element is focused, this method draws a focus ring around the current path.
+
{{domxref("CanvasRenderingContext2D.scrollPathIntoView()")}}
+
Scrolls the current path or a given path into the view.
+
{{domxref("CanvasRenderingContext2D.clip()")}}
+
Creates a clipping path from the current sub-paths. Everything drawn after clip() is called appears inside the clipping path only. For an example, see Clipping paths in the Canvas tutorial.
+
{{domxref("CanvasRenderingContext2D.isPointInPath()")}}
+
Reports whether or not the specified point is contained in the current path.
+
{{domxref("CanvasRenderingContext2D.isPointInStroke()")}}
+
Reports whether or not the specified point is inside the area contained by the stroking of a path.
+
+ +

Transformações

+ +

Objects in the CanvasRenderingContext2D rendering context have a current transformation matrix and methods to manipulate it. The transformation matrix is applied when creating the current default path, painting text, shapes and {{domxref("Path2D")}} objects. The methods listed below remain for historical and compatibility reasons as {{domxref("SVGMatrix")}} objects are used in most parts of the API nowadays and will be used in the future instead.

+ +
+
{{domxref("CanvasRenderingContext2D.currentTransform")}}
+
Current transformation matrix ({{domxref("SVGMatrix")}} object).
+
{{domxref("CanvasRenderingContext2D.rotate()")}}
+
Adds a rotation to the transformation matrix. The angle argument represents a clockwise rotation angle and is expressed in radians.
+
{{domxref("CanvasRenderingContext2D.scale()")}}
+
Adds a scaling transformation to the canvas units by x horizontally and by y vertically.
+
{{domxref("CanvasRenderingContext2D.translate()")}}
+
Adds a translation transformation by moving the canvas and its origin x horzontally and y vertically on the grid.
+
{{domxref("CanvasRenderingContext2D.transform()")}}
+
Multiplies the current transformation matrix with the matrix described by its arguments.
+
{{domxref("CanvasRenderingContext2D.setTransform()")}}
+
Resets the current transform to the identity matrix, and then invokes the transform() method with the same arguments.
+
{{domxref("CanvasRenderingContext2D.resetTransform()")}} {{experimental_inline}}
+
Resets the current transform by the identity matrix.
+
+ +

Compositing

+ +
+
{{domxref("CanvasRenderingContext2D.globalAlpha")}}
+
Alpha value that is applied to shapes and images before they are composited onto the canvas. Default 1.0 (opaque).
+
{{domxref("CanvasRenderingContext2D.globalCompositeOperation")}}
+
With globalAlpha applied this sets how shapes and images are drawn onto the existing bitmap.
+
+ +

Desenhando imagens

+ +
+
{{domxref("CanvasRenderingContext2D.drawImage()")}}
+
Draws the specified image. This method is available in multiple formats, providing a great deal of flexibility in its use.
+
+ +

Manipulação de pixels

+ +

See also the {{domxref("ImageData")}} object.

+ +
+
{{domxref("CanvasRenderingContext2D.createImageData()")}}
+
Creates a new, blank {{domxref("ImageData")}} object with the specified dimensions. All of the pixels in the new object are transparent black.
+
{{domxref("CanvasRenderingContext2D.getImageData()")}}
+
Returns an {{domxref("ImageData")}} object representing the underlying pixel data for the area of the canvas denoted by the rectangle which starts at (sx, sy) and has an sw width and sh height.
+
{{domxref("CanvasRenderingContext2D.putImageData()")}}
+
Paints data from the given {{domxref("ImageData")}} object onto the bitmap. If a dirty rectangle is provided, only the pixels from that rectangle are painted.
+
+ +

Image smoothing

+ +
+
{{domxref("CanvasRenderingContext2D.imageSmoothingEnabled")}} {{experimental_inline}}
+
Image smoothing mode; if disabled, images will not be smoothed if scaled.
+
+ +

The canvas state

+ +

The CanvasRenderingContext2D rendering context contains a variety of drawing style states (attributes for line styles, fill styles, shadow styles, text styles). The following methods help you to work with that state:

+ +
+
{{domxref("CanvasRenderingContext2D.save()")}}
+
Saves the current drawing style state using a stack so you can revert any change you make to it using restore().
+
{{domxref("CanvasRenderingContext2D.restore()")}}
+
Restores the drawing style state to the last element on the 'state stack' saved by save().
+
{{domxref("CanvasRenderingContext2D.canvas")}}
+
A read-only back-reference to the {{domxref("HTMLCanvasElement")}}. Might be {{jsxref("null")}} if it is not associated with a {{HTMLElement("canvas")}} element.
+
+ +

Hit regions

+ +
+
{{domxref("CanvasRenderingContext2D.addHitRegion()")}} {{experimental_inline}}
+
Adds a hit region to the canvas.
+
{{domxref("CanvasRenderingContext2D.removeHitRegion()")}} {{experimental_inline}}
+
Removes the hit region with the specified id from the canvas.
+
{{domxref("CanvasRenderingContext2D.clearHitRegions()")}} {{experimental_inline}}
+
Removes all hit regions from the canvas.
+
+ +

Non-standard APIs

+ + + +

Most of these APIs are deprecated and will be removed in the future.

+ +
+
{{non-standard_inline}} CanvasRenderingContext2D.clearShadow()
+
Removes all shadow settings like {{domxref("CanvasRenderingContext2D.shadowColor")}} and {{domxref("CanvasRenderingContext2D.shadowBlur")}}.
+
{{non-standard_inline}} CanvasRenderingContext2D.drawImageFromRect()
+
This is redundant with an equivalent overload of drawImage.
+
{{non-standard_inline}} CanvasRenderingContext2D.setAlpha()
+
Use {{domxref("CanvasRenderingContext2D.globalAlpha")}} instead.
+
{{non-standard_inline}} CanvasRenderingContext2D.setCompositeOperation()
+
Use {{domxref("CanvasRenderingContext2D.globalCompositeOperation")}} instead.
+
{{non-standard_inline}} CanvasRenderingContext2D.setLineWidth()
+
Use {{domxref("CanvasRenderingContext2D.lineWidth")}} instead.
+
{{non-standard_inline}} CanvasRenderingContext2D.setLineJoin()
+
Use {{domxref("CanvasRenderingContext2D.lineJoin")}} instead.
+
{{non-standard_inline}} CanvasRenderingContext2D.setLineCap()
+
Use {{domxref("CanvasRenderingContext2D.lineCap")}} instead.
+
{{non-standard_inline}} CanvasRenderingContext2D.setMiterLimit()
+
Use {{domxref("CanvasRenderingContext2D.miterLimit")}} instead.
+
{{non-standard_inline}} CanvasRenderingContext2D.setStrokeColor()
+
Use {{domxref("CanvasRenderingContext2D.strokeStyle")}} instead.
+
{{non-standard_inline}} CanvasRenderingContext2D.setFillColor()
+
Use {{domxref("CanvasRenderingContext2D.fillStyle")}} instead.
+
{{non-standard_inline}} CanvasRenderingContext2D.setShadow()
+
Use {{domxref("CanvasRenderingContext2D.shadowColor")}} and {{domxref("CanvasRenderingContext2D.shadowBlur")}} instead.
+
{{non-standard_inline}} CanvasRenderingContext2D.webkitLineDash
+
Use {{domxref("CanvasRenderingContext2D.getLineDash()")}} and {{domxref("CanvasRenderingContext2D.setLineDash()")}} instead.
+
{{non-standard_inline}} CanvasRenderingContext2D.webkitLineDashOffset
+
Use {{domxref("CanvasRenderingContext2D.lineDashOffset")}} instead.
+
{{non-standard_inline}} CanvasRenderingContext2D.webkitImageSmoothingEnabled
+
Use {{domxref("CanvasRenderingContext2D.imageSmoothingEnabled")}} instead.
+
+ + + +
+
{{non-standard_inline}} CanvasRenderingContext2D.getContextAttributes()
+
Inspired by the same WebGLRenderingContext method it returns an Canvas2DContextAttributes object that contains the attributes "storage" to indicate which storage is used ("persistent" by default) and the attribute "alpha" (true by default) to indicate that transparency is used in the canvas.
+
{{non-standard_inline}} CanvasRenderingContext2D.isContextLost()
+
Inspired by the same WebGLRenderingContext method it returns true if the Canvas context has been lost, or false if not.
+
+ +

WebKit only

+ +
+
{{non-standard_inline}} CanvasRenderingContext2D.webkitBackingStorePixelRatio
+
The backing store size in relation to the canvas element. See High DPI Canvas.
+
{{non-standard_inline}} CanvasRenderingContext2D.webkitGetImageDataHD
+
Intended for HD backing stores, but removed from canvas specifications.
+
{{non-standard_inline}} CanvasRenderingContext2D.webkitPutImageDataHD
+
Intended for HD backing stores, but removed from canvas specifications.
+
+ +
+
+ +

Gecko only

+ +
+
{{non-standard_inline}} {{domxref("CanvasRenderingContext2D.filter")}}
+
CSS and SVG filters as Canvas APIs. Likely to be standardized in a new version of the specification.
+
+ +

Prefixed APIs

+ +
+
{{non-standard_inline}} CanvasRenderingContext2D.mozCurrentTransform
+
Sets or gets the current transformation matrix, see {{domxref("CanvasRenderingContext2D.currentTransform")}}.  {{ gecko_minversion_inline("7.0") }}
+
{{non-standard_inline}} CanvasRenderingContext2D.mozCurrentTransformInverse
+
Sets or gets the current inversed transformation matrix.  {{ gecko_minversion_inline("7.0") }}
+
{{non-standard_inline}} CanvasRenderingContext2D.mozFillRule
+
The fill rule to use. This must be one of evenodd or nonzero (default).
+
{{non-standard_inline}} CanvasRenderingContext2D.mozImageSmoothingEnabled
+
See {{domxref("CanvasRenderingContext2D.imageSmoothingEnabled")}}.
+
{{non-standard_inline}} {{deprecated_inline}} CanvasRenderingContext2D.mozDash
+
An array which specifies the lengths of alternating dashes and gaps {{ gecko_minversion_inline("7.0") }}. Use {{domxref("CanvasRenderingContext2D.getLineDash()")}} and {{domxref("CanvasRenderingContext2D.setLineDash()")}} instead.
+
{{non-standard_inline}} {{deprecated_inline}} CanvasRenderingContext2D.mozDashOffset
+
Specifies where to start a dash array on a line. {{ gecko_minversion_inline("7.0") }}. Use {{domxref("CanvasRenderingContext2D.lineDashOffset")}} instead.
+
{{non-standard_inline}} {{deprecated_inline}} CanvasRenderingContext2D.mozTextStyle
+
Introduced in in Gecko 1.9, deprecated in favor of the {{domxref("CanvasRenderingContext2D.font")}} property.
+
{{non-standard_inline}} {{obsolete_inline}} CanvasRenderingContext2D.mozDrawText()
+
This method was introduced in Gecko 1.9 and is removed starting with Gecko 7.0. Use {{domxref("CanvasRenderingContext2D.strokeText()")}} or {{domxref("CanvasRenderingContext2D.fillText()")}} instead.
+
{{non-standard_inline}} {{obsolete_inline}} CanvasRenderingContext2D.mozMeasureText()
+
This method was introduced in Gecko 1.9 and is unimplemented starting with Gecko 7.0. Use {{domxref("CanvasRenderingContext2D.measureText()")}} instead.
+
{{non-standard_inline}} {{obsolete_inline}} CanvasRenderingContext2D.mozPathText()
+
This method was introduced in Gecko 1.9 and is removed starting with Gecko 7.0.
+
{{non-standard_inline}} {{obsolete_inline}} CanvasRenderingContext2D.mozTextAlongPath()
+
This method was introduced in Gecko 1.9 and is removed starting with Gecko 7.0.
+
+ +

Internal APIs (chrome-context only)

+ +
+
{{non-standard_inline}} {{domxref("CanvasRenderingContext2D.asyncDrawXULElement()")}}
+
Renders a region of a XUL element into the canvas.
+
{{non-standard_inline}} {{domxref("CanvasRenderingContext2D.drawWindow()")}}
+
Renders a region of a window into the canvas. The contents of the window's viewport are rendered, ignoring viewport clipping and scrolling.
+
{{non-standard_inline}} CanvasRenderingContext2D.demote()
+
This causes a context that is currently using a hardware-accelerated backend to fallback to a software one. All state should be preserved.
+
+ +

Internet Explorer

+ +
+
{{non-standard_inline}} CanvasRenderingContext2D.msFillRule
+
The fill rule to use. This must be one of evenodd or nonzero (default).
+
+ +

Especificações

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "scripting.html#2dcontext:canvasrenderingcontext2d", "CanvasRenderingContext2D")}}{{Spec2('HTML WHATWG')}}
+ +

Compatibilidade do Navegador

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("1")}}{{CompatGeckoDesktop("1.8")}}{{CompatIE("9")}}{{CompatOpera("9")}}{{CompatSafari("2")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Compatibility notes

+ + + +

Veja também

+ + diff --git a/files/pt-br/web/api/canvasrenderingcontext2d/lineto/index.html b/files/pt-br/web/api/canvasrenderingcontext2d/lineto/index.html new file mode 100644 index 0000000000..1876b469a8 --- /dev/null +++ b/files/pt-br/web/api/canvasrenderingcontext2d/lineto/index.html @@ -0,0 +1,176 @@ +--- +title: CanvasRenderingContext2D.lineTo() +slug: Web/API/CanvasRenderingContext2D/lineTo +tags: + - API + - Canvas + - CanvasRenderingContext2D + - Referencia + - metodo +translation_of: Web/API/CanvasRenderingContext2D/lineTo +--- +
{{APIRef}}
+ +

O método CanvasRenderingContext2D.lineTo() da API Canvas 2D conecta o último ponto do sub-caminho (sub-path) para as coordenadas x, y, através de uma linha (mas na realidade não a desenha).

+ +

Sintaxe

+ +
void ctx.lineTo(x, y);
+
+ +

Parâmetros

+ +
+
x
+
O valor da coordenada x que indica o fim da linha.
+
y
+
O valor da coordenada y que indica o fim da linha.
+
+ +

Exemplos

+ +

Usando o método lineTo

+ +

sto é só um simples trecho de código que usa o método lineTo. Use o {{domxref("CanvasRenderingContext2D.beginPath", "beginPath()")}} para indicar o path onde será desenhada a linha, mova a caneta (pen) com {{domxref("CanvasRenderingContext.moveTo", "moveTo()")}} e use o método {{domxref("CanvasRenderingContext2D.stroke", "stroke()")}} para desenhar a linha.

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById('canvas');
+var ctx = canvas.getContext('2d');
+
+ctx.beginPath();
+ctx.moveTo(50, 50);
+ctx.lineTo(100, 100);
+ctx.stroke();
+
+ +

Edite o código abaixo e veja as alterações instantâneas no canvas:

+ +
+
Playable code
+ +
<canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas>
+<div class="playable-buttons">
+  <input id="edit" type="button" value="Edit" />
+  <input id="reset" type="button" value="Reset" />
+</div>
+<textarea id="code" class="playable-code">
+ctx.beginPath();
+ctx.moveTo(50,50);
+ctx.lineTo(100, 100);
+ctx.stroke();</textarea>
+
+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+var textarea = document.getElementById("code");
+var reset = document.getElementById("reset");
+var edit = document.getElementById("edit");
+var code = textarea.value;
+
+function drawCanvas() {
+  ctx.clearRect(0, 0, canvas.width, canvas.height);
+  eval(textarea.value);
+}
+
+reset.addEventListener("click", function() {
+  textarea.value = code;
+  drawCanvas();
+});
+
+edit.addEventListener("click", function() {
+  textarea.focus();
+})
+
+textarea.addEventListener("input", drawCanvas);
+window.addEventListener("load", drawCanvas);
+
+
+ +

{{ EmbedLiveSample('Playable_code', 700, 360) }}

+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('HTML WHATWG', "scripting.html#dom-context-2d-lineto", "CanvasRenderingContext2D.lineTo")}}{{Spec2('HTML WHATWG')}} 
+ +

Compatibilidade em Navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome para AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/canvasrenderingcontext2d/moveto/index.html b/files/pt-br/web/api/canvasrenderingcontext2d/moveto/index.html new file mode 100644 index 0000000000..137e4e2203 --- /dev/null +++ b/files/pt-br/web/api/canvasrenderingcontext2d/moveto/index.html @@ -0,0 +1,176 @@ +--- +title: CanvasRenderingContext2D.moveTo() +slug: Web/API/CanvasRenderingContext2D/moveTo +tags: + - API + - Canvas + - CanvasRenderingContext2D + - Referencia + - metodo +translation_of: Web/API/CanvasRenderingContext2D/moveTo +--- +
{{APIRef}}
+ +

O método CanvasRenderingContext2D.moveTo() da API Canvas 2D move o ponto inicial de um novo sub-caminho (sub-path) para as coordenadas (x, y).

+ +

Sintaxe

+ +
void ctx.moveTo(x, y);
+
+ +

Parâmetros

+ +
+
x
+
O valor da coordenada x.
+
y
+
O valor da coordenada y.
+
+ +

Exemplos

+ +

Usando o método moveTo

+ +

Isto é só um simples trecho de código que usa o método moveTo para mover a caneta (pen) para um deteminado ponto onde vai iniciar o desenho.

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById('canvas');
+var ctx = canvas.getContext('2d');
+
+ctx.beginPath();
+ctx.moveTo(50, 50);
+ctx.lineTo(200, 50);
+ctx.stroke();
+
+ +

Edite o código abaixo e veja as alterações instantâneas no canvas:

+ +
+
Playable code
+ +
<canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas>
+<div class="playable-buttons">
+  <input id="edit" type="button" value="Edit" />
+  <input id="reset" type="button" value="Reset" />
+</div>
+<textarea id="code" class="playable-code">
+ctx.beginPath();
+ctx.moveTo(50,50);
+ctx.lineTo(200, 50);
+ctx.stroke()</textarea>
+
+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+var textarea = document.getElementById("code");
+var reset = document.getElementById("reset");
+var edit = document.getElementById("edit");
+var code = textarea.value;
+
+function drawCanvas() {
+  ctx.clearRect(0, 0, canvas.width, canvas.height);
+  eval(textarea.value);
+}
+
+reset.addEventListener("click", function() {
+  textarea.value = code;
+  drawCanvas();
+});
+
+edit.addEventListener("click", function() {
+  textarea.focus();
+})
+
+textarea.addEventListener("input", drawCanvas);
+window.addEventListener("load", drawCanvas);
+
+
+ +

{{ EmbedLiveSample('Playable_code', 700, 360) }}

+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('HTML WHATWG', "scripting.html#dom-context-2d-moveto", "CanvasRenderingContext2D.moveTo")}}{{Spec2('HTML WHATWG')}} 
+ +

Compatibilidade em Navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome para AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/canvasrenderingcontext2d/quadraticcurveto/index.html b/files/pt-br/web/api/canvasrenderingcontext2d/quadraticcurveto/index.html new file mode 100644 index 0000000000..b60b7de07c --- /dev/null +++ b/files/pt-br/web/api/canvasrenderingcontext2d/quadraticcurveto/index.html @@ -0,0 +1,182 @@ +--- +title: CanvasRenderingContext2D.quadraticCurveTo() +slug: Web/API/CanvasRenderingContext2D/quadraticCurveTo +translation_of: Web/API/CanvasRenderingContext2D/quadraticCurveTo +--- +
{{APIRef}}
+ +

o método CanvasRenderingContext2D.quadraticCurveTo() da API Canvas 2D adiciona uma Curva de Bézier quadrática ao caminho. São exigidos dois pontos. O primeiro ponto é um ponto de controle e o segundo é o ponto final. The starting point is the last point in the current path, which can be changed using moveTo() before creating the quadratic Bézier curve.

+ +

Sintaxe

+ +
void ctx.quadraticCurveTo(cpx, cpy, x, y);
+
+ +

Parâmetros

+ +
+
cpx
+
O eixo X da coordenada para o ponto de controle.
+
cpy
+
O eixo Y da coordenada para o ponto de controle.
+
x
+
O eixo X da coordenada para o ponto final.
+
y
+
O eixo Y da coordenada para o ponto final.
+
+ +

Exemplos

+ +

Usando o método quadraticCurveTo

+ +

This is just a simple code snippet drawing a quadratic bezier curve. The control point is red and the start and end points are blue.

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById('canvas');
+var ctx = canvas.getContext('2d');
+
+ctx.beginPath();
+ctx.moveTo(50,20);
+ctx.quadraticCurveTo(230, 30, 50, 100);
+ctx.stroke();
+
+ctx.fillStyle = 'blue';
+// start point
+ctx.fillRect(50, 20, 10, 10);
+// end point
+ctx.fillRect(50, 100, 10, 10);
+
+ctx.fillStyle = 'red';
+// control point
+ctx.fillRect(230, 30, 10, 10);
+ +

{{ EmbedLiveSample('Using_the_quadraticCurveTo_method', 315, 165) }}

+ +

Trying the quadraticCurveTo parameters

+ +

Edit the code below and see your changes update live in the canvas:

+ +
+
<canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas>
+<div class="playable-buttons">
+  <input id="edit" type="button" value="Edit" />
+  <input id="reset" type="button" value="Reset" />
+</div>
+<textarea id="code" class="playable-code">
+ctx.beginPath();
+ctx.moveTo(50,20);
+ctx.quadraticCurveTo(230, 30, 50, 100);
+ctx.stroke();</textarea>
+
+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+var textarea = document.getElementById("code");
+var reset = document.getElementById("reset");
+var edit = document.getElementById("edit");
+var code = textarea.value;
+
+function drawCanvas() {
+  ctx.clearRect(0, 0, canvas.width, canvas.height);
+  eval(textarea.value);
+}
+
+reset.addEventListener("click", function() {
+  textarea.value = code;
+  drawCanvas();
+});
+
+edit.addEventListener("click", function() {
+  textarea.focus();
+})
+
+textarea.addEventListener("input", drawCanvas);
+window.addEventListener("load", drawCanvas);
+
+
+ +

{{ EmbedLiveSample('Trying_the_quadraticCurveTo_parameters', 700, 360) }}

+ +

Especificações

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "scripting.html#dom-context-2d-quadraticcurveto", "CanvasRenderingContext2D.quadraticCurveTo")}}{{Spec2('HTML WHATWG')}} 
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
{{CompatVersionUnknown}} + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
{{CompatVersionUnknown}} + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/canvasrenderingcontext2d/rect/index.html b/files/pt-br/web/api/canvasrenderingcontext2d/rect/index.html new file mode 100644 index 0000000000..6c19b38495 --- /dev/null +++ b/files/pt-br/web/api/canvasrenderingcontext2d/rect/index.html @@ -0,0 +1,177 @@ +--- +title: CanvasRenderingContext2D.rect() +slug: Web/API/CanvasRenderingContext2D/rect +tags: + - API + - Canvas + - CanvasRenderingContext2D + - Referencia + - metodo +translation_of: Web/API/CanvasRenderingContext2D/rect +--- +
{{APIRef}}
+ +

O método CanvasRenderingContext2D.rect() da Canvas 2D API cria um path (trajeto) para um retângulo na posição (x, y), cujo tamanho é determinado pelo width (largura) e height (altura). Esses quatro pontos estão conectados por linhas retas e o sub-path (sub-trajeto) é marcado como fechado, para que você possa fill (preencher) ou stroke (contornar) o retângulo.

+ +

Sintaxe

+ +
void ctx.rect(x, y, width, height);
+
+ +

Parameters

+ +
+
x
+
O valor da coordenada x que indica ponto de início (superior esquerdo) do retângulo.
+
y
+
O valor da coordenada y que indica ponto de início (superior esquerdo) do retângulo.
+
width
+
A largura do retângulo.
+
height
+
A altura do retângulo.
+
+ +

Exemplos

+ +

Usando o método rect

+ +

Isto é somente um simples fragmentode código que usa o método rect para criar um path. Para verdadeiramente desenhar um path no canvas, você pode usar o método {{domxref("CanvasRenderingContext2D.fill", "fill()")}} ou o {{domxref("CanvasRenderingContext2D.stroke", "stroke()")}}. Veja também os métodos {{domxref("CanvasRenderingContext2D.fillRect", "fillRect()")}} e {{domxref("CanvasRenderingContext2D.strokeRect", "strokeRect()")}}, que podem fazer isto em um único passo.

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById('canvas');
+var ctx = canvas.getContext('2d');
+ctx.rect(10, 10, 100, 100);
+ctx.fill();
+
+ +

Edite o código abaixo e veja as alterações instantâneas no canvas:

+ +
+
Playable code
+ +
<canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas>
+<div class="playable-buttons">
+  <input id="edit" type="button" value="Edit" />
+  <input id="reset" type="button" value="Reset" />
+</div>
+<textarea id="code" class="playable-code">
+ctx.rect(10, 10, 100, 100);
+ctx.fill();</textarea>
+
+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+var textarea = document.getElementById("code");
+var reset = document.getElementById("reset");
+var edit = document.getElementById("edit");
+var code = textarea.value;
+
+function drawCanvas() {
+  ctx.clearRect(0, 0, canvas.width, canvas.height);
+  eval(textarea.value);
+}
+
+reset.addEventListener("click", function() {
+  textarea.value = code;
+  drawCanvas();
+});
+
+edit.addEventListener("click", function() {
+  textarea.focus();
+})
+
+textarea.addEventListener("input", drawCanvas);
+window.addEventListener("load", drawCanvas);
+
+
+ +

{{ EmbedLiveSample('Playable_code', 700, 360) }}

+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('HTML WHATWG', "scripting.html#dom-context-2d-rect", "CanvasRenderingContext2D.rect")}}{{Spec2('HTML WHATWG')}} 
+ +

Compatibilidade em Navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/canvasrenderingcontext2d/stroke/index.html b/files/pt-br/web/api/canvasrenderingcontext2d/stroke/index.html new file mode 100644 index 0000000000..866e317383 --- /dev/null +++ b/files/pt-br/web/api/canvasrenderingcontext2d/stroke/index.html @@ -0,0 +1,187 @@ +--- +title: CanvasRenderingContext2D.stroke() +slug: Web/API/CanvasRenderingContext2D/stroke +tags: + - API + - Canvas + - CanvasRenderingContext2D + - Referencia + - metodo +translation_of: Web/API/CanvasRenderingContext2D/stroke +--- +
{{APIRef}}
+ +

O método CanvasRenderingContext2D.stroke() da API Canvas 2D contorna um dado path ou o path atual com o estilo atual de traçado usando uma regra de controle diferente de zero.

+ +

Sintaxe

+ +
void ctx.stroke();
+void ctx.stroke(path);
+
+ +

Parâmetros

+ +
+
path
+
Um path de {{domxref("Path2D")}} para contorno.
+
+ +

Exemplos

+ +

Usando o método stroke

+ +

Isto é só um simples trecho de código que usa o método stroke para contornar um path.

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById('canvas');
+var ctx = canvas.getContext('2d');
+ctx.rect(10, 10, 100, 100);
+ctx.stroke();
+
+ +

Edite o código abaixo e veja as alterações instantâneas no canvas:

+ +
+
Playable code
+ +
<canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas>
+<div class="playable-buttons">
+  <input id="edit" type="button" value="Edit" />
+  <input id="reset" type="button" value="Reset" />
+</div>
+<textarea id="code" class="playable-code">
+ctx.rect(10, 10, 100, 100);
+ctx.stroke();</textarea>
+
+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+var textarea = document.getElementById("code");
+var reset = document.getElementById("reset");
+var edit = document.getElementById("edit");
+var code = textarea.value;
+
+function drawCanvas() {
+  ctx.clearRect(0, 0, canvas.width, canvas.height);
+  eval(textarea.value);
+}
+
+reset.addEventListener("click", function() {
+  textarea.value = code;
+  drawCanvas();
+});
+
+edit.addEventListener("click", function() {
+  textarea.focus();
+})
+
+textarea.addEventListener("input", drawCanvas);
+window.addEventListener("load", drawCanvas);
+
+
+ +

{{ EmbedLiveSample('Playable_code', 700, 360) }}

+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('HTML WHATWG', "scripting.html#dom-context-2d-stroke", "CanvasRenderingContext2D.stroke")}}{{Spec2('HTML WHATWG')}} 
+ +

Compatibilidade em Navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
Suporte para o parâmetro path{{ CompatVersionUnknown() }}{{CompatVersionUnknown}}{{ CompatGeckoDesktop(31) }}{{ CompatNo }}{{ CompatVersionUnknown() }}{{ CompatNo }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome para AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
Suporte para o parâmetro path{{ CompatUnknown() }}{{ CompatUnknown() }}{{CompatVersionUnknown}}{{ CompatGeckoMobile(31) }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/canvasrenderingcontext2d/strokerect/index.html b/files/pt-br/web/api/canvasrenderingcontext2d/strokerect/index.html new file mode 100644 index 0000000000..e11812857f --- /dev/null +++ b/files/pt-br/web/api/canvasrenderingcontext2d/strokerect/index.html @@ -0,0 +1,177 @@ +--- +title: CanvasRenderingContext2D.strokeRect() +slug: Web/API/CanvasRenderingContext2D/strokeRect +tags: + - API + - Canvas + - CanvasRenderingContext2D + - Referencia + - metodo +translation_of: Web/API/CanvasRenderingContext2D/strokeRect +--- +
{{APIRef}}
+ +

O método CanvasRenderingContext2D.strokeRect() da API Canvas 2D desenha um retângulo na posição (x, y), que possui uma largura (width) w e uma altura (height) h, e não tem nenhum preenchimento (estilo stroke).

+ +

Sintaxe

+ +
void ctx.strokeRect(x, y, width, height);
+
+ +

Parâmetros

+ +
+
x
+
O valor da coordenada x para o ponto inicial do retângulo.
+
y
+
O valor da coordenada y para o ponto inicial do retângulo.
+
width
+
A largura do retângulo.
+
height
+
A altura do retângulo.
+
+ +

Exemplos

+ +

Usando o método strokeRect

+ +

Isto é só um simples trecho de código que usa o método strokeRect.

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +
var canvas = document.getElementById('canvas');
+var ctx = canvas.getContext('2d');
+
+ctx.strokeStyle = 'green';
+ctx.strokeRect(10, 10, 100, 100);
+
+ +

Edite o código abaixo e veja as alterações instantâneas no canvas:

+ +
+
Playable code
+ +
<canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas>
+<div class="playable-buttons">
+  <input id="edit" type="button" value="Edit" />
+  <input id="reset" type="button" value="Reset" />
+</div>
+<textarea id="code" class="playable-code">
+ctx.strokeStyle = "green";
+ctx.strokeRect(10, 10, 100, 100);</textarea>
+
+ +
var canvas = document.getElementById("canvas");
+var ctx = canvas.getContext("2d");
+var textarea = document.getElementById("code");
+var reset = document.getElementById("reset");
+var edit = document.getElementById("edit");
+var code = textarea.value;
+
+function drawCanvas() {
+  ctx.clearRect(0, 0, canvas.width, canvas.height);
+  eval(textarea.value);
+}
+
+reset.addEventListener("click", function() {
+  textarea.value = code;
+  drawCanvas();
+});
+
+edit.addEventListener("click", function() {
+  textarea.focus();
+})
+
+textarea.addEventListener("input", drawCanvas);
+window.addEventListener("load", drawCanvas);
+
+
+ +

{{ EmbedLiveSample('Playable_code', 700, 360) }}

+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('HTML WHATWG', "scripting.html#dom-context-2d-strokerect", "CanvasRenderingContext2D.strokeRect")}}{{Spec2('HTML WHATWG')}} 
+ +

Compatibilidade em Navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome para AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/characterdata/index.html b/files/pt-br/web/api/characterdata/index.html new file mode 100644 index 0000000000..8eb415f6e3 --- /dev/null +++ b/files/pt-br/web/api/characterdata/index.html @@ -0,0 +1,94 @@ +--- +title: CharacterData +slug: Web/API/CharacterData +translation_of: Web/API/CharacterData +--- +

{{APIRef("DOM")}}

+ +

A interface abstrata CharacterData  representa um objeto {{domxref("Node")}} que contém caracteres. Esta é uma interface abstrata, o que significa que não há nenhum objeto do tipo CharacterData: ela é implementada por outras interfaces, como {{domxref("Text")}}, {{domxref("Comment")}} ou {{domxref("ProcessingInstruction")}}, que não são abstratas.

+ +

{{InheritanceDiagram}}

+ +

Propriedades

+ +

Herda propriedades de seu pai, {{domxref("Node")}}, e implementa as interfaces {{domxref("ChildNode")}} e {{domxref("NonDocumentTypeChildNode")}}.

+ +
+
{{domxref("CharacterData.data")}}
+
É um {{domxref("DOMString")}} representando os dados textuais contidos neste objeto.
+
{{domxref("CharacterData.length")}} {{readonlyInline}}
+
Retorna um unsigned long representando o tamanho da string contida em CharacterData.data.
+
{{domxref("NonDocumentTypeChildNode.nextElementSibling")}} {{readonlyInline}}
+
Returns the {{domxref("Element")}} immediately following the specified one in its parent's children list, or null if the specified element is the last one in the list.
+
{{domxref("NonDocumentTypeChildNode.previousElementSibling")}} {{readonlyInline}}
+
Returns the {{domxref("Element")}} immediately prior to the specified one in its parent's children list, or null if the specified element is the first one in the list.
+
+ +

Methods

+ +

Inherits methods from its parent, {{domxref("Node")}}, and implements the {{domxref("ChildNode")}} and {{domxref("NonDocumentTypeChildNode")}} interface.

+ +
+
{{domxref("CharacterData.appendData()")}}
+
Appends the given {{domxref("DOMString")}} to the CharacterData.data string; when this method returns, data contains the concatenated {{domxref("DOMString")}}.
+
{{domxref("CharacterData.deleteData()")}}
+
Removes the specified amount of characters, starting at the specified offset, from the CharacterData.data string; when this method returns, data contains the shortened {{domxref("DOMString")}}.
+
{{domxref("CharacterData.insertData()")}}
+
Inserts the specified characters, at the specified offset, in the CharacterData.data string; when this method returns, data contains the modified {{domxref("DOMString")}}.
+
{{domxref("ChildNode.remove()")}} {{experimental_inline}}
+
Removes the object from its parent children list.
+
{{domxref("CharacterData.replaceData()")}}
+
Replaces the specified amount of characters, starting at the specified offset, with the specified {{domxref("DOMString")}}; when this method returns, data contains the modified {{domxref("DOMString")}}.
+
{{domxref("CharacterData.substringData()")}}
+
Returns a {{domxref("DOMString")}} containing the part of CharacterData.data of the specified length and starting at the specified offset.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#characterdata', 'CharacterData')}}{{Spec2('DOM WHATWG')}}Added implemention of the {{domxref("ChildNode")}} and {{domxref("NonDocumentTypeChildNode")}} interface.
{{SpecName('DOM3 Core', 'core.html#ID-FF21A306', 'CharacterData')}}{{Spec2('DOM3 Core')}}No change from {{SpecName('DOM2 Core')}}.
{{SpecName('DOM2 Core', 'core.html#ID-FF21A306', 'CharacterData')}}{{Spec2('DOM2 Core')}}No change from {{SpecName('DOM1')}}.
{{SpecName('DOM1', 'level-one-core.html#ID-FF21A306', 'CharacterData')}}{{Spec2('DOM1')}}Initial definition.
+ +

Browser compatibility

+ + + +

 

+ +

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

+ +

See also

+ +

 

+ + diff --git a/files/pt-br/web/api/childnode/after/index.html b/files/pt-br/web/api/childnode/after/index.html new file mode 100644 index 0000000000..8d8d40df47 --- /dev/null +++ b/files/pt-br/web/api/childnode/after/index.html @@ -0,0 +1,187 @@ +--- +title: ChildNode.after() +slug: Web/API/ChildNode/after +tags: + - API + - DOM + - Experimental + - Nó + - Referencia + - metodo +translation_of: Web/API/ChildNode/after +--- +
{{APIRef("DOM")}} {{SeeCompatTable}}
+ +

The ChildNode.after() method inserts a set of {{domxref("Node")}} or {{domxref("DOMString")}} objects in the children list of this ChildNode's parent, just after this ChildNode. {{domxref("DOMString")}} objects are inserted as equivalent {{domxref("Text")}} nodes.

+ +

Sintaxe

+ +
[Throws, Unscopable]
+void ChildNode.after((Node or DOMString)... nodes);
+
+ +

Parâmetros

+ +
+
nós
+
A set of {{domxref("Node")}} or {{domxref("DOMString")}} objects to insert.
+
+ +

Exceções

+ + + +

Exemplos

+ +

Inserindo uum elemento

+ +
var parente = document.createElement("div");
+var filho = document.createElement("p");
+parente.appendChild(filho);
+var span = document.createElement("span");
+
+filho.after(span);
+
+console.log(parente.outerHTML);
+// "<div><p></p><span></span></div>"
+
+ +

Inserindo texto

+ +
var parente = document.createElement("div");
+var filho = document.createElement("p");
+parente.appendChild(filho);
+
+filho.after("Text");
+
+console.log(parente.outerHTML);
+// "<div><p></p>Text</div>"
+ +

Inserindo um elemento e um texto 

+ +
var parente = document.createElement("div");
+var filho = document.createElement("p");
+parente.appendChild(filho);
+var span = document.createElement("span");
+
+filho.after(span, "Text");
+
+console.log(parente.outerHTML);
+// "<div><p></p><span></span>Text</div>"
+ +

ChildNode.after() is unscopable

+ +

The after() method is not scoped into the with statement. Veja {{jsxref("Symbol.unscopables")}} para maior infomação.

+ +
with(node) {
+  after("foo");
+}
+// ReferenceError: after is not defined 
+ +

Polyfill

+ +

Você pode usar polyfill com  o método  after()  no Internet Explorer 9 e com o seguinte código:

+ +
//from: https://github.com/jserz/js_piece/blob/master/DOM/ChildNode/after()/after().md
+(function (arr) {
+  arr.forEach(function (item) {
+    if (item.hasOwnProperty('after')) {
+      return;
+    }
+    Object.defineProperty(item, 'after', {
+      configurable: true,
+      enumerable: true,
+      writable: true,
+      value: function after() {
+        var argArr = Array.prototype.slice.call(arguments),
+          docFrag = document.createDocumentFragment();
+
+        argArr.forEach(function (argItem) {
+          var isNode = argItem instanceof Node;
+          docFrag.appendChild(isNode ? argItem : document.createTextNode(String(argItem)));
+        });
+
+        this.parentNode.insertBefore(docFrag, this.nextSibling);
+      }
+    });
+  });
+})([Element.prototype, CharacterData.prototype, DocumentType.prototype]);
+ +

 

+ +
//https://github.com/FabioVergani/js-Polyfill_Element.prototype.after/blob/master/after.js
+
+(function(x){
+ var o=x.prototype,p='after';
+ if(!o[p]){
+    o[p]=function(){
+     var e, m=arguments, l=m.length, i=0, t=this, p=t.parentNode, n=Node, s=String, d=document;
+     if(p!==null){
+        while(i<l){
+         e=m[i];
+         if(e instanceof n){
+            t=t.nextSibling;
+            if(t!==null){
+                p.insertBefore(e,t);
+            }else{
+                p.appendChild(e);
+            };
+         }else{
+            p.appendChild(d.createTextNode(s(e)));
+         };
+         ++i;
+        };
+     };
+    };
+ };
+})(Element);
+
+
+
+/*
+min:
+
+(function(x){
+ var o=x.prototype;
+ o.after||(o.after=function(){var e,m=arguments,l=m.length,i=0,t=this,p=t.parentNode,n=Node,s=String,d=document;if(p!==null){while(i<l){((e=m[i]) instanceof n)?(((t=t.nextSibling )!==null)?p.insertBefore(e,t):p.appendChild(e)):p.appendChild(d.createTextNode(s(e)));++i;}}});
+}(Element));
+
+*/
+
+ +

 

+ +

Especificação

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('DOM WHATWG', '#dom-childnode-after', 'ChildNode.after()')}}{{Spec2('DOM WHATWG')}}Initial definition.
+ + + + + +

{{Compat("api.ChildNode.after")}}

+ +

Veja mais

+ + diff --git a/files/pt-br/web/api/childnode/index.html b/files/pt-br/web/api/childnode/index.html new file mode 100644 index 0000000000..a5bb9c280c --- /dev/null +++ b/files/pt-br/web/api/childnode/index.html @@ -0,0 +1,78 @@ +--- +title: ChildNode +slug: Web/API/ChildNode +tags: + - API + - DOM + - Experimental + - Interface + - NeedsTranslation + - Node + - TopicStub +translation_of: Web/API/ChildNode +--- +
{{APIRef("DOM")}}
+ +
A interface ChildNode contém métodos que são particulares para os objetos
+ +

{{domxref("Node")}} que podem ter um pai.

+ +

ChildNode é uma interface bruta e nenhum objeto desse tipo pode ser criado; eles são implementados pelos objetos {{domxref("Element")}}, {{domxref("DocumentType")}}, e {{domxref("CharacterData")}}.

+ +

Propriedades

+ +

Não há propriedades herdadas nem específicas.

+ +

Métodos

+ +

Não há métodos herdados.

+ +
+
{{domxref("ChildNode.remove()")}} {{experimental_inline}}
+
Removes this ChildNode from the children list of its parent.
+
{{domxref("ChildNode.before()")}} {{experimental_inline}}
+
Inserts a set of {{domxref("Node")}} or {{domxref("DOMString")}} objects in the children list of this ChildNode's parent, just before this ChildNode. {{domxref("DOMString")}} objects are inserted as equivalent {{domxref("Text")}} nodes.
+
{{domxref("ChildNode.after()")}} {{experimental_inline}}
+
Inserts a set of {{domxref("Node")}} or {{domxref("DOMString")}} objects in the children list of this ChildNode's parent, just after this ChildNode. {{domxref("DOMString")}} objects are inserted as equivalent {{domxref("Text")}} nodes.
+
{{domxref("ChildNode.replaceWith()")}} {{experimental_inline}}
+
Replaces this ChildNode in the children list of its parent with a set of {{domxref("Node")}} or {{domxref("DOMString")}} objects. {{domxref("DOMString")}} objects are inserted as equivalent {{domxref("Text")}} nodes.
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('DOM WHATWG', '#interface-childnode', 'ChildNode')}}{{Spec2('DOM WHATWG')}}Split the ElementTraversal interface in {{domxref("ParentNode")}} and ChildNode. previousElementSibling and nextElementSibling are now defined on the latter. The {{domxref("CharacterData")}} and {{domxref("DocumentType")}} implemented the new interfaces. Added the remove(), before(), after() and replaceWith() methods.
{{SpecName('Element Traversal', '#interface-elementTraversal', 'ElementTraversal')}}{{Spec2('Element Traversal')}}Added the initial definition of its properties to the ElementTraversal pure interface and use it on {{domxref("Element")}}.
+ +

Polyfill

+ +

External on github: childNode.js

+ +

Compatibilidade Com Navegadores

+ +

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

+ +

See also

+ + diff --git a/files/pt-br/web/api/childnode/remove/index.html b/files/pt-br/web/api/childnode/remove/index.html new file mode 100644 index 0000000000..98fba11b93 --- /dev/null +++ b/files/pt-br/web/api/childnode/remove/index.html @@ -0,0 +1,100 @@ +--- +title: ChildNode.remove() +slug: Web/API/ChildNode/remove +tags: + - API + - ChildNode + - DOM + - Experimental + - Método(2) + - remove +translation_of: Web/API/ChildNode/remove +--- +
{{APIRef("DOM")}}
+ +

O método ChildNode.remove() remove o objeto da árvore a que ele pertence.

+ +

Sintase

+ +
elementNodeReference.remove();
+
+ +

Exemplo

+ +

Usando remove()

+ +
<div id="div-01">Here is div-01</div>
+<div id="div-02">Here is div-02</div>
+<div id="div-03">Here is div-03</div>
+
+ +
var el = document.getElementById('div-01');
+el.nextElementSibling.remove(); // Remove o div com o id 'div-02'
+
+ +

ChildNode.remove() não tem escopo

+ +

O método remove() não tem escopo na função with. Veja {{jsxref("Symbol.unscopables")}} para mais informação.

+ +
with(node) {
+  remove();
+}
+// ReferenceError: remove is not defined 
+ +

Polyfill

+ +

Você pode evitar incompatibilidade ao usar o método remove() no Internet Explorer 9 em diante com o seguinte código:

+ +
// de: https://github.com/jserz/js_piece/blob/master/DOM/ChildNode/remove()/remove().md
+(function (arr) {
+  arr.forEach(function (item) {
+    if (item.hasOwnProperty('remove')) {
+      return;
+    }
+    Object.defineProperty(item, 'remove', {
+      configurable: true,
+      enumerable: true,
+      writable: true,
+      value: function remove() {
+        this.parentNode.removeChild(this);
+      }
+    });
+  });
+})([Element.prototype, CharacterData.prototype, DocumentType.prototype]);
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + +
EspecificaçãoSituaçãoComentário
{{SpecName('DOM WHATWG', '#dom-childnode-remove', 'ChildNode.remove')}}{{Spec2('DOM WHATWG')}}Definição Inicial.
{{SpecName('DOM4', '#dom-childnode-remove', 'ChildNode.remove')}}{{Spec2('DOM4')}} 
+ +

Compatibilidade de navegadores

+ +
{{Compat("api.ChildNode.remove")}}
+ +

 

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/clipboardevent/index.html b/files/pt-br/web/api/clipboardevent/index.html new file mode 100644 index 0000000000..ca14f4478f --- /dev/null +++ b/files/pt-br/web/api/clipboardevent/index.html @@ -0,0 +1,59 @@ +--- +title: ClipboardEvent +slug: Web/API/ClipboardEvent +translation_of: Web/API/ClipboardEvent +--- +

{{APIRef("Clipboard API")}} {{SeeCompatTable}}

+ +

A interface ClipboardEvent representa eventos correlatos à modificação da área de transferência, i. e., eventos de cortar ({{event("cut")}}), de copiar ({{event("copy")}}), e de colar ({{event("paste")}}).

+ +

Construtor

+ +
+
{{domxref("ClipboardEvent.ClipboardEvent", "ClipboardEvent()")}}
+
Cria um evento ClipboardEvent com os parâmetros fornecidos.
+
+ +

Propriedades

+ +

Ainda, propriedades herdadas de sua superclasse {{domxref("Event")}}.

+ +
+
{{domxref("ClipboardEvent.clipboardData")}} {{readonlyInline}}
+
é um objeto {{domxref("DataTransfer")}} contendo informação oriunda das operações de {{event("cut")}}, de {{event("copy")}}, ou de {{event("paste")}} iniciadas pelo usuário, juntamente com sua espécie/tipo MIME.
+
+ +

Methods

+ +

Não há método próprio; métodos herdados de {{domxref("Event")}}.

+ +

Especificações

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('Clipboard API', '#clipboard-event-interfaces', 'ClipboardEvent') }}{{ Spec2('Clipboard API') }}Definição inicial
+ + + + + +

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

+ +

See also

+ + diff --git a/files/pt-br/web/api/closeevent/closeevent/index.html b/files/pt-br/web/api/closeevent/closeevent/index.html new file mode 100644 index 0000000000..d5b7f088c0 --- /dev/null +++ b/files/pt-br/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 uma nova instância {{domxref("CloseEvent")}}.

+ +

Sintaxe

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

Valores

+ +
+
typeArg
+
É uma {{domxref("DOMString")}} que representa o nome do evento.
+
closeEventInit {{optional_inline}}
+
+ +
+
É uma coleção CloseEventInit, que possui os seguintes campos: + +
    +
  • "wasClean", opcional e inicialmente de valor false, do tipo long, indica se uma conexão foi encerrada de forma limpa ou não.
  • +
  • "code", opcional e inicialmente de valor 0, do tipo unsigned short, este é o código de encerramento da conexão enviado pelo servidor.
  • +
  • "reason", opcional e inicialmente de valor '', do tipo {{domxref("DOMString")}}, esta é uma razão humanamente compreensível do porque o servidor encerrou a conexão.
  • +
+ +
+

A coleção CloseEventInit também aceita campos vindos da coleção {{domxref("Event.Event", "EventInit")}}.

+
+
+
+ +

Especificações

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

Compatibilidade de navegadores

+ + + +

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

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/closeevent/index.html b/files/pt-br/web/api/closeevent/index.html new file mode 100644 index 0000000000..94f718e8b2 --- /dev/null +++ b/files/pt-br/web/api/closeevent/index.html @@ -0,0 +1,239 @@ +--- +title: CloseEvent +slug: Web/API/CloseEvent +translation_of: Web/API/CloseEvent +--- +

{{APIRef("Websockets API")}}

+ +

Um CloseEvent é enviado aos clientes que usam {{Glossary("WebSockets")}} quando a conexão está fechada (closed). Ele é enviado ao ouvinte(listener) pelo atributo onclose do objeto WebSocket.

+ +

Construtor

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

Propriedades

+ +

Esta interface também herda as propriedades de seu objeto pai, {{domxref("Event")}}.

+ +
+
{{domxref("CloseEvent.code")}} {{readOnlyInline}}
+
Retorna um valor unsigned short contendo o código de encerramento enviado pelo servidor. Os seguintes valores são status de códigos permitidos. As definições seguintes são originadas da página da IANA [Ref]. Observe que os códigos 1xxx são exclusivamente Websockets internos e não para os mesmos propósitos dos dados enviados (como quando o protocolo da camada de aplicação é invalido). Os únicos códigos que permitem especificação no Firefox são o 1000 e do 3000 ao 4999 [Source, Bug]. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Código de StatusNomeDescrição
0999Reservado e não utilizado.
1000CLOSE_NORMALEncerramento normal. A conexão foi completada com sucesso sempre que o propósito para o qual ela foi criada tenha sido atingida.
1001CLOSE_GOING_AWAYO "endpoint" desapareceu, por causa de uma falha no servidor ou por que o navegador navegou para fora da página que abriu a conexão.
1002CLOSE_PROTOCOL_ERRORO "endpoint" finalizou a conexão devido a um erro de protocolo.
1003CLOSE_UNSUPPORTEDA conexão está sendo finalizada por causa de o dado do "endpoint" recebido ser de um tipo que não pode ser aceito (por exemplo, um "text-only endpoint" recebido como dado binário).
1004Reservado. Um significado pode ser definido futuramente.
1005CLOSE_NO_STATUSReservado.  Indica que um código "no status" foi fornecido mesmo que qualquer outro código seja esperado.
1006CLOSE_ABNORMALReservado. Usado para indicar que uma conexão foi fechada anormalmente (isto é, sem o "close frame" ter sido enviado) quando um "status code" é esperado.
1007Unsupported DataO "endpoint" está finalizando a conexão por causa da mensagem ter sido recebida com dados inconsistentes (por exemplo, dados que não estejam no padrão UTF-8, dentro de uma mensagem de texto).
1008Policy ViolationO "endpoint" está finalizando a conexão por causa dele ter recebido uma mensagem que viola sua política. Este é um código de status genérico, usado quando o código 1003 e o código 1009 não sejam adequados.
1009CLOSE_TOO_LARGEO "endpoint" está finalizando a conexão por causa de que o "data frame" recebido é muito grande.
1010Missing ExtensionO cliente está fechando a conexão por causa de que navegador espera o servidor negociar uma ou mais extensões esperadas, o servidor não responde corretamente.
1011Internal ErrorO servidor está finalizando uma conexão por causa de que ele encontrou uma condição inesperada que o impediu de cumprir a solicitação.
1012Service Restart +

O servidor está finalizando uma conexão por que ele está em processo de "restar". [Ref]

+
1013Try Again Later +

O servidor está finalizando a conexão devido a uma condição temporária, por exemplo, ele estar sobrecarregado e estar rejeitando alguns dos seus clientes. [Ref]

+
1014Reservado para o futuro uso de um padrão WebSocket.
1015TLS Handshake +

Reservado. Indica que a conexão foi fechada devido a uma falha para executar um " TLS handshake" (por exemplo, o certificado do servidor não pode ser verificado).

+
10161999Reservado para o futuro uso de um padrão WebSocket.
20002999Reservado para uso de "WebSocket extensions".
30003999 +

Disponível para uso de bibliotecas e frameworks. Não pode ser usado para aplicações. Disponível para registro em "IANA via first-come, first-serve".

+
40004999Disponível para uso em aplicações.
+
+
{{domxref("CloseEvent.reason")}} {{readOnlyInline}}
+
Retorna um {{domxref("DOMString")}} indicando a razão do porquê o servidor fechou uma conexão. Isto é especifico para um servidor e sub-protocolo particular.
+
{{domxref("CloseEvent.wasClean")}} {{readOnlyInline}}
+
Retorna um {{jsxref("Boolean")}} indicando se a conexão está ou não está claramente fechada.
+
+ +

Métodos

+ +

Esta interface também herda as propriedades de seu objeto pai, {{domxref("Event")}}.

+ +
+
{{domxref("CloseEvent.initCloseEvent()")}} {{Non-standard_inline}} {{Obsolete_inline}}
+
Inicializa o valor de um CloseEvent criado. Se o evento já tenha sido enviado, este método não realiza nada.  Não use este método mais, use o construtor {{domxref("CloseEvent.CloseEvent", "CloseEvent()")}} em vez disso.
+
+ +

Compatibilidade nos navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatUnknown}}{{CompatGeckoDesktop("8.0")}}[1]
+ {{CompatGeckoDesktop("12.0")}}[2]
10{{CompatUnknown}}{{CompatUnknown}}
initCloseEvent() {{Non-standard_inline}}{{CompatNo}}{{CompatGeckoDesktop("8.0")}}
+ {{CompatNo}} 41.0
{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatGeckoMobile("8.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
initCloseEvent() {{Non-standard_inline}}{{CompatNo}}{{CompatGeckoMobile("8.0")}}
+ {{CompatNo}} 41.0
{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] Anterior ao Gecko 8.0 {{geckoRelease("8.0")}}, o Gecko envia o evento WebSocket {{event("close")}}  ao ouvinte como um evento simples. O suporte para o CloseEvent foi implementado no Gecko 8.0.

+ +

[2] Anterior ao Gecko 12.0 {{geckoRelease("12.0")}}, o Gecko reportava o código de encerramento CLOSE_NORMAL quando o canal se fechava devido a um erro inesperado, ou se a condição de erro não era coberta pela especificação. Agora CLOSE_GOING_AWAY é reportado em seu lugar.

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/console/assert/index.html b/files/pt-br/web/api/console/assert/index.html new file mode 100644 index 0000000000..571815d791 --- /dev/null +++ b/files/pt-br/web/api/console/assert/index.html @@ -0,0 +1,148 @@ +--- +title: Console.assert() +slug: Web/API/Console/assert +translation_of: Web/API/console/assert +--- +
{{APIRef("Console API")}}
+ +

Escreve uma mensagem de erro para o console se a afirmação é falsa. Se a firmação é verdadeira, nada acontece.

+ +

{{AvailableInWorkers}}

+ +
+

Note: O método console.assert() é implementado de forma diferente em Node.js.
+ Especificamente, em navegadores, chamando o método console.assert() com uma afirmação falsa fará com que a mensagem a ser impressa para o console não interrompa a execução do código subsequente. Em Node.js, no entanto, uma afirmação falsa causará um AssertionError.

+
+ +

Sintaxe

+ +
console.assert(afirmação, obj1 [, obj2, ..., objN]);
+console.assert(afirmação, msg [, subst1, ..., substN]); // c-mensagem de formatação
+
+ +

Parâmetros

+ +
+
afirmação
+
Qualquer expressão booleana. Se a afirmação é falsa, a mensagem é impressa no console.
+
obj1 ... objN
+
Uma lista de objetos JavaScript para escrever. As representações de strings de cada um desses objetos são acrescentados juntos na ordem dada e saída.
+
msg
+
Uma String que contém zero ou mais seguências de substituição.
+
subst1 ... substN
+
Objetos JavaScript com qual as strings de substituição msg serão substituidas. Isto dá um contriole adicional sobre a mensagem que será escrita.
+
+ +

Ver Outputting text to the console na documentação do {{domxref("console")}} para mais detalhes.

+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçõesStatusComentário
{{SpecName("Console API", "#consoleassertexpression-object", "console.assert()")}}{{Spec2("Console API")}}Initial definition
+ +

Compatibilidade entre os navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte Básico{{CompatVersionUnknown}}{{CompatGeckoDesktop("28.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+

Disponível para trabalhadores

+
{{CompatVersionUnknown}}{{CompatGeckoDesktop("38.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
c-like message formatting{{CompatNo}}{{CompatGeckoDesktop("28.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatUnknown}}{{CompatGeckoMobile("28.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Disponível para trabalhadores{{CompatUnknown}}{{CompatGeckoMobile("38.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
c-like message formatting{{CompatUnknown}}{{CompatGeckoMobile("28.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Ver também

+ + diff --git a/files/pt-br/web/api/console/clear/index.html b/files/pt-br/web/api/console/clear/index.html new file mode 100644 index 0000000000..f7ae8df40f --- /dev/null +++ b/files/pt-br/web/api/console/clear/index.html @@ -0,0 +1,38 @@ +--- +title: console.clear() +slug: Web/API/Console/clear +translation_of: Web/API/Console/clear +--- +
{{APIRef("Console API")}}
+ +

O método console.clear() limpa o console, se o ambiente permitir.

+ +

Sintaxe

+ +
console.clear();
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Console API", "#clear", "console.clear()")}}{{Spec2("Console API")}}Initial definition
+ +

Compatibilidade de Browser

+ + + +

{{Compat("api.Console.clear")}}

diff --git a/files/pt-br/web/api/console/count/index.html b/files/pt-br/web/api/console/count/index.html new file mode 100644 index 0000000000..b9328b5e91 --- /dev/null +++ b/files/pt-br/web/api/console/count/index.html @@ -0,0 +1,168 @@ +--- +title: Console.count() +slug: Web/API/Console/count +translation_of: Web/API/Console/count +--- +
{{APIRef("Console API")}}
+ +

Exibe o número de vezes em que a chamada count() em particular foi invocada. Essa função recebe um argumento opcional label.

+ +

{{AvailableInWorkers}}

+ +

Se label é fornecido, essa função exibe o número de vezes que a função count() foi chamada com a respectiva label.

+ +

Se label for omitido, a função exibe o número de vezes que a função count() foi chamada na respectiva linha.

+ +

Por exemplo, no código abaixo:

+ +
var usuario = "";
+
+function cumprimentar() {
+  console.count();
+  return "olá " + usuario;
+}
+
+usario = "bob";
+cumprimentar();
+usario = "alice";
+cumprimentar();
+cumprimentar();
+console.count();
+ +

A saída do console será algo como:

+ +
"<no label>: 1"
+"<no label>: 2"
+"<no label>: 3"
+"<no label>: 1"
+
+ +

Note a última linha da saída do console: a chamada individual de count() na linha 11 é tratada como um evento independente.

+ +

Se passarmos a variável usuario como o argumento label para a primeira invocação de count(), e a string "alice" para a segunda:

+ +
var usuario = "";
+
+function cumprimentar() {
+  console.count(usuario);
+  return "olá " + usuario;
+}
+
+usuario = "bob";
+cumprimentar();
+usuario = "alice";
+cumprimentar();
+cumprimentar();
+console.count("alice");
+ +

Teremos uma saída assim:

+ +
"bob: 1"
+"alice: 1"
+"alice: 2"
+"alice: 3"
+ +

Agora estamos mantendo contagens separadamente baseadas no valor de label. Como a label "alice" na linha 11 corresponde ao valor de usuario duas vezes, não é considerado um evento independente.

+ +

Sintaxe

+ +
console.count([label]);
+
+ +

Parâmetros

+ +
+
label
+
Uma string. Se for fornecida, exibe o número de vezes que  count() foi invocada com a mesma label.
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName("Console API", "#count", "console.count()")}}{{Spec2("Console API")}}Definição inicial
+ +

Compatibilidade de browsers

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
RecursoChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("30.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Disponível em workers{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("38.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
RecursoAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("30.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Disponível em Workers{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("38.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
diff --git a/files/pt-br/web/api/console/dir/index.html b/files/pt-br/web/api/console/dir/index.html new file mode 100644 index 0000000000..aa5c153903 --- /dev/null +++ b/files/pt-br/web/api/console/dir/index.html @@ -0,0 +1,108 @@ +--- +title: Console.dir() +slug: Web/API/Console/dir +tags: + - API + - console +translation_of: Web/API/Console/dir +--- +

{{ APIRef("Console API") }}{{Non-standard_header}}

+ +

Resumo

+ +

Exibe uma lista interativa das propriedades do objeto JavaScript especificado. A saída é apresentada como uma lista hierárquica com triângulos que permitem ver o conteúdo de objetos-filho.

+ +

{{AvailableInWorkers}}

+ +

console-dir.png

+ +

Sintaxe

+ +
console.dir(object);
+
+ +

Parâmetros

+ +
+
object
+
Um objeto JavaScript cujas propriedades devem ser emitidas.
+
+ +

Especificação

+ +

Console Object API

+ +

Compatibilidade do Browser

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{ CompatVersionUnknown() }}{{ CompatGeckoDesktop("8.0") }}9{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
Disponível em trabalhos{{ CompatUnknown() }}{{ CompatGeckoDesktop("38.0") }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{ CompatUnknown() }}{{ CompatGeckoMobile("8.0") }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
Disponível em trabalhos{{ CompatUnknown() }}{{ CompatGeckoDesktop("38.0") }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

 

+ +

Ver também

+ + diff --git a/files/pt-br/web/api/console/error/index.html b/files/pt-br/web/api/console/error/index.html new file mode 100644 index 0000000000..bf0ff45540 --- /dev/null +++ b/files/pt-br/web/api/console/error/index.html @@ -0,0 +1,160 @@ +--- +title: Console.error() +slug: Web/API/Console/error +translation_of: Web/API/Console/error +--- +
{{APIRef("Console API")}}{{Non-standard_header}}
+ +

'Escreve' uma mensagem de erro no  Web Console.

+ +

{{AvailableInWorkers}}

+ +

Sintaxe

+ +
console.error(obj1 [, obj2, ..., objN]);
+console.error(msg [, subst1, ..., substN]);
+console.exception(obj1 [, obj2, ..., objN]);
+console.exception(msg [, subst1, ..., substN]);
+
+ +
+

Nota: console.exception() é um alias para console.error(); as funcionalidades deles são identicas.

+
+ +

Parâmetros

+ +
+
obj1 ... objN
+
Uma lista de objetos Javascript para serem escritos. As representações String de cada um destes objetos é ligada junto na ordem listada e escrita.
+
msg
+
Uma String Javascript contendo zero ou mais Strings de substituição.
+
subst1 ... substN
+
Objetos JavaScript o qual substituirão as Strings no msg. Este parâmetro fornece controle adicional sobre o formato de output.
+
+ +

Veja Outputting text to the console na documentação de {{domxref("console")}} para mais detalhes.

+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName("Console API", "#consoleerrorobject--object-", "console.error()")}}{{Spec2("Console API")}}Initial definition
+ +

Compatibilidade com os navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatGeckoDesktop("2.0")}}8{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Substituição de Strings{{CompatVersionUnknown}}{{CompatGeckoDesktop("9.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
console.exception alias{{CompatNo}}{{CompatGeckoDesktop("28.0")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
Disponível em workers{{CompatUnknown}}{{CompatGeckoDesktop("38.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatUnknown}}{{CompatGeckoMobile("2.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Substituição de Strings{{CompatUnknown}}{{CompatGeckoMobile("9.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
console.exception alias{{CompatNo}}{{CompatGeckoMobile("28.0")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
Disponível em workers{{CompatUnknown}}{{CompatGeckoMobile("38.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Ver também

+ + diff --git a/files/pt-br/web/api/console/index.html b/files/pt-br/web/api/console/index.html new file mode 100644 index 0000000000..c8d6331685 --- /dev/null +++ b/files/pt-br/web/api/console/index.html @@ -0,0 +1,242 @@ +--- +title: Console +slug: Web/API/Console +translation_of: Web/API/Console +--- +
+
{{APIRef("Console API")}}{{Non-standard_header}}
+
+ +

O objeto console fornece acesso ao console de debug do navegador (por exemplo, o Web Console do Firefox). O seu funcionamento específico varia de navegador para navegador, mas existe um conjunto de ferramentas que na prática são fornecidas normalmente.

+ +

Esta página documenta os {{anch("Métodos")}} disponíveis no objeto console e fornece alguns exemplos de {{anch("Uso")}}.

+ +

Métodos

+ +
+
{{domxref("console.assert()", "console.assert(expression, object[, object...])")}}
+
Emite uma mensagem e traça a sequência de operações até o primeiro argumento for falso.
+
{{domxref("console.count()", "console.count([label])")}}
+
Mostra o número de vezes que esta linha foi chamada com a label fornecida.
+
{{domxref("console.log()", "console.debug(object[, object...])")}} {{deprecated_inline("5.0")}}
+
Um atalho para log(); que foi adicionado para melhorar a compatibilidade de páginas já existentes que utilizavam debug(). Porém, ao invés destes comandos você deve utilizar {{domxref("console.log()")}}.
+
{{domxref("console.dir()", "console.dir(object)")}}
+
Exibe uma listagem interativa das propriedades de um objeto JavaScript especificado. Esta listagem permite a você expandir o objeto para visualizar o conteúdo de objetos filhos.
+
{{domxref("console.error()", "console.error(object[, object...])")}}
+
Emite uma mensagem de erro. Você pode usar substituição de string e outros argumentos adicionais com este método. Consulte {{anch("Uso de substituição de string")}}.
+
{{domxref("console.error()", "console.exception(object[, object...])")}}
+
Um atalho para error();
+
{{domxref("console.group()", "console.group(object[, object...])")}}
+
Cria um novo grupo em linha e recua todas as mensagens seguintes para um nível de indentação superior. Para voltar um nível, utilize groupEnd(). Consulte {{anch("Uso de grupos no console")}}.
+
{{domxref("console.groupCollapsed()", "console.groupCollapsed(object[, object...])")}}
+
Cria um novo grupo em linha e recua todas as mensagens seguintes para um nível de indentação superior; ao contrário de group(), o grupo em linha começa recolhido. Para revelar seu conteúdo, basta clicar no botão de revelação para expandí-lo. Para recuar um nível, utilize groupEnd(). Consulte {{anch("Uso de grupos no console")}}.
+
{{domxref("console.groupEnd()")}}
+
Sai do grupo em linha atual. Veja {{anch("Uso de grupos no console")}}.
+
{{domxref("console.info()", "console.info(object[, object...])")}}
+
Informações de registro. Você pode utilizar substituição de string e outros argumentos com este método. Consulte {{anch("Uso de substituição de string")}}.
+
{{domxref("console.log()", "console.log(object[, object...])")}}
+
Utilizado para a emissão de informações de registro em geral. Você pode utilizar substituição de string e outros argumentos com este método. Consulte {{anch("Uso de substituição de string")}}.
+
{{domxref("console.profile()", "console.profile( [profileLabel] )")}}
+
Inicia o JavaScript profiler. Você pode especificar qualquer label opcional para o perfil.
+
{{domxref("console.profileEnd()")}}
+
Interrompe o profiler. Você pode ver o profile resultante no JavaScript profiler.
+
+ +

 

+ +
+
{{domxref("Console.table()")}}
+
Exibe dados, como objeto e array, como uma tabela.
+
+ +

 

+ +
+
{{domxref("console.time()", "console.time(name)")}}
+
Inicia um contador de tempo com o nome especificado no parâmetro name. Até 10.000 contadores de tempo podem ser rodados por página.
+
{{domxref("console.timeEnd()", "console.timeEnd(name)")}}
+
Interrompe o contador de tempo especificado e emite o tempo e registros do contador de tempo em milisegundos desde o seu início. Veja {{anch("Contadores de Tempo")}}.
+
{{domxref("console.trace()")}}
+
Emite um traçado de pilha. See {{anch("Traçados de pilha")}}.
+
{{domxref("console.warn()", "console.warn(object[, object...])")}}
+
Emite uma mensagem de alerta. Você pode utilizar substituição de string e argumentos adicionais com este método. Veja {{anch("Uso de substituição de string")}}.
+
+ + +

Uso

+ +

Output de texto para o console

+ +

A utilização mais frequente do console é realizar o log de texto e de outros dados. Há quatro categorias de output que podem ser geradas, utilizando os métodos {{domxref("console.log()")}}, {{domxref("console.info()")}}, {{domxref("console.warn()")}} e o {{domxref("console.error()")}}. Cada um destes resultam em outputs que possuem estilos diferentes no log, e você pode utilizar os controles de filtragem fornecidos pelo navegador para ver apenas os outputs que lhe interessam.

+ +

Há duas maneiros da utilizar cada um dos métodos de outuput. Você pode simplemente passar uma lista dos objetos cuja representação em string será concatenadas em uma string e então realizar o output  para o console, ou você pode passar uma string contendo zero ou mais substituições de strings seguidas por uma lista de objetos para serem utilizados na substituição.

+ +

Output de um único objeto

+ +

A forma mais simples de utilizar os métodos de log é realizar o output de um único objeto:

+ +
var algumObjeto = { str: "Algum texto", id: 5 };
+console.log(algumObjeto);
+
+ +

O output vai se parecer como algo assim:

+ +
[09:27:13.475] ({str:"Algum texto", id:5})
+ +

Output de múltiplos objetos

+ +

Você também pode realizar o output de múltiplos objetos ao simplesmente listá-los ao chamar o método de log, desta forma:

+ +
var carro = "Fusca";
+var algumObjeto = {str:"Algum texto", id:5};
+console.info("Meu primeiro carro era um ", carro, ". O objeto é: ", algumObjeto);
+ +

O output será algo assim:

+ +
[09:28:22.711] Meu primeiro carro era um Fusca. O objeto é:  ({str:"Algum texto", id:5})
+
+ +

Uso de substituição de string

+ +

O Gecko 9.0 {{geckoRelease("9.0")}} introduziu o suporte à substituição de strings. Ao fornecer uma string para um dos métodos do console que aceitam uma string, você pode utilizar estas strings de substituição:

+ + + + + + + + + + + + + + + + + + + + + + + + +
String de substituiçãoDescrição
%oEmite um link para o objeto JavaScript. Clicar no link abre um inspetor.
%d ou %iEmite uma numero inteiro. A formatação ainda não possui suporte.
%sEmite uma string.
%fEmite um número de ponto flutuante. A formatação ainda não possui suporte.
+ +

Cada um destes puxam o próximo argumento na lista de parâmetros após a string fornecida inicialmente. Por exemplo:

+ +
for (var i=0; i<5; i++) {
+  console.log("Olá, %s. Você me chamou pela %dª vez.", "João", i+1);
+}
+
+ +

O output será algo assim:

+ +
[13:14:13.481] Olá, João. Você me chamou pela 1ª vez.
+[13:14:13.483] Olá, João. Você me chamou pela 2ª vez.
+[13:14:13.485] Olá, João. Você me chamou pela 3ª vez.
+[13:14:13.487] Olá, João. Você me chamou pela 4ª vez.
+[13:14:13.488] Olá, João. Você me chamou pela 5ª vez.
+
+ +

Estilizando o output no console

+ +

You can use the "%c" directive to apply a CSS style to console output:

+ +
console.log("%cMy stylish message", "color: red; font-style: italic");
+ +
+ +
{{h3_gecko_minversion("Using groups in the console", "9.0")}}
+ +

You can use nested groups to help organize your output by visually combining related material. To create a new nested block, call console.group(). The console.groupCollapsed() method is similar, but creates the new block collapsed, requiring the use of a disclosure button to open it for reading.

+ +
Note: Collapsed groups are not supported yet in Gecko; the groupCollapsed() method is the same as group() at this time.
+ +

To exit the current group, simply call console.groupEnd().

+ +

For example, given this code:

+ +
console.log("This is the outer level");
+console.group();
+console.log("Level 2");
+console.group();
+console.log("Level 3");
+console.warn("More of level 3");
+console.groupEnd();
+console.log("Back to level 2");
+console.groupEnd();
+console.debug("Back to the outer level");
+
+ +

The output looks like this:

+ +

nesting.png

+ +
{{h3_gecko_minversion("Timers", "10.0")}}
+ +

In order to calculate the duration of a specific operation, Gecko 10 introduced the support of timers in the console object. To start a timer, call the console.time() method, giving it a name as only parameter. To stop the timer, and to get the elapsed time in miliseconds, just call the console.timeEnd() method, again passing the timer's name as the parameter. Up to 10,000 timers can run simultaneously on a given page.

+ +

For example, given this code:

+ +
console.time("answer time");
+alert("Click to continue");
+console.timeEnd("answer time");
+
+ +

will log the time needed by the user to discard the alert box:

+ +

timerresult.png

+ +

Notice that the timer's name is displayed both when the timer is started and when it's stopped.

+ +
Note: It's important to note that if you're using this to log the timing for network traffic, the timer will report the total time for the transaction, while the time listed in the network panel is just the amount of time required for the header. If you have response body logging enabled, the time listed for the response header and body combined should match what you see in the console output.
+ +

Stack traces

+ +

The console object also supports outputting a stack trace; this will show you the call path taken to reach the point at which you call {{domxref("console.trace()")}}. Given code like this:

+ +
foo();
+
+function foo() {
+  function bar() {
+    console.trace();
+  }
+  bar();
+}
+
+ +

The output in the console looks something like this:

+ +

+ +

Notes

+ + + +

See also

+ + + +

Other implementations

+ +

 

+ + diff --git a/files/pt-br/web/api/console/info/index.html b/files/pt-br/web/api/console/info/index.html new file mode 100644 index 0000000000..e4033e254d --- /dev/null +++ b/files/pt-br/web/api/console/info/index.html @@ -0,0 +1,154 @@ +--- +title: Console.info() +slug: Web/API/Console/info +translation_of: Web/API/Console/info +--- +
{{APIRef("Console API")}}{{Non-standard_header}}
+ +

Apresenta uma mensagem de saída no console do navegador . No Firefox e Chrome , um pequeno ícone "i" e apresentado próximo aos items do log do console .  

+ +

{{AvailableInWorkers}}

+ +

Sintaxe

+ +
console.info(obj1 [, obj2, ..., objN]);
+console.info(msg [, subst1, ..., substN]);
+
+ +

Parâmetros

+ +
+
obj1 ... objN
+
A lista de objetos javascript para saída . As representações de strings de cada um desses objetos são anexados juntos em ordem de listagem e saida . 
+
msg
+
Uma string javascript que contém zero ou mais strings para substituição.
+
subst1 ... substN
+
Objeto javascript o qual substitui strings com msg. Isso permite controle adicional sobre o formato da saída.
+
+ +

Veja Outputting text to the console na documentação {{domxref("console")}} para mais  detalhes.

+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçõesStatusComentários
{{SpecName("Console API", "#consoleinfoobject--object-", "console.info()")}}{{Spec2("Console API")}}Definição inicial
+ +

Compatibilidade de Browser

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticasChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatGeckoDesktop("2.0")}}8{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Substituição de strings{{CompatUnknown}}{{CompatGeckoDesktop("9.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Icones informação{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}
Disponível para trabalhadores{{CompatUnknown}}{{CompatGeckoDesktop("38.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticasAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatUnknown}}{{CompatGeckoMobile("2.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Substituição de  strings{{CompatUnknown}}{{CompatGeckoMobile("9.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+ + + + + + + +
Disponível para trabalhadores 
+
{{CompatUnknown}}{{CompatGeckoMobile("38.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Veja  também

+ + diff --git a/files/pt-br/web/api/console/log/index.html b/files/pt-br/web/api/console/log/index.html new file mode 100644 index 0000000000..b25a14a3fe --- /dev/null +++ b/files/pt-br/web/api/console/log/index.html @@ -0,0 +1,119 @@ +--- +title: Console.log() +slug: Web/API/Console/log +translation_of: Web/API/Console/log +--- +
{{APIRef("Console API")}}{{Non-standard_header}}
+ +

Sumário

+ +

Exibe uma mensagem na console do navegador.

+ +

Syntax

+ +
console.log(obj1[, obj2, ..., objN]);
+console.log(msg[, subst1, ..., substN]);
+
+ +

Parameters

+ +
+
obj1 ... objN
+
Uma lista de objetos JavaScript para exibir. A representação por escrito de cada um desses objetos é exibida na ordem com a qual foram inseridos na função.
+
msg
+
Uma string JavaScript com zero ou mais substituições.
+
subst1 ... substN
+
Strings ou objetos JavaScript para substituirem as marcações de substituição em msg. Estas substituições ocorrem de um para um e na ordem em que são passadas para a console.log.
+
+ +

Veja Exibindo texto na console na documentação do objeto {{domxref("console")}} para mais detalhes.

+ +

Especificação

+ +

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

+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatGeckoDesktop("2.0")}}8{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Strings de substituição +

{{CompatVersionUnknown}}

+ +

{{CompatChrome(28)}}

+ +

%d - se um valor fracional negativo é passado, ele será arredondado para baixo, exemplo: -0,35 será arredondado para 1

+
{{CompatGeckoDesktop("9.0")}} +

10 - parcial

+ +

%c - não suportado
+ %d - irá renderizar como 0 quando NaN

+
{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatUnknown}}{{CompatGeckoMobile("2.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Strings de substituição{{CompatUnknown}}{{CompatGeckoMobile("9.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Ver também

+ + diff --git a/files/pt-br/web/api/console/table/index.html b/files/pt-br/web/api/console/table/index.html new file mode 100644 index 0000000000..946a642003 --- /dev/null +++ b/files/pt-br/web/api/console/table/index.html @@ -0,0 +1,143 @@ +--- +title: Console.table() +slug: Web/API/Console/table +translation_of: Web/API/Console/table +--- +
{{APIRef("Console API")}}
+ +

Exibe dados tabulares como uma tabela.

+ +

Essa função recebe um parâmetro obrigatório data, que deve ser um array ou um objeto, e um parametro opcional columns.

+ +

Registra data como uma tabela. Cada elemento no array (ou propriedade enumerável se data for um objeto) será uma linha na tabela.

+ +

A primeira coluna na tabela será rotulada (index). Se data for um array, seus valores serão os índices da matriz. Se data for um objeto, seus valores serão os nomes das propriedades. Observe que (no Firefox) o console.table está limitado a exibir 1000 linhas (a primeira linha é o índice rotulado).

+ +

{{AvailableInWorkers}}

+ +

Coleções de tipos primitivos

+ +

O argumento data pode ser um array ou um objeto.

+ +
// um array de strings
+
+console.table(["apples", "oranges", "bananas"]);
+ +

+ +
// um objeto cujas propriedades são strings
+
+function Person(firstName, lastName) {
+  this.firstName = firstName;
+  this.lastName = lastName;
+}
+
+var me = new Person("John", "Smith");
+
+console.table(me);
+ +

+ +

Coleções de tipos compostos

+ +

Se os elementos no array, ou propriedades no objeto, forem arrays ou objetos, seus elementos ou propriedades serão enumerados na linha, um por coluna:

+ +
// um array de arrays
+
+var people = [["John", "Smith"], ["Jane", "Doe"], ["Emily", "Jones"]]
+console.table(people);
+ +

Table displaying array of arrays

+ +
// um array de objetos
+
+function Person(firstName, lastName) {
+  this.firstName = firstName;
+  this.lastName = lastName;
+}
+
+var john = new Person("John", "Smith");
+var jane = new Person("Jane", "Doe");
+var emily = new Person("Emily", "Jones");
+
+console.table([john, jane, emily]);
+ +

Observe que, se a matriz contiver objetos, as colunas serão rotuladas com o nome da propriedade.

+ +

Table displaying array of objects

+ +
// um objeto cujas propriedades são objetos
+
+var family = {};
+
+family.mother = new Person("Jane", "Smith");
+family.father = new Person("John", "Smith");
+family.daughter = new Person("Emily", "Smith");
+
+console.table(family);
+ +

Table displaying object of objects

+ +

Restringindo as colunas exibidas

+ +

Por padrão, console.table() lista todos os elementos em cada linha. Você pode usar o parâmetro opcional columns para selecionar um subconjunto de colunas a serem exibidas:

+ +
// um array de objetos, registrando apenas firstName
+
+function Person(firstName, lastName) {
+  this.firstName = firstName;
+  this.lastName = lastName;
+}
+
+var john = new Person("John", "Smith");
+var jane = new Person("Jane", "Doe");
+var emily = new Person("Emily", "Jones");
+
+console.table([john, jane, emily], ["firstName"]);
+ +

Table displaying array of objects with filtered output

+ +

Classificando colunas

+ +

Você pode classificar a tabela por uma coluna específica clicando no rótulo dessa coluna.

+ +

Sintaxe

+ +
console.table(data [, columns]);
+
+ +

Parâmentros

+ +
+
data
+
Os dados a serem exibidos. Deve ser um array ou um objeto.
+
columns
+
Um array contendo os nomes das colunas para incluir na saída.
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName("Console API", "#table", "console.table()")}}{{Spec2("Console API")}}Definição inicial
+ +

Compatibilidade de browsers

+ +
+ + +

{{Compat("api.Console.table")}}

+
diff --git a/files/pt-br/web/api/console/time/index.html b/files/pt-br/web/api/console/time/index.html new file mode 100644 index 0000000000..14b6f4a03c --- /dev/null +++ b/files/pt-br/web/api/console/time/index.html @@ -0,0 +1,103 @@ +--- +title: Console.time() +slug: Web/API/Console/time +translation_of: Web/API/Console/time +--- +

{{ APIRef("Console API") }}{{Non-standard_header}}

+ +

Sumário

+ +

Inicia um cronômetro que você pode usar para monitorar quanto tempo uma operação leva. Você dá para cada cronômetro um nome único, e deve ter no máximo 10.000 deles sendo executados na página. Quando você chama {{ domxref("console.timeEnd()") }} com o mesmo nome, o navegador mostrará o tempo, em milisegundos, que se passou desde que o cronômetro iniciou.

+ +

Veja Timers na documentação {{ domxref("console") }} para detalhes e exemplos.

+ +

{{AvailableInWorkers}}

+ +

Sintaxe

+ +
console.time(cronometroNome);
+
+ +

Parâmetros

+ +
+
cronometroNome
+
O nome para dar ao novo cronômetro. Ele identificará o cronômetro; use o mesmo quando chamar {{ domxref("console.timeEnd()") }} para parar o cronômetro e obter o tempo na saída do console.
+
+ +

Especificação

+ +

API do objeto Console

+ +

Compatibilidade com navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico2{{ CompatGeckoDesktop("10.0") }}11{{ CompatVersionUnknown() }}4.0
Disponível em Workers{{ CompatUnknown() }}{{ CompatGeckoDesktop("38.0") }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{ CompatUnknown() }}{{ CompatGeckoMobile("10.0") }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
Disponível em Workers{{ CompatUnknown() }}{{ CompatGeckoMobile("38.0") }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/console/timeend/index.html b/files/pt-br/web/api/console/timeend/index.html new file mode 100644 index 0000000000..7ef63ea5bc --- /dev/null +++ b/files/pt-br/web/api/console/timeend/index.html @@ -0,0 +1,90 @@ +--- +title: Console.timeEnd() +slug: Web/API/Console/timeEnd +tags: + - Desenvolvimento Web + - metodo +translation_of: Web/API/Console/timeEnd +--- +
+
{{APIRef("Console API")}}{{Non-standard_header}}
+
+ +

Resumo

+ +

Interrompe um temporizador que foi anteriormente iniciado por uma chamada a {{domxref("console.time()")}}.

+ +

Veja Timers na documentação de {{domxref("console")}} para detalhes e exemplos.

+ +

Sintaxe

+ +
console.timeEnd(timerName);
+
+ +

Parametros

+ +
+
timerName
+
O nome do temporizador a ser interrompido. Uma vez interrompido, o tempo decorrido é automaticamente apresentado no Web Console.
+
+ +

Especificação

+ +

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

+ +

Compatibilidade com navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support2{{CompatGeckoDesktop("10.0")}}11{{CompatVersionUnknown}}4.0
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatGeckoMobile("10.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/console/timestamp/index.html b/files/pt-br/web/api/console/timestamp/index.html new file mode 100644 index 0000000000..774ee4048b --- /dev/null +++ b/files/pt-br/web/api/console/timestamp/index.html @@ -0,0 +1,106 @@ +--- +title: Console.timeStamp() +slug: Web/API/Console/timeStamp +translation_of: Web/API/Console/timeStamp +--- +

{{ APIRef("Console API") }}{{Non-standard_header}}

+ +

Sumário

+ +

Adiciona um marcador simples para as ferramentas Timeline ou Waterfall do navegador. Ele deixa você relacionar um ponto no seu código com os outros eventos gravados na linha do tempo, como um evento de layout ou de pintura.

+ +

Opcionalmente, você pode fornecer um argumento como rótulo do carimbo de hora, e esse rótulo será então mostrado juntamente com a marcação.

+ +
+

Nota: essa funcionalidade está disponível em Web Workers.

+
+ +

Sintaxe

+ +
console.timeStamp(rotulo);
+
+ +

Parâmetros

+ +
+
rotulo
+
Rótulo para o carimbo de hora. Opcional.
+
+ +

Especificação

+ +

API do objeto Console

+ +

Compatibilidade com navegadores

+ +

{{ CompatibilityTable() }}

+ +
{{ CompatUnknown() }} + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatNo() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
Disponível em workers{{ CompatVersionUnknown() }}{{ CompatGeckoDesktop("38.0") }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{ CompatUnknown() }}{{ CompatGeckoMobile("10.0") }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
Disponível em workers{{ CompatUnknown() }}{{ CompatGeckoMobile("38.0") }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/console/warn/index.html b/files/pt-br/web/api/console/warn/index.html new file mode 100644 index 0000000000..73eab6abee --- /dev/null +++ b/files/pt-br/web/api/console/warn/index.html @@ -0,0 +1,139 @@ +--- +title: Console.warn() +slug: Web/API/Console/warn +translation_of: Web/API/Console/warn +--- +
{{APIRef("Console API")}}{{non-standard_header}}
+ +

Escreve uma mensagem de alerta no Console Web.

+ +

{{AvailableInWorkers}}

+ +

{{Note("No Firefox, warnings têm um pequeno icone de ponto de exclamação perto deles no log do Console Web.")}}

+ +

Sintaxe

+ +
console.warn(obj1 [, obj2, ..., objN]);
+console.warn(msg [, subst1, ..., substN]);
+
+ +

Parâmetros

+ +
+
obj1 ... objN
+
Uma lista de objetos JavaScript para escrever. A representação String de cada um destes objetos é ligada junto na ordem listada e escrita.
+
msg
+
Uma string JavaScript contendo zero ou mais strings de substituição.
+
subst1 ... substN
+
Objetos JavaScript com qual as strings de substituição msg serão substituidas. Isto dá um contriole adicional sobre a mensagem que será escrita.
+
+ +

Ver Outputting text to the console na documentação do {{domxref("console")}} para mais detalhes.

+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName("Console API", "#consolewarnobject--object-", "console.warn()")}}{{Spec2("Console API")}}Definição inicial
+ +

Compatibilidade entre os navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatGeckoDesktop("2.0")}}8{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Substituição strings{{CompatUnknown}}{{CompatGeckoDesktop("9.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Disponível em workers{{CompatUnknown}}{{CompatGeckoDesktop("38.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatUnknown}}{{CompatGeckoMobile("2.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Substituição strings{{CompatUnknown}}{{CompatGeckoMobile("9.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Disponível em workers{{CompatUnknown}}{{CompatGeckoMobile("38.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Ver também

+ + diff --git a/files/pt-br/web/api/console_api/index.html b/files/pt-br/web/api/console_api/index.html new file mode 100644 index 0000000000..560264eb23 --- /dev/null +++ b/files/pt-br/web/api/console_api/index.html @@ -0,0 +1,68 @@ +--- +title: Console API +slug: Web/API/Console_API +translation_of: Web/API/Console_API +--- +
{{DefaultAPISidebar("Console API")}}
+ +

O Console API  traz funcionalidades que permitem desenvolvedores realizar tarefas de debug, como registrar mensagens or os valores das variáveis em sertoes pontos do código, or cronometrar quanto tempo uma operação leva para concluir.

+ +

Conceitos e uso

+ +

O Console API começou como uma API proprietária, com diferentes navegadores a implementando.  A especificação do Console API foi criado para definir um comportamento consistente, e todos o navegadores atuais ventualmente foram implementando a funconalidade — Apsar de algumas implementações ainda terem funções adicionais proprietárias. Veja mais sobre isso em:

+ + + +

Uso é bastante simples — o objeto {{domxref("console")}} — disponível via {{domxref("window.console")}}, ou {{domxref("WorkerGlobalScope.console")}} em workers; acessível apenas usando console — contém vários métodos que você pode chamar para executar tarefas de depuração, geralmente focado no registro de vários valores no navegador Web Console.

+ +

De longe o método mais comum usado é o {{domxref("console.log")}}, que é usado para mostrar o valor atual contido em uma variável específica.

+ +

Interfaces

+ +
+
{{domxref("console")}}
+
Provides rudimentary debugging functionality, including logging, stack traces, timers, and counters.
+
+ +

Examples

+ +
let myString = 'Hello world';
+
+// Output "Hello world" to the console
+console.log(myString)
+ +

See the Console reference page for more examples.

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Console API')}}{{Spec2('Console API')}}Initial definition.
+ +

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/pt-br/web/api/crypto/index.html b/files/pt-br/web/api/crypto/index.html new file mode 100644 index 0000000000..cc9a0214d1 --- /dev/null +++ b/files/pt-br/web/api/crypto/index.html @@ -0,0 +1,72 @@ +--- +title: Crypto +slug: Web/API/Crypto +tags: + - API + - Interface + - Referencia + - Web Crypto API +translation_of: Web/API/Crypto +--- +

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

+ +

A interface Crypto apresenta características de criptografia básica disponíveis no contexto atual. Isto permite acesso a um forte gerador criptográfico de números aleatórios e a criptografias primitivas.

+ +

Um objeto com essa interface está disponível no contexto web via propriedade {{domxref("Window.crypto")}} .

+ +

Propriedades

+ +

Esta interface implementa propriedades definidas em {{domxref("RandomSource")}}.

+ +
+
{{domxref("Crypto.subtle")}} {{experimental_inline}}{{readOnlyInline}}
+
Retorna um objeto {{domxref("SubtleCrypto")}} provendo acesso a criptografias primitivas comuns, como hashing, signing, encryption ou decryption.
+
+ +

Métodos

+ +

Esta interface implementa métodos definidos em {{domxref("RandomSource")}}.

+ +
+
{{domxref("RandomSource.getRandomValues()")}}
+
Preenche a {{ jsxref("TypedArray") }} com valores criptografados aleatórios.
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName("Web Crypto API", "#crypto-interface", "Crypto")}}{{Spec2("Web Crypto API")}}Definição inicial.
+ +

Compatibilidade de Browser

+ + + +

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

+ +
 
+ +

Veja também

+ + + +

Dicionário:

+ +

"Key" = "Chave"

diff --git a/files/pt-br/web/api/crypto/subtle/index.html b/files/pt-br/web/api/crypto/subtle/index.html new file mode 100644 index 0000000000..caf7e0d4f0 --- /dev/null +++ b/files/pt-br/web/api/crypto/subtle/index.html @@ -0,0 +1,51 @@ +--- +title: Crypto.subtle +slug: Web/API/Crypto/subtle +tags: + - API + - Criptografía + - Propriedade + - Read-only + - Referencia + - Web Crypto API +translation_of: Web/API/Crypto/subtle +--- +

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

+ +

A prorpiedade Crypto.subtle de apenas leitura retorna como objeto {{domxref("SubtleCrypto")}} permitindo exercer operações de criptografia.

+ +

Sintaxe

+ +
var crypto = crypto.subtle;
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{ SpecName('Web Crypto API', '#dfn-Crypto', 'Crypto.subtle') }}{{ Spec2('Web Crypto API') }}Definição inicial.
+ +

Compatibilidade de Browser

+ + + +

{{Compat("api.Crypto.subtle")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/cryptokey/algorithm/index.html b/files/pt-br/web/api/cryptokey/algorithm/index.html new file mode 100644 index 0000000000..ab2440f6b6 --- /dev/null +++ b/files/pt-br/web/api/cryptokey/algorithm/index.html @@ -0,0 +1,112 @@ +--- +title: CryptoKey.algorithm +slug: Web/API/CryptoKey/algorithm +tags: + - API + - CryptoKey + - Propriedade + - Read-only + - Referencia + - Web Crypto API +translation_of: Web/API/CryptoKey +--- +

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

+ +

A propriedade CryptoKey.algorithm de apenas leitura é um valor opaco contendo todas as informações sobre o algoritmo relacionado à key.

+ +

Implementações diferentes tem diferentes tipos de valores opacos para os mesmos: tal objeto não pode ser compartilhado.

+ +

Sintaxe

+ +
result = key.algorithm
+
+ +

Valor de retorno

+ + + +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{ SpecName('Web Crypto API', '#dfn-CryptoKey-algorithm', 'CryptoKey.algorithm') }}{{ Spec2('Web Crypto API') }}Definição inicial.
+ +

Compatibilidade de Browser

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{ CompatChrome(37) }}{{CompatVersionUnknown}}{{ CompatGeckoDesktop(34) }}{{ CompatNo() }}{{ CompatUnknown() }}{{ CompatNo }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}37{{CompatVersionUnknown}}{{ CompatGeckoMobile(34) }}{{ CompatNo }}{{ CompatUnknown() }}{{ CompatNo }}
+
+ +

Veja também

+ + + +

Dicionário

+ +

"Key" = "Chave"

diff --git a/files/pt-br/web/api/cryptokey/extractable/index.html b/files/pt-br/web/api/cryptokey/extractable/index.html new file mode 100644 index 0000000000..6ff8bde9c7 --- /dev/null +++ b/files/pt-br/web/api/cryptokey/extractable/index.html @@ -0,0 +1,110 @@ +--- +title: CryptoKey.extractable +slug: Web/API/CryptoKey/extractable +tags: + - API + - CryptoKey + - Propriedade + - Read-only + - Referencia + - Web Crypto API +translation_of: Web/API/CryptoKey +--- +

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

+ +

A propriedade de apenas leitura CryptoKey.extractable que indica se a key bruta do material pode ser extraída, para por exemplo arquivá-la.

+ +

Sintaxe

+ +
result = key.extractable
+
+ +

Valor de retorno

+ + + +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{ SpecName('Web Crypto API', '#dfn-CryptoKey-extractable', 'CryptoKey.extractable') }}{{ Spec2('Web Crypto API') }}Definição inicial.
+ +

Compatibilidade de Browser

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{ CompatChrome(37) }}{{CompatVersionUnknown}}{{ CompatGeckoDesktop(34) }}{{ CompatNo() }}{{ CompatUnknown() }}{{ CompatNo }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}37{{CompatVersionUnknown}}{{ CompatGeckoMobile(34) }}{{ CompatNo }}{{ CompatUnknown() }}{{ CompatNo }}
+
+ +

Veja também

+ + + +

Dicionário

+ +

"Key" = "Chave"

diff --git a/files/pt-br/web/api/cryptokey/index.html b/files/pt-br/web/api/cryptokey/index.html new file mode 100644 index 0000000000..e532bba078 --- /dev/null +++ b/files/pt-br/web/api/cryptokey/index.html @@ -0,0 +1,120 @@ +--- +title: CryptoKey +slug: Web/API/CryptoKey +tags: + - API + - Chaves Criptografadas + - Interface + - Referencia + - Web Crypto API +translation_of: Web/API/CryptoKey +--- +

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

+ +

A interface CryptoKey representa uma {{glossary("key")}} criptografada derivada de uma key de algoritmo definido.

+ +

Um objeto CryptoKey pode ser obtido utilizando {{domxref("SubtleCrypto.generateKey()")}}, {{domxref("SubtleCrypto.deriveKey()")}} ou {{domxref("SubtleCrypto.importKey()")}}

+ +

Propriedades

+ +

Esta interface não herda nehunha propriedade.

+ +
+
{{domxref("CryptoKey.type")}}
+
Retorna um valor enumerado representando o tipo da key, uma key secreta (para algoritmos simétricos), uma key pública ou privada (para algoritmos assimétricos).
+
{{domxref("CryptoKey.extractable")}}
+
Retorna um {{jsxref("Boolean")}} indicando se a informação bruta pode ser exportada para a aplicação ou não.
+
{{domxref("CryptoKey.algorithm")}}
+
Retorna um objeto opaco representando uma cifra em particular que deve ser utilizada com a key.
+
{{domxref("CryptoKey.usages")}}
+
Retorna uma matriz de valores enumerados indicando onde a key pode ser utilizada.
+
+ +

Métodos

+ +

Esta interface não herda, nem implementa nenhum método.

+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{ SpecName('Web Crypto API', '#dfn-CryptoKey', 'CryptoKey') }}{{ Spec2('Web Crypto API') }}Definição inicial.
+ +

Compatibilidade com o Browser

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico.{{ CompatChrome(37) }}{{CompatVersionUnknown}}{{ CompatGeckoDesktop(34) }}{{ CompatNo() }}{{ CompatUnknown() }}{{ CompatNo }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico.37{{ CompatChrome(37) }}{{CompatVersionUnknown}}{{ CompatGeckoMobile(34) }}{{ CompatNo }}{{ CompatUnknown() }}{{ CompatNo }}
+ +

 

+
+ +

Veja também

+ + + +

Dicionário:

+ +

"Key" = "Chave"

diff --git a/files/pt-br/web/api/cryptokey/type/index.html b/files/pt-br/web/api/cryptokey/type/index.html new file mode 100644 index 0000000000..6a1bc1703e --- /dev/null +++ b/files/pt-br/web/api/cryptokey/type/index.html @@ -0,0 +1,117 @@ +--- +title: CryptoKey.type +slug: Web/API/CryptoKey/type +tags: + - API + - Apenas Leitura + - CryptoKey + - Propriedades + - Referencia + - Web Crypto API +translation_of: Web/API/CryptoKey +--- +

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

+ +

CryptoKey.type é uma propriedade de apenas leitura que indica o tipo de key: se for uma key para um algoritmo simétrico ("secret") ou, para um algoritmo assimétrico, ("public" ou "private", dependendo do seu propósito).

+ +

Sintaxe

+ +
result = key.type
+
+ +

Valor de retorno

+ + + +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçõesStatusComentário
{{ SpecName('Web Crypto API', '#dfn-CryptoKey-type', 'CryptoKey.type') }}{{ Spec2('Web Crypto API') }}Definição inicial.
+ +

Compatibilidade de Browser

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticasChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{ CompatChrome(37) }}{{CompatVersionUnknown}}{{ CompatGeckoDesktop(34) }}{{ CompatNo() }}{{ CompatUnknown() }}{{ CompatNo }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticasAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}37{{CompatVersionUnknown}}{{ CompatGeckoMobile(34) }}{{ CompatNo }}{{ CompatUnknown() }}{{ CompatNo }}
+
+ +

Veja também

+ + + +

Dicionário:

+ +

"Key" = "Chave"

diff --git a/files/pt-br/web/api/cryptokey/usages/index.html b/files/pt-br/web/api/cryptokey/usages/index.html new file mode 100644 index 0000000000..ba51dbaa0f --- /dev/null +++ b/files/pt-br/web/api/cryptokey/usages/index.html @@ -0,0 +1,123 @@ +--- +title: CryptoKey.usages +slug: Web/API/CryptoKey/usages +tags: + - API + - CryptoKey + - Propriedade + - Read-only + - Referencia + - Web Crypto API +translation_of: Web/API/CryptoKey +--- +

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

+ +

A propriedade de apenas leitura CryptoKey.usages é um conjunto enumerado que indica os propósitos da key.

+ +

Possíveis valores são:

+ + + +

Sintaxe

+ +
result = key.usages
+
+ +

Valor de retorno

+ + + +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{ SpecName('Web Crypto API', '#dfn-CryptoKey-usages', 'CryptoKey.usages') }}{{ Spec2('Web Crypto API') }}Definição inicial.
+ +

Compatibilidade de Browser

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{ CompatChrome(37) }}{{CompatVersionUnknown}}{{ CompatGeckoDesktop(34) }}{{ CompatNo() }}{{ CompatUnknown() }}{{ CompatNo }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}37{{CompatVersionUnknown}}{{ CompatGeckoMobile(34) }}{{ CompatNo }}{{ CompatUnknown() }}{{ CompatNo }}
+
+ +

Veja também

+ + + +

Dicionário:

+ +

"Key" = "Chave"

diff --git a/files/pt-br/web/api/css/index.html b/files/pt-br/web/api/css/index.html new file mode 100644 index 0000000000..9e7e83f1d2 --- /dev/null +++ b/files/pt-br/web/api/css/index.html @@ -0,0 +1,136 @@ +--- +title: CSS +slug: Web/API/CSS +tags: + - Apps + - CSSOM + - Referencia +translation_of: Web/API/CSS +--- +
{{APIRef("CSSOM")}}
+ +

A interface CSS carrega métodos CSS-relacionados úteis. Nenhum objeto com essa interface foi implementado: Aqui só contém métodos estáticos e futuramente uma interface útil.

+ +

Propriedades

+ +

A interface CSS é a interface utilizada e nenhum objeto desse tipo pode ser criado: só métodos estáticos são definidos aqui.

+ +

Métodos

+ +

A interface CSS é a interface utilizada e nenhum objeto desse tipo pode ser criado: só métodos estáticos são definidos aqui.

+ +

Métodos státicos

+ +

Nenhuma método estático herdado.

+ +
+
{{domxref("CSS.supports()")}}
+
Retorna um {{domxref("Boolean")}} indicando se o par property-value, ou a condição dada do parâmetro é suportada.
+
+ +
+
{{domxref("CSS.escape()")}} {{experimental_inline}}
+
Pode ser usado para escapar um string mais usado como parte de um seletor CSS.
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + +
EspecificaçõesEstadoComentário
{{SpecName('CSSOM', '#the-css.escape%28%29-method', 'CSS')}}{{Spec2('CSSOM')}}Adicionado o   escape() método estático.
{{SpecName('CSS3 Conditional', '#the-css-interface', 'CSS')}}{{Spec2('CSS3 Conditional')}}Definição inicial.
+ +

Compatibilidade com os Navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support28.0{{CompatGeckoDesktop("22.0")}} [1]6.012.1{{CompatNo}}
escape(){{experimental_inline}}46.0{{CompatGeckoDesktop("31.0")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatGeckoMobile("22.0")}}[1]{{CompatNo}}12.1{{CompatNo}}
escape(){{experimental_inline}}{{CompatNo}}{{CompatGeckoMobile("31.0")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] Também disponível através do layout.css.supports-rule.enabled preferência desde Gecko 20.

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/css_object_model/index.html b/files/pt-br/web/api/css_object_model/index.html new file mode 100644 index 0000000000..df8709c400 --- /dev/null +++ b/files/pt-br/web/api/css_object_model/index.html @@ -0,0 +1,133 @@ +--- +title: CSS Object Model +slug: Web/API/CSS_Object_Model +tags: + - API + - CSSOM + - Referencia +translation_of: Web/API/CSS_Object_Model +--- +

{{DefaultAPISidebar('CSSOM')}}

+ +

O CSS Object Model é um conjunto de APIs que permite manipular o CSS através do JavaScript. Isto depende do DOM e da HTML APIs. Com isto é permitido a leitura e a modificação dos estilos CSS dinamicamente.

+ +

Referências

+ +
+ +
+ +

Outras interfaces podem ser usadas com  CSSOM:

+ +

{{domxref("Document")}}, {{domxref("Window")}}, {{domxref("Element")}}, {{domxref("HTMLElement")}}, {{domxref("HTMLImageElement")}}, {{domxref("Range")}}, {{domxref("MouseEvent")}}, and {{domxref("SVGElement")}}.

+ +

Tutoriais

+ + + +

Especificações

+ +

 

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName("CSSOM")}}{{Spec2("CSSOM")}} 
{{SpecName("CSSOM View")}}{{Spec2("CSSOM View")}} 
{{SpecName("Screen Orientation")}}{{Spec2("Screen Orientation")}} 
{{SpecName("CSS3 Fonts")}}{{Spec2("CSS3 Fonts")}} 
{{SpecName("CSS3 Animations")}}{{Spec2("CSS3 Animations")}} 
{{SpecName("CSS3 Transitions")}}{{Spec2("CSS3 Transitions")}} 
{{SpecName("CSS3 Variables")}}{{Spec2("CSS3 Variables")}} 
{{SpecName("CSS3 Conditional")}}{{Spec2("CSS3 Conditional")}} 
{{SpecName("CSS3 Device")}}{{Spec2("CSS3 Device")}} 
{{SpecName("CSS3 Counter Styles")}}{{Spec2("CSS3 Counter Styles")}} 
+ +

Notas de compatibilidade do navegador

+ +

Todos esses recursos foram adicionados pouco a pouco ao logo dos anos para os diferentes navegadores: Foi um processo bastante complexo que não podem ser sintetizados em uma simples tabela. Por favor, pesquise por uma interface específica e sua disponibilidade.

diff --git a/files/pt-br/web/api/customelementregistry/index.html b/files/pt-br/web/api/customelementregistry/index.html new file mode 100644 index 0000000000..b1e3be4458 --- /dev/null +++ b/files/pt-br/web/api/customelementregistry/index.html @@ -0,0 +1,93 @@ +--- +title: CustomElementRegistry +slug: Web/API/CustomElementRegistry +translation_of: Web/API/CustomElementRegistry +--- +

{{DefaultAPISidebar("Web Components")}}

+ +

A interface CustomElementRegistry provê métodos para registro de elementos customizados e busca de elementos registrados. Para instancia-lo, use a propriedade {{domxref("window.customElements")}}. 

+ +

Métodos

+ +
+
{{domxref("CustomElementRegistry.define()")}}
+
Define um novo elemento customizado.
+
{{domxref("CustomElementRegistry.get()")}}
+
Retorna o construtor do nome do elemento informado, ou undefined caso não tenha sido definido.
+
{{domxref("CustomElementRegistry.whenDefined()")}}
+
Retorna um {{jsxref("Promise", "promise")}} vazio que é resolvido quando o elemento customizado é inserido. Se o elemento já foi definido, o retorno ja é informado.
+
+ +

Exemplos

+ +

O código a seguir foi pego do nosso word-count-web-component exemplo (veja em ação). Perceba que usamos o método {{domxref("CustomElementRegistry.define()")}} para definir um elemento customizado.

+ +
// Cria uma classe para o elemento
+class WordCount extends HTMLParagraphElement {
+  constructor() {
+    // Sempre execute primeiro o método super
+    super();
+
+    // Conta as palavras no elemento pai
+    var wcParent = this.parentNode;
+
+    function countWords(node){
+      var text = node.innerText || node.textContent
+      return text.split(/\s+/g).length;
+    }
+
+    var count = 'Words: ' + countWords(wcParent);
+
+    // Cria um shadow root
+    var shadow = this.attachShadow({mode: 'open'});
+
+    // Cria um nó de texto e adiciona o contador de palavra nele
+    var text = document.createElement('span');
+    text.textContent = count;
+
+    // Acrescenta ao shadow root
+    shadow.appendChild(text);
+
+
+    // Atualiza o contador quando houver mudança
+    setInterval(function() {
+      var count = 'Words: ' + countWords(wcParent);
+      text.textContent = count;
+    }, 200)
+
+  }
+}
+
+// Define um novo elemento
+customElements.define('word-count', WordCount, { extends: 'p' });
+ +
+

Note: The CustomElementsRegistry is available through the {{domxref("Window.customElements")}} property.

+
+ +

Especificações

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("HTML WHATWG", "custom-elements.html#customelementregistry", "CustomElementRegistry")}}{{Spec2("HTML WHATWG")}}Definição inicial
+ +

Compatibilidade de navegadores

+ +

 

+ + + +

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

+ +

 

diff --git a/files/pt-br/web/api/datatransfer/index.html b/files/pt-br/web/api/datatransfer/index.html new file mode 100644 index 0000000000..96358c84d0 --- /dev/null +++ b/files/pt-br/web/api/datatransfer/index.html @@ -0,0 +1,383 @@ +--- +title: DataTransfer +slug: Web/API/DataTransfer +translation_of: Web/API/DataTransfer +--- +
{{APIRef("HTML DOM")}}
+ +

{{ gecko_minversion_header("1.9") }} O objeto DataTransfer é usado para guardar os dados que estão sendo arrastados durante uma operação de Drag e Drop (arrastar e soltar). Ele pode guardar um ou mais itens de dados, cada um de um ou mais tipos de dados. Para mais informações sobre drag e drop (arrastar e soltar), veja Drag and Drop.

+ +

Esse objeto está disponível pela propriedade dataTransfer de todos os eventos de drag. Ele não pode ser criado separadamente.

+ +

Visão geral das propriedades

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropriedadesTipo
dropEffectString
effectAllowedString
files {{ gecko_minversion_inline("1.9.2") }}{{ domxref("FileList") }}
mozCursor {{ non-standard_inline() }} {{ gecko_minversion_inline("1.9.1") }}String
mozItemCount {{ non-standard_inline() }}unsigned long
mozSourceNode {{ non-standard_inline() }} {{ gecko_minversion_inline("2") }}{{ domxref("Node") }}
mozUserCancelledBoolean
typesDOMStringList
+ +

Visão geral dos métodos

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
void addElement(in Element element)
void clearData([in String type])
String getData(in String type)
void setData(in String type, in String data)
void setDragImage(in nsIDOMElement image, in long x, in long y)
void mozClearDataAt([in String type, in unsigned long index])
nsIVariant mozGetDataAt(in String type, in unsigned long index)
void mozSetDataAt(in String type, in nsIVariant data, in unsigned long index)
StringList mozTypesAt([in unsigned long index])
+ +

Propriedades

+ +

dropEffect

+ +

O efeito atual que será usado, e deve sempre ser um dos possíveis valores de effectAllowed. Isso afetará qual cursor será exibido enquanto arrasta.

+ +

Para os eventos dragenter e dragover, o dropEffect será inicializado com base na ação que o usuário está solicitando. Como isso é determinado é específico da plataforma, mas, normalmente o usuário pode pressionar teclas de modificação, como a tecla alt, para ajustar qual ação é desejada. Com um manipulador de evento para os eventos dragenter e dragover, o dropEffect deverá ser modificado se a ação desejada é diferente da ação que o usuário está solicitando.

+ +

Para os eventos dragstart, drag, e dragleave, o dropEffect será inicializado como "none". Qualquer valor atribuído à dropEffect será definido, mas o valor não será usado para nada.

+ +

Para os eventos drop e dragend, o dropEffect será inicializado para a ação que foi desejada, que será o valor que o dropEffect tinha depois do último evento de dragenter ou dragover. Em um evento de dragend, por exemplo, se a o dropEffect desejado for "move", então os dados que estão sendo arrastados deverão ser removidos da origem.

+ +

Valores possíveis:

+ + + +

Atribuindo qualquer outro valor não terá efeito e o valor antigo será mantido.

+ +

effectAllowed

+ +

Especifica os efeitos que são permitidos para esse drag. Você pode definir isso no evento dragstart para definir os efeitos desejados para a origem. Com os eventos dragenter e dragover, o effectAllowed será definido para qualquer que seja o valor que foi atribuído durante o evento dragstart. Isso pode ser usado para determinar quais efeitos são permitidos. Atribuindo um valor para effectAllowed nos outros eventos, exceto dragstart, não terá efeito.

+ +

Valores possíveis:

+ + + +

Atribuindo qualquer outro valor não terá efeito e permanece o valor anterior.

+ +

files

+ +

{{ gecko_minversion_header("1.9.2") }}

+ +

Contains a list of all the local files available on the data transfer. If the drag operation doesn't involve dragging files, this property is an empty list. An invalid index access on the {{ domxref("FileList") }} specified by this property will return undefined.

+ +

Example

+ +

These examples dump the list of files dragged into the browser window.

+ + + +

types

+ +

Guarda uma lista dos tipos de formato dos dados que estão armazenados para o primeiro ítem, na mesma ordem que os dados foram adicionados. Uma lista vazia será retornada caso nenhum dado tenha sido adicionado.

+ +

{{ gecko_minversion_note("1.9.2", 'A string "Files" é incluída nessa lista se houverem arquivos sendo arrastados.') }}

+ +

{{ h3_gecko_minversion("mozCursor", "1.9.1", "mozCursor") }}

+ +

O estado do cursor de drag. Isto é usado principalmente para controlar o cursor durante a guia de drag.

+ +
Nota: Esse método está atualmente implementado somento no Windows.
+ +

Valores possíveis

+ +
+
auto
+
Utiliza o comportamento padrão do sistema.
+
default
+
Utiliza o comportamento padrão Gecko, que é definir o cursor para uma seta durante a operação de arrastar.
+
+ +
Nota: Se você especificar qualquer valor diferente de "default", "auto" é assumido.
+ +

mozItemCount

+ +

O número de ítens sendo arrastados.

+ +
Nota: Essa propriedade é específica Gecko.
+ +

mozSourceNode

+ +

{{ gecko_minversion_header("2") }}

+ +

O {{ domxref("Node") }} sobre o qual o cursor do mouse estava localizado quando o botão foi pressionado para iniciar a operação de arrastar. O valor é null para drags externos ou se o elmento não pode acessar o node.

+ +
Nota: Essa propriedade é específica Gecko.
+ +

mozUserCancelled

+ +

Essa propriedade é aplicada apenas no evento dragend, e é true se o usuário cancelar a operação de arrastar pressionando escape (esc). Será false em qualquer outro caso, incluindo se a operação de arrastar falhar por algum motivo, por exemplo devido a ação de soltar em um local inválido.

+ +
Nota: Essa propriedade é específica Gecko.
+ +

Methods

+ +

addElement()

+ +

Set the drag source. Usually you would not change this, but it will affect which node the drag and dragend events are fired at. The default target is the node that was dragged.

+ +
 void addElement(
+   in Element element
+ );
+
+ +
Parameters
+ +
+
element
+
The element to add.
+
+ +

clearData()

+ +

Remove the data associated with a given type. The type argument is optional. If the type is empty or not specified, the data associated with all types is removed. If data for the specified type does not exist, or the data transfer contains no data, this method will have no effect.

+ +
 void clearData(
+   [optional] in String type
+ );
+
+ +
Parameters
+ +
+
type
+
The type of data to remove.
+
+ +

getData()

+ +

Retrieves the data for a given type, or an empty string if data for that type does not exist or the data transfer contains no data.

+ +

A security error will occur if you attempt to retrieve data during a drag that was set from a different domain, or the caller would otherwise not have access to. This data will only be available once a drop occurs during the drop event.

+ +
 String getData(
+   in String type
+ );
+
+ +
Parameters
+ +
+
type
+
The type of data to retrieve.
+
+ +

setData()

+ +

Set the data for a given type. If data for the type does not exist, it is added at the end, such that the last item in the types list will be the new format. If data for the type already exists, the existing data is replaced in the same position. That is, the order of the types list is not changed when replacing data of the same type.

+ +
 void setData(
+   in String type,
+   in String data
+ );
+
+ +
Parameters
+ +
+
type
+
The type of data to add.
+
data
+
The data to add.
+
+ +

setDragImage()

+ +

Set the image to be used for dragging if a custom one is desired. Most of the time, this would not be set, as a default image is created from the node that was dragged.

+ +

If the node is an HTML img element, an HTML canvas element or a XUL image element, the image data is used. Otherwise, image should be a visible node and the drag image will be created from this. If image is null, any custom drag image is cleared and the default is used instead.

+ +

The coordinates specify the offset into the image where the mouse cursor should be. To center the image, for instance, use values that are half the width and height of the image.

+ +
 void setDragImage(
+   in Element image,
+   in long x,
+   in long y
+ );
+
+ +
Parameters
+ +
+
image
+
An element to use as the drag feedback image
+
x
+
Horizontal offset within the image.
+
y
+
Vertical offset within the image.
+
+ +

mozClearDataAt()

+ +

Removes the data associated with the given format for an item at the specified index. The index is in the range from zero to the number of items minus one.

+ +

If the last format for the item is removed, the entire item is removed, reducing mozItemCount by one.

+ +

If the format list is empty, then the data associated with all formats is removed. If the format is not found, then this method has no effect.

+ +
Note: This method is Gecko-specific.
+ +
 void mozClearDataAt(
+   [optional] in String type,
+   in unsigned long index
+ );
+
+ +
Parameters
+ +
+
type
+
The type of data to remove.
+
index
+
The index of the data to remove.
+
+ +

mozGetDataAt()

+ +

Retrieves the data associated with the given format for an item at the specified index, or null if it does not exist. The index should be in the range from zero to the number of items minus one.

+ +
Note: This method is Gecko-specific.
+ +
 nsIVariant mozGetDataAt(
+   [optional] in String type,
+   in unsigned long index
+ );
+
+ +
Parameters
+ +
+
type
+
The type of data to retrieve.
+
index
+
The index of the data to retrieve.
+
+ +

mozSetDataAt()

+ +

A data transfer may store multiple items, each at a given zero-based index. mozSetDataAt() may only be called with an index argument less than mozItemCount in which case an existing item is modified, or equal to mozItemCount in which case a new item is added, and the mozItemCount is incremented by one.

+ +

Data should be added in order of preference, with the most specific format added first and the least specific format added last. If data of the given format already exists, it is replaced in the same position as the old data.

+ +

The data should be either a string, a primitive boolean or number type (which will be converted into a string) or an {{ interface("nsISupports") }}.

+ +
Note: This method is Gecko-specific.
+ +
 void mozSetDataAt(
+   [optional] in String type,
+   in nsIVariant data,
+   in unsigned long index
+ );
+
+ +
Parameters
+ +
+
type
+
The type of data to add.
+
data
+
The data to add.
+
index
+
The index of the data to add.
+
+ +

mozTypesAt()

+ +

Holds a list of the format types of the data that is stored for an item at the specified index. If the index is not in the range from 0 to the number of items minus one, an empty string list is returned.

+ +
Note: This method is Gecko-specific.
+ +
 nsIVariant mozTypesAt(
+   in unsigned long index
+ );
+
+ +
Parameters
+ +
+
index
+
The index of the data for which to retrieve the types.
+
+ +

See also

+ +

Drag and Drop

+ +

{{ languages( { "ja": "Ja/DragDrop/DataTransfer" } ) }}

diff --git a/files/pt-br/web/api/deviceacceleration/index.html b/files/pt-br/web/api/deviceacceleration/index.html new file mode 100644 index 0000000000..7f46e75436 --- /dev/null +++ b/files/pt-br/web/api/deviceacceleration/index.html @@ -0,0 +1,42 @@ +--- +title: DeviceAcceleration +slug: Web/API/DeviceAcceleration +tags: + - API + - Experimental + - Interface +translation_of: Web/API/DeviceMotionEventAcceleration +--- +
{{ ApiRef("Device Orientation Events") }}{{SeeCompatTable}}
+ +

Um objeto DeviceAcceleration fornece informações sobre a quantidade de aceleração que o dispositivo desempenha ao longo dos três eixos.

+ +

Propriedades

+ +
+
{{domxref("DeviceAcceleration.x")}} {{readonlyInline}}
+
A quantidade de aceleração ao longo do eixo X. Somente leitura.
+
{{domxref("DeviceAcceleration.y")}} {{readonlyInline}}
+
A quantidade de aceleração ao longo do eixo Y. Somente leitura.
+
{{domxref("DeviceAcceleration.z")}} {{readonlyInline}}
+
A quantidade de aceleração ao longo do eixo Z.Somente leitura.
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçõesStatusComentario
{{SpecName("Device Orientation", "#device_acceleration", "DeviceAcceleration")}}{{Spec2("Device Orientation")}}Definição inicial
diff --git a/files/pt-br/web/api/devicerotationrate/index.html b/files/pt-br/web/api/devicerotationrate/index.html new file mode 100644 index 0000000000..bce9a29495 --- /dev/null +++ b/files/pt-br/web/api/devicerotationrate/index.html @@ -0,0 +1,92 @@ +--- +title: DeviceRotationRate +slug: Web/API/DeviceRotationRate +translation_of: Web/API/DeviceMotionEventRotationRate +--- +

{{ ApiRef("Device Orientation Events") }} {{SeeCompatTable}}

+ +

Um objeto DeviceRotationRate fornece informações sobre a taxa na qual o dispositivo está girando em torno de todos os três eixos.

+ +

Properties

+ +
+
{{ domxref("DeviceRotationRate.alpha") }} {{readonlyInline}}
+
A quantidade de rotação em torno do eixo Z, em graus por segundo.
+
{{ domxref("DeviceRotationRate.beta") }} {{readonlyInline}}
+
A quantidade de rotação em torno do eixo Y, em graus por segundo
+
{{ domxref("DeviceRotationRate.gamma") }} {{readonlyInline}}
+
A quantidade de rotação em torno do eixo X, em graus por segundo
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificacõesStatusComentario
{{SpecName('Device Orientation')}}{{Spec2('Device Orientation')}}Definição inicial.
+ + + +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticasChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticasAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
diff --git a/files/pt-br/web/api/devicestorage.get/index.html b/files/pt-br/web/api/devicestorage.get/index.html new file mode 100644 index 0000000000..9258c4da29 --- /dev/null +++ b/files/pt-br/web/api/devicestorage.get/index.html @@ -0,0 +1,58 @@ +--- +title: DeviceStorage.get +slug: Web/API/DeviceStorage.get +tags: + - API + - B2G + - Device Storage + - Firefox OS + - Method + - Non Standard + - Non-standard + - Não Padrão + - Reference + - Referencia + - WebAPI + - metodo +translation_of: Archive/B2G_OS/API/DeviceStorage/get +--- +

{{ non-standard_header() }}

+

{{ B2GOnlyHeader2('privileged') }}

+

Sumário

+

O metodo get é usado para obter um arquivo somente-leitura de uma dada área de armazenamento.

+

Caso o pedido seja bem-sucedido, o resultado do pedido result é um objeto {{domxref("File")}} contendo os dados do arquivo original do dispositivo.

+

Sintaxe

+
var instanciaDeDOMRequest = instanciaDeDeviceStorage.get(nomeDoArquivo);
+

Parametros

+
+
+ nomeDoArquivo
+
+ Uma string representando o nome completo (caminho + nome do arquivo) do arquivo a ser obtido.
+
+

Retorno

+

Retorna um objeto {{domxref("DOMRequest")}} para manipular o sucesso ou o erro da operação.

+

Exemplo

+
var sdcard = navigator.getDeviceStorage("sdcard");
+
+var pedido = sdcard.get("meuArquivo.txt");
+
+pedido.onsuccess = function () {
+  var name = this.result.name;
+  console.log('O arquivo "' + name + '" foi obtido com sucesso da área de armazenamento do sdcard');
+}
+
+request.onerror = function () {
+  console.warn('Nao foi possivel obter o arquivo: ' + this.error);
+}
+
+

Especificação

+

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

+

Veja também

+ diff --git a/files/pt-br/web/api/devicestorage.onchange/index.html b/files/pt-br/web/api/devicestorage.onchange/index.html new file mode 100644 index 0000000000..1b1b1db375 --- /dev/null +++ b/files/pt-br/web/api/devicestorage.onchange/index.html @@ -0,0 +1,30 @@ +--- +title: DeviceStorage.onchange +slug: Web/API/DeviceStorage.onchange +translation_of: Archive/B2G_OS/API/DeviceStorage/onchange +--- +

{{ ApiRef() }}

+

{{ non-standard_header() }}

+

{{ B2GOnlyHeader2('privileged') }}

+

Resumo

+

A propriedade onchange é usado para especificar um manuseador de eventos para receber eventos {{event("change")}}. Estes eventos são disparados cada vez que um arquivo é criado, modificado ou excluído na area de armazenamento.

+

Sintaxe

+
instanceOfDeviceStorage.onchange = funcRef
+

Onde funcRef é uma função para ser chamada quando o evento {{event("change")}} ocorre. Estes eventos são do tipo {{domxref("DeviceStorageChangeEvent")}}.

+

Exemplo

+
var sdcard = navigator.getDeviceStorage('sdcard');
+
+sdcard.onchange = function (change) {
+  var reason = change.reason;
+  var path   = change.path;
+
+  console.log('O arquivo "' + path + '" foi ' + reason);
+}
+

Especificação

+

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

+

Veja também

+ diff --git a/files/pt-br/web/api/document/activeelement/index.html b/files/pt-br/web/api/document/activeelement/index.html new file mode 100644 index 0000000000..c29692eaf3 --- /dev/null +++ b/files/pt-br/web/api/document/activeelement/index.html @@ -0,0 +1,164 @@ +--- +title: Document.activeElement +slug: Web/API/Document/activeElement +tags: + - API + - Document + - HTML DOM + - Property + - Reference +translation_of: Web/API/DocumentOrShadowRoot/activeElement +--- +

{{APIRef("DOM")}}

+ +

Retorna o {{ domxref("Element", "elemento") }} atualmente em foco, ou seja, o elemento que receberá os eventos do teclado caso o usuário digite algo. Esse atributo é somente-leitura.

+ +

Geralmente retorna um {{ HTMLElement("input") }} ou {{ HTMLElement("textarea") }}, caso esteja com uma seleção de texto ativa. Caso esteja, pode obter mais informações sobre a seleção utilizando as propriedades selectionStartselectionEnd. Caso o elemento em foco seja um {{ HTMLElement("select") }}(menu) ou {{ HTMLElement("input") }} do tipo button, checkbox ou radio.

+ +
Note: No Mac, elementos que nao sejam campos de texto geralmente não recebem foco.
+ +

Normalmente o usuário pode navegar entre os elementos que pode receber foco na página com o uso da tecla tab e ativar estes elementos com a tecla espaço (apertar um botão ou selecionar uma opção).

+ +

Não confunda foco com uma seleção de texto no documento, que consiste em sua maioria de nódos de texto estáticos. Veja {{ domxref("window.getSelection()") }}.

+ +

Quando não há nada selecionado, o activeElement da página é o {{ HTMLElement("body") }} ou null

+ +
+

Este atributo é parte da seção "Em desenvolvimento" da especificação do HTML 5.

+
+ +

Sintaxe

+ +
var curElement = document.activeElement;
+
+ +

Exemplo

+ +
<!DOCTYPE HTML>
+<html>
+<head>
+    <script type="text/javascript" charset="utf-8">
+    function init() {
+
+        function onMouseUp(e) {
+            console.log(e);
+            var outputElement = document.getElementById('output-element');
+            var outputText = document.getElementById('output-text');
+            var selectedTextArea = document.activeElement;
+            var selection = selectedTextArea.value.substring(
+            selectedTextArea.selectionStart, selectedTextArea.selectionEnd);
+            outputElement.innerHTML = selectedTextArea.id;
+            outputText.innerHTML = selection;
+        }
+
+        document.getElementById("ta-example-one").addEventListener("mouseup", onMouseUp, false);
+        document.getElementById("ta-example-two").addEventListener("mouseup", onMouseUp, false);
+    }
+    </script>
+</head>
+<body onload="init()">
+<div>
+    Select some text from one of the Textareas below:
+</div>
+<form id="frm-example" action="#" accept-charset="utf-8">
+<textarea name="ta-example-one" id="ta-example-one" rows="8" cols="40">
+This is Textarea Example One:
+Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec tincidunt, lorem a porttitor molestie, odio nibh iaculis libero, et accumsan nunc orci eu dui.
+</textarea>
+<textarea name="ta-example-two" id="ta-example-two" rows="8" cols="40">
+This is Textarea Example Two:
+Fusce ullamcorper, nisl ac porttitor adipiscing, urna orci egestas libero, ut accumsan orci lacus laoreet diam. Morbi sed euismod diam.
+</textarea>
+</form>
+Active Element Id: <span id="output-element"></span><br/>
+Selected Text: <span id="output-text"></span>
+
+</body>
+</html>
+
+ +

View on JSFiddle

+ +

Notas

+ +

Originalmente apresentada como extensão DOM proprietária no Internet Explorer 4, esta propriedade também é suportada no Opera e Safari (versão 4 ou maior)

+ +

Especificações

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'interaction.html#dom-document-activeelement', 'activeElement')}}{{Spec2('HTML WHATWG')}} 
+ +

Compatibilidade nos navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support23.04 [1]9.64.0
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

[1]: O IE9 tem um bug que ao tentar acessar o activeElement do {{domxref("window.parent")}} {{domxref("Document")}} de um {{HTMLElement("iframe")}}(i.e. parent.document.activeElement) é lançado um erro

+ +

Eventos relacionados

+ + diff --git a/files/pt-br/web/api/document/alinkcolor/index.html b/files/pt-br/web/api/document/alinkcolor/index.html new file mode 100644 index 0000000000..85d2bfaa77 --- /dev/null +++ b/files/pt-br/web/api/document/alinkcolor/index.html @@ -0,0 +1,36 @@ +--- +title: Document.alinkColor +slug: Web/API/Document/alinkColor +tags: + - Depreciado + - Propriedade + - Referencia +translation_of: Web/API/Document/alinkColor +--- +
{{APIRef("DOM")}}{{Deprecated_header}}
+ +

Retorna ou define a cor de um link ativo no corpo do documento. Um link está ativo durante o tempo entre os eventos mousedown e mouseup.

+ +

Sintaxe

+ +
var color = document.alinkColor;
+document.alinkColor = color;
+
+ +

color é uma string que contém o nome da cor (e.g., blue, darkblue, etc.) ou o valor hexadecimal da cor (e.g., #0000FF)

+ +

Notas

+ +

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

+ +

document.alinkColor está obsoleto em DOM Level 2 HTML. Uma alternativa é o seletor de CSS {{Cssxref(":active")}}.

+ +

Outra alternativa é document.body.aLink, embora tenha sido depreciado no HTML 4.01 a favor da alternativa CSS.

+ +

Gecko suporta ambos alinkColor/:active e {{Cssxref(":focus")}}. Suporte para Internet Explorer 6 e 7 alinkColor/:active apenas para HTML anchor (<a>) links e o comportamento é o mesmo que :focus sob Gecko. Não há suporte para :focus no IE.

+ +

Compatibilidade do navegador

+ + + +

{{Compat("api.Document.alinkColor")}}

diff --git a/files/pt-br/web/api/document/anchors/index.html b/files/pt-br/web/api/document/anchors/index.html new file mode 100644 index 0000000000..624c955b0e --- /dev/null +++ b/files/pt-br/web/api/document/anchors/index.html @@ -0,0 +1,107 @@ +--- +title: Document.anchors +slug: Web/API/Document/anchors +tags: + - API + - Deprecated + - HTML DOM + - NeedsCompatTable + - Property + - Reference +translation_of: Web/API/Document/anchors +--- +
{{APIRef("DOM")}}
+ +

{{deprecated_header("HTML5")}}

+ +

anchors retorna uma lista de todas as âncoras no documento.

+ +

Sintaxe

+ +
nodeList = document.anchors;
+
+ +

Exemplo

+ +
if ( document.anchors.length >= 5 ) {
+  dump("dump found too many anchors");
+  window.location = "http://www.google.com";
+}
+
+ +

O código a seguir é um exemplo que popula automaticamente um índice de conteúdo com cada âncora encontrada na página:

+ +
<!DOCTYPE html>
+<html lang="en">
+<head>
+<meta charset="UTF-8" />
+<title>Test</title>
+<script>
+function init() {
+  var toc = document.getElementById("toc");
+  var i, li, newAnchor;
+  for (i = 0; i < document.anchors.length; i++) {
+    li = document.createElement("li");
+    newAnchor = document.createElement('a');
+    newAnchor.href = "#" + document.anchors[i].name;
+    newAnchor.innerHTML = document.anchors[i].text;
+    li.appendChild(newAnchor);
+    toc.appendChild(li);
+  }
+}
+</script>
+
+</head>
+<body onload="init()">
+
+<h1>Title</h1>
+<h2><a name="contents">Contents</a></h2>
+<ul id="toc"></ul>
+
+<h2><a name="plants">Plants</a></h2>
+<ol>
+    <li>Apples</li>
+    <li>Oranges</li>
+    <li>Pears</li>
+</ol>
+
+<h2><a name="veggies">Veggies</a></h2>
+<ol>
+    <li>Carrots</li>
+    <li>Celery</li>
+    <li>Beats</li>
+</ol>
+
+</body>
+</html>
+
+ +

View on JSFiddle

+ +

Notas

+ +

Por motivos de compatibilidade, o conjunto de âncoras retornadas por anchors contém apenas as âncoras criadas com o atributo name, não incluindo as âncoras criadas com o atributo {{ htmlattrxref("id") }}.

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#dom-document-anchors', 'Document.anchors')}}{{ Spec2('HTML WHATWG') }}Obsoleted.
{{SpecName('DOM2 HTML', 'html.html#ID-7577272', 'Document.anchors')}}{{ Spec2('DOM2 Events') }}Initial definition.
diff --git a/files/pt-br/web/api/document/bgcolor/index.html b/files/pt-br/web/api/document/bgcolor/index.html new file mode 100644 index 0000000000..66ec8d48ca --- /dev/null +++ b/files/pt-br/web/api/document/bgcolor/index.html @@ -0,0 +1,35 @@ +--- +title: Document.bgColor +slug: Web/API/Document/bgColor +tags: + - Obsoleto + - Propriedade + - Referencia +translation_of: Web/API/Document/bgColor +--- +

{{APIRef("DOM")}} {{ Deprecated_header() }}

+ +

A propriedade obsoleta bgColor obtém ou atribue a cor de fundo do documento atual.

+ +

Sintaxe

+ +
color = document.bgColor
+document.bgColor = color
+
+ +

Parâmetros

+ + + +

Exemplo

+ +
document.bgColor = "darkblue";
+
+ +

Notas

+ +

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

+ +

document.bgColor está obsoleto no DOM Level 2 HTML. A alternativa recomendada é fazer uso do atributo CSS {{Cssxref("background-color")}} que pode ser acessado através do DOM com document.body.style.backgroundColor. Uma outra alternativa é o document.body.bgColor, apesar dessa também estar obsoleta no HTML 4.01 em funcão da alternativa do CSS.

diff --git a/files/pt-br/web/api/document/body/index.html b/files/pt-br/web/api/document/body/index.html new file mode 100644 index 0000000000..cb21522c4f --- /dev/null +++ b/files/pt-br/web/api/document/body/index.html @@ -0,0 +1,44 @@ +--- +title: Document.body +slug: Web/API/Document/body +translation_of: Web/API/Document/body +--- +
{{APIRef("DOM")}}
+ +

Retorna o elemento {{HTMLElement("body")}} ou o {{HTMLElement("frameset")}} do documento atual, ou null se nenhum destes elementos existir.

+ +

Sintaxe

+ +
var objRef = document.body;
+document.body = objRef;
+ +

Exemplo

+ +
// No HTML: <body id="oldBodyElement"></body>
+alert(document.body.id); // "oldBodyElement"
+
+var aNewBodyElement = document.createElement("body");
+
+aNewBodyElement.id = "newBodyElement";
+document.body = aNewBodyElement;
+alert(document.body.id); // "newBodyElement"
+
+ +

Notas

+ +

document.body é o elemento que envolve o conteúdo do documento. Em documentos com conteúdo no <body>, retorna o elemento <body>, e em documentos que usam frameset, retorna o elemento <frameset> mais periférico.

+ +

Apesar do body ser configurável, definir um novo body em um documento irá remover todos os elementos contidos no elemento <body> existente.

+ +

Especificação

+ + + +

Veja Também

+ + diff --git a/files/pt-br/web/api/document/characterset/index.html b/files/pt-br/web/api/document/characterset/index.html new file mode 100644 index 0000000000..30ec060745 --- /dev/null +++ b/files/pt-br/web/api/document/characterset/index.html @@ -0,0 +1,65 @@ +--- +title: Document.characterSet +slug: Web/API/Document/characterSet +tags: + - Documento + - Propriedade + - Referencia +translation_of: Web/API/Document/characterSet +--- +
{{ ApiRef("DOM") }}
+ +
A propriedade somente leitura Document.characterSet retorna a character encoding(codificação de caracteres) do documento com o qual ele é renderizado atualmente. (Uma codificação de caracteres é um conjunto de caracteres e como interpretar bytes nesses caracteres.)
+ +
+ +
+

Um “character set”(conjunto de caracteres) e “character encoding”(codificação de caracteres) estão relacionados, mas diferentes. Apesar do nome dessa propriedade, ela retorna a codificação.

+
+ +

Usuários podem sobrepor a codificação especificada pelo desenvolvedor dentro do cabeçalho Content-Type (tipo de conteúdo) ou embutida como <meta charset = "utf-8">, como no menu Exibir → Codificacao de Texto Essa substituição é fornecida para corrigir codificações especificadas pelo desenvolvedor incorretas que resultam em texto ilegivel.

+ +
+

As propriedades document.charset e document.inputEncoding são aliases legados para document.characterSet. Não use mais eles.

+
+ +

Sintaxe

+ +
var string = document.characterSet;
+ +

Exemplos

+ +
<button onclick="console.log(document.characterSet);">
+  Registro de Codificacao de Caracteres
+</button>
+<!-- mostra a codificacao de caracteres do documento no console do desevolvedor, como "ISO-8859-1" ou "UTF-8" -->
+
+ +

Especificações

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-document-characterset', 'characterSet')}}{{Spec2('DOM WHATWG')}} +

Definição Inicial.

+
+ +

Compatibilidade do navegador

+ + + +

{{Compat("api.Document.characterSet")}}

diff --git a/files/pt-br/web/api/document/close/index.html b/files/pt-br/web/api/document/close/index.html new file mode 100644 index 0000000000..7c9b110edd --- /dev/null +++ b/files/pt-br/web/api/document/close/index.html @@ -0,0 +1,27 @@ +--- +title: Document.close() +slug: Web/API/Document/close +translation_of: Web/API/Document/close +--- +

{{APIRef("DOM")}}

+ +

O metodo document.close() termina a gravação em um documento, aberto com  document.open().

+ +

Sintaxe

+ +
document.close();
+
+ +

Exemplo

+ +
// abre um documento e escreve nele.
+// escreve o conteúdo no documento.
+// fecha o documento.
+document.open();
+document.write("<p>O primeiro e unico conteúdo.</p>");
+document.close();
+
+ +

Especificação

+ +

DOM Level 2 HTML: close() Method

diff --git a/files/pt-br/web/api/document/compatmode/index.html b/files/pt-br/web/api/document/compatmode/index.html new file mode 100644 index 0000000000..1ca33ff573 --- /dev/null +++ b/files/pt-br/web/api/document/compatmode/index.html @@ -0,0 +1,42 @@ +--- +title: Document.compatMode +slug: Web/API/Document/compatMode +translation_of: Web/API/Document/compatMode +--- +

{{ ApiRef("DOM") }}

+ +

Indica se o documento está renderizado no Quirks mode ou no modo dos Padrões.

+ +

Sintaxe

+ +
modo = document.compatMode
+
+ +

Valores

+ + + +
+
modo
+
É um valor enumerado que pode ser:
+
+ +
+

Nota: todos estes modos agora são definidos em padrões, então os antigos nomes "standards" e "almost standards" são sem sentido, e portanto não são mais usados nos padrões.

+
+ +

Exemplo

+ +
if (document.compatMode == "BackCompat") {
+  // in Quirks mode
+}
+
+ +

Especificações

+ + diff --git a/files/pt-br/web/api/document/contenttype/index.html b/files/pt-br/web/api/document/contenttype/index.html new file mode 100644 index 0000000000..5d29907089 --- /dev/null +++ b/files/pt-br/web/api/document/contenttype/index.html @@ -0,0 +1,46 @@ +--- +title: Document.contentType +slug: Web/API/Document/contentType +translation_of: Web/API/Document/contentType +--- +
{{APIRef}}
+ +

Document.contentType é uma propriedade somente de leitura, que retorna o tipo MIME do documento que esta sendo rendenrizado.Isso pode vir de cabeçalhos HTPP ou de outras fontes de informações MIME, e pode se afetado por conversões realizadas pelo navegador ou pelas extenções.

+ +
+

Note: Esta proiedade não é afetada pelos elementos {{HTMLElement("meta")}}.

+
+ +

Sintaxe

+ +
contentType = document.contentType;
+
+ +

Value

+ +

contentType é uma propriedade somente de leitura.

+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('DOM WHATWG', '#dom-document-contenttype', 'Document.contentType')}}{{Spec2('DOM WHATWG')}}Definição inicial
+ +

Compatibilidade com os navegadores

+ + + +
{{Compat("api.Document.contentType")}}
diff --git a/files/pt-br/web/api/document/createelement/index.html b/files/pt-br/web/api/document/createelement/index.html new file mode 100644 index 0000000000..3cb88ecb37 --- /dev/null +++ b/files/pt-br/web/api/document/createelement/index.html @@ -0,0 +1,82 @@ +--- +title: Document.createElement() +slug: Web/API/Document/createElement +tags: + - Documento + - Referencia + - Referência(2) + - metodo +translation_of: Web/API/Document/createElement +--- +
{{APIRef("DOM")}}
+ +
 
+ +

Em um documento HTML, o método Document.createElement() cria o elemento HTML especificado ou um {{domxref("HTMLUnknownElement")}} se o nome do elemento dado não for conhecido.

+ +

Em um documento XUL, o elemento XUL especificado é criado.

+ +

Em outros documentos, ele cria um elemento com um namespace URI null.

+ +

Sintaxe

+ +
var elemento = document.createElement(nomeDaTag);
+
+ + + +

Exemplo

+ +

Este código cria uma nova <div> e a insere antes do elemento com ID "div1".

+ +

HTML

+ +
<!DOCTYPE html>
+<html>
+<head>
+  <title>||Trabalhando com elementos||</title>
+</head>
+<body>
+  <div id="div1">O texto acima foi criado dinamicamente.</div>
+</body>
+</html>
+
+ +

JavaScript

+ +
document.body.onload = adcElemento;
+
+function adcElemento () {
+  // cria um novo elemento div
+  // e dá à ele conteúdo
+  var divNova = document.createElement("div");
+  var conteudoNovo = document.createTextNode("Olá, cumprimentos!");
+  divNova.appendChild(conteudoNovo); //adiciona o nó de texto à nova div criada
+
+  // adiciona o novo elemento criado e seu conteúdo ao DOM
+  var divAtual = document.getElementById("div1");
+  document.body.insertBefore(divNova, divAtual);
+}
+ +

{{EmbedLiveSample("Exemplo", 500, 50)}}

+ +

Notas

+ + + +

Especificações

+ + diff --git a/files/pt-br/web/api/document/createelementns/index.html b/files/pt-br/web/api/document/createelementns/index.html new file mode 100644 index 0000000000..ece55f592e --- /dev/null +++ b/files/pt-br/web/api/document/createelementns/index.html @@ -0,0 +1,90 @@ +--- +title: Document.createElementNS() +slug: Web/API/Document/createElementNS +tags: + - API + - DOM + - Referencia + - metodo +translation_of: Web/API/Document/createElementNS +--- +
{{ApiRef("DOM")}}
+ +

Creates an element with the specified namespace URI and qualified name.

+ +

Cria um elemento com Namespace URI e nome qualificado, como especificado.

+ +

Syntax

+ +
element = document.createElementNS(namespaceURI, qualifiedName);
+
+ + + +

Namespace URI's válidos

+ + + +

Exemplo

+ +

Isso cria um novo elemento <div> no namespace XHTML e anexa ele ao elemento vbox. Embora isso não seja um documento XUL extremamente útil, pode demonstrar o uso de elementos de dois namespaces diferentes em apenas um documento:

+ +
<?xml version="1.0"?>
+<page xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
+      xmlns:html="http://www.w3.org/1999/xhtml"
+      title="||Working with elements||"
+      onload="init()">
+
+<script type="text/javascript"><![CDATA[
+ var container;
+ var newdiv;
+ var txtnode;
+
+ function init(){
+   container = document.getElementById("ContainerBox");
+   newdiv = document.createElementNS("http://www.w3.org/1999/xhtml","div");
+   txtnode = document.createTextNode("Este é o texto construído dinâmicamente com createElementNS e createTextNode então é inserido no documento usando appendChild.");
+   newdiv.appendChild(txtnode);
+   container.appendChild(newdiv);
+ }
+
+]]></script>
+
+ <vbox id='ContainerBox' flex='1'>
+  <html:div>
+   O script desta página irá colocar conteúdo dinâmico abaixo:
+  </html:div>
+ </vbox>
+
+</page>
+
+ +

Notas

+ +

O exemplo dado anteriormente usa script inline que não é recomendado em documentos XHTML. Este exemplo particular é atualmente um documento  XUL com XHTML incorporado, contudo, a recomendação ainda se aplica. scripts Inline  não causam nenhum problema neste pequeno exemplo, contudo, para qualquer trabalho sério você precisa ler sobre Uso correto de CSS e JavaScript en documentos XHTML.

+ +

Para criar um elemento sem especificar seu namespace URI, use o método createElement.

+ +

Especificação

+ + + +

Veja também

+ + diff --git a/files/pt-br/web/api/document/currentscript/index.html b/files/pt-br/web/api/document/currentscript/index.html new file mode 100644 index 0000000000..179c950916 --- /dev/null +++ b/files/pt-br/web/api/document/currentscript/index.html @@ -0,0 +1,99 @@ +--- +title: Document.currentScript +slug: Web/API/Document/currentScript +translation_of: Web/API/Document/currentScript +--- +
{{ ApiRef("DOM") }}
+ +
 
+ +

Retorna o elemento que está sendo processado atualmente.

+ +

Sintaxe

+ +
var curScriptElement = document.currentScript;
+
+ +

Exemplo

+ +

O exemplo abaixo verifica se o script está sendo executado de forma assíncrona:

+ +
if (document.currentScript.async) {
+  console.log("Execução assíncrona");
+} else {
+  console.log("Execução síncrona");
+}
+ +

View Live Examples

+ +

Nota

+ +

Se o código estiver sendo chamado como um callback ou manipulador de eventos, ele não irá referenciar o  elemento; a referência ao elemento só acontece quando ele está sendo processado inicialmente.

+ +

Compatibilidade nos navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte Básico29{{ CompatGeckoDesktop("2.0") }}{{ CompatNo() }} (as of IE11)16 +

+
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte Básico4.4{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{ CompatUnknown() }}{{ CompatUnknown() }}iOS 8
+
+ +

Especificações

+ + + +

Veja também

+ + diff --git a/files/pt-br/web/api/document/defaultview/index.html b/files/pt-br/web/api/document/defaultview/index.html new file mode 100644 index 0000000000..77ed7a4c72 --- /dev/null +++ b/files/pt-br/web/api/document/defaultview/index.html @@ -0,0 +1,28 @@ +--- +title: Document.defaultView +slug: Web/API/Document/defaultView +translation_of: Web/API/Document/defaultView +--- +
{{ ApiRef() }}
+ +

Sumário

+ +

Em navegadores, retorna o objeto window associado ao documento ou null se não houver.

+ +

Sintaxe

+ +
var win = document.defaultView;
+ +

Esta propriedade é de somente-leitura.

+ +

Notas

+ +

De acordo com o quirksmode, defaultView não é suportado no IE até o IE 9.

+ +

Especificação

+ + diff --git a/files/pt-br/web/api/document/designmode/index.html b/files/pt-br/web/api/document/designmode/index.html new file mode 100644 index 0000000000..b2c070008b --- /dev/null +++ b/files/pt-br/web/api/document/designmode/index.html @@ -0,0 +1,104 @@ +--- +title: Document.designMode +slug: Web/API/Document/designMode +translation_of: Web/API/Document/designMode +--- +
{{ ApiRef() }}
+ +
 
+ +

Sumário

+ +

document.designMode controla se o documento todo é editável. Valores validos são "on" e "off". De acordo com a especificação, esta propriedade é por padrão "off". Firefox segue este padrão. Nas versões anteriores do Chrome e IE o padrão é "inherit". No IE6-10, o valor é capitalizado.

+ +

Sintaxe

+ +
var mode = document.designMode;
+document.designMode = "on";
+document.designMode = "off";
+ +

Exemplo

+ +

Cria um documento {{HTMLElement("iframe")}} editável:

+ +
iframe_node.contentDocument.designMode = "on";
+
+ +

Especificação

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#making-entire-documents-editable:-the-designmode-idl-attribute', 'designMode')}}{{Spec2('HTML WHATWG')}}Initial definition.
+ +

Compatibilidade nos Browsers

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

 

+ +

Veja também:

+ + diff --git a/files/pt-br/web/api/document/doctype/index.html b/files/pt-br/web/api/document/doctype/index.html new file mode 100644 index 0000000000..72a731c314 --- /dev/null +++ b/files/pt-br/web/api/document/doctype/index.html @@ -0,0 +1,59 @@ +--- +title: Document.doctype +slug: Web/API/Document/doctype +translation_of: Web/API/Document/doctype +--- +
{{ApiRef("DOM")}}
+ +

Retorna a declaração do tipo de documento(Document Type Declaration (DTD)) associado ao documento atual. O objeto retornado implementa a interface {{domxref("DocumentType")}}. Use {{domxref("DOMImplementation.createDocumentType()")}} para criar um DocumentType.

+ +

Sintaxe

+ +
doctype = document.doctype;
+
+ + + +

Exemplo

+ +
var doctypeObj = document.doctype;
+
+console.log(
+  "doctypeObj.name: "           + doctypeObj.name            + "\n" +
+  "doctypeObj.internalSubset: " + doctypeObj.internalSubset  + "\n" +
+  "doctypeObj.publicId: "       + doctypeObj.publicId        + "\n" +
+  "doctypeObj.systemId: "       + doctypeObj.systemId
+);
+ +

Notas

+ +

A propriedade retornará null se não houvernehum  DTD associado ao documento atual.

+ +

O nível 2 do DOM não suporta a edição da declaração do tipo de documento.

+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('DOM WHATWG', '#dom-document-doctype', 'Document: doctype')}}{{Spec2('DOM WHATWG')}}
+ +

 Compatibilidade com os navegadores

+ + + +

{{Compat("api.Document.doctype")}}

diff --git a/files/pt-br/web/api/document/document/index.html b/files/pt-br/web/api/document/document/index.html new file mode 100644 index 0000000000..3152137704 --- /dev/null +++ b/files/pt-br/web/api/document/document/index.html @@ -0,0 +1,87 @@ +--- +title: Document() +slug: Web/API/Document/Document +translation_of: Web/API/Document/Document +--- +

{{APIRef}}{{Non-standard_header}}

+ +

O construtor Document cria um novo objeto {{domxref("Document")}},  o qual trata de uma página carregada no navegador servindo como porta de entrada para o conteúdo da página.

+ +

Sintaxe

+ +
var document = new Document()
+ +

Parâmetros

+ +

Nenhum.

+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('DOM WHATWG','#interface-document','Document')}}{{Spec2('DOM WHATWG')}}Definição inicial
+ +

Compatibilidade com Navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
NavegadorChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte{{CompatChrome(60)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOpera(47)}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
NavegadorAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Suporte{{CompatChrome(60)}}{{CompatChrome(60)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOperaMobile(47)}}{{CompatUnknown}}
+
diff --git a/files/pt-br/web/api/document/documentelement/index.html b/files/pt-br/web/api/document/documentelement/index.html new file mode 100644 index 0000000000..869cd7a75d --- /dev/null +++ b/files/pt-br/web/api/document/documentelement/index.html @@ -0,0 +1,43 @@ +--- +title: Document.documentElement +slug: Web/API/Document/documentElement +tags: + - Propriedade + - Referencia + - raiz +translation_of: Web/API/Document/documentElement +--- +

{{ ApiRef("DOM") }}

+ +

O  document.documentElement  retorna o Elemento que é o elemento raiz do documento (por exemplo, o elemento <html> para documentos HTML).

+ +

Sintaxe

+ +
var element = document.documentElement;
+
+ +

Exemplo

+ +
var rootElement = document.documentElement;
+var primeiroNivel = rootElement.childNodes;
+
+// primeiroNivel é a NodeList do filho direto do elemento raíz
+for (var i = 0; i < primeiroNivel.length; i++) {
+   // faça algo com cada filho direto do elemento raiz
+   // como primeiroNivel[i]
+
+}
+ +

Notas

+ +

Esta propriedade é uma conveniência somente leitura para obter o elemento raiz associado com qualquer documento.

+ +

Documentos HTML tipicamente contém somente um único nó filho, <html>, talvez com uma declaração DOCTYPE antes dele. Documentos XML, frequentemete contêm múltiplos nós filhos: o elemento de raiz, a declaração DOCTYPE, e as instruções de processamento.

+ +

É por isso que você deve usar document.documentElement em vez de {{Domxref ("document.firstChild")}} para obter o elemento raiz.

+ +

Especificações

+ + diff --git a/files/pt-br/web/api/document/documenturi/index.html b/files/pt-br/web/api/document/documenturi/index.html new file mode 100644 index 0000000000..52609f2bd5 --- /dev/null +++ b/files/pt-br/web/api/document/documenturi/index.html @@ -0,0 +1,53 @@ +--- +title: Document.documentURI +slug: Web/API/Document/documentURI +translation_of: Web/API/Document/documentURI +--- +
{{ApiRef("DOM")}}
+ +
A propiedade documentURI da interface {{domxref("Document")}} retorna uma string com a localização de um documento.
+ +
+ +
Na definição original DOM3 documentURI é um atributo de leitura/escrita.No padrão mais recente DOM4 é somente de leitura.
+ +

Sintaxe

+ +
var string = document.documentURI;
+
+ +

Notas

+ +

Os Documentos HTML tem uma propriedade {{domxref("document.URL")}} que retorna o mesmo valor (localização do documento).

+ +

A diferençã é que document.URL só pode ser usado em documentos HTML, enquanto documentURI está disponivel para todos os documentos web.

+ +

Specificações

+ + + + + + + + + + + + + + + + + + + + + +
SpecificaçãoStatusComentário
{{SpecName('DOM WHATWG', '#dom-document-documenturi','documentURI')}}{{Spec2('DOM WHATWG')}}
{{SpecName('DOM3 Core', '#Document3-documentURI', 'documentURI')}}{{Spec2('DOM3 Core')}}Initial definition
+ +

Compatibilidade de navegadores

+ + + +

{{Compat("api.Document.documentURI")}}

diff --git a/files/pt-br/web/api/document/elementfrompoint/index.html b/files/pt-br/web/api/document/elementfrompoint/index.html new file mode 100644 index 0000000000..ce447f2830 --- /dev/null +++ b/files/pt-br/web/api/document/elementfrompoint/index.html @@ -0,0 +1,132 @@ +--- +title: Document.elementFromPoint() +slug: Web/API/Document/elementFromPoint +tags: + - API + - CSSOM View + - Method + - NeedsMarkupWork + - NeedsMobileBrowserCompatibility + - Reference +translation_of: Web/API/DocumentOrShadowRoot/elementFromPoint +--- +
{{APIRef("DOM")}}
+ +

O método elementFromPoint() da interface {{domxref("Document")}} retorna o elemento de maior nível nas coordenadas especificadas.

+ +

Se o elemento no ponto especificado pertencer à outro documento (por exemplo, um subdocumento em um iframe), será retornado o pai do subdocumento (o próprio iframe). Se o elemento em determinado ponto for anônimo ou for um conteudo gerado por XBL, como por exemplo barras de scroll de caixas de texto, então será retornado o primeiro elemento pai, não-anônimo (por exemplo, a própria caixa de texto).

+ +

Se o ponto especificado estiver fora dos limites visíveis do documento ou tiver uma coordenada negativa, o resultado é null.

+ +

Se você precisa encontrar uma posição específica dentro do elemento, use {{domxref("Document.caretPositionFromPoint()")}}.

+ +

{{Note("Chamados por documentos XUL devem esperar até o evento onload ser acionado antes de chamar este método.")}}

+ +

Sintaxe

+ +
var element = document.elementFromPoint(x, y);
+ +

Parâmetros

+ +
+
x
+
Uma posição horizontal dentro do viewport atual.
+
y
+
Uma position vertical dentro do viewport atual.
+
+ +

Valor retornado

+ +

O objeto de nível mais alto {{domxref("Element")}} dentro das coordenadas declaradas.

+ +

Exemplo

+ +
<!DOCTYPE html>
+<html lang="en">
+<head>
+<title>exemplo de elementFromPoint</title>
+
+<script>
+function changeColor(newColor) {
+  elem = document.elementFromPoint(2, 2);
+  elem.style.color = newColor;
+}
+</script>
+</head>
+
+<body>
+<p id="para1">Algum texto aqui</p>
+<button onclick="changeColor('blue');">azul</button>
+<button onclick="changeColor('red');">vermelho</button>
+</body>
+</html>
+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComment
{{SpecName('CSSOM View', '#dom-document-elementfrompoint', 'elementFromPoint')}}{{Spec2('CSSOM View')}}Definição Inicial.
+ +

Compatibilidade entre navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support {{CompatChrome(4.0)}}35.510.50{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeAndroidChrome para AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
diff --git a/files/pt-br/web/api/document/elementoregistrado/index.html b/files/pt-br/web/api/document/elementoregistrado/index.html new file mode 100644 index 0000000000..bff318b3a9 --- /dev/null +++ b/files/pt-br/web/api/document/elementoregistrado/index.html @@ -0,0 +1,132 @@ +--- +title: Document.registerElement() +slug: Web/API/Document/ElementoRegistrado +tags: + - DOM + - Document.registerElement() + - ELEMENTO DOM + - Web Components + - registerElement +translation_of: Web/API/Document/registerElement +--- +

{{APIRef("DOM")}}

+ +
+

Note:document.registerElement() está depreciado em favor do customElements.define().

+
+ +

O método document.registerElement() registra um novo elemento personalizado no browser e returna um construtor para o novo elemento.

+ +
+

Nota: Esta é uma tecnologia experimental. O browser você precisa usar suporte à componentes web. Veja Habilitando componentes web no Firefox.

+
+ +

Sintaxe

+ +
var constructor = document.registerElement(tag-name, options);
+ +

Parâmetros

+ +
+
tag-name
+
O nome do elemento personalizado. O nome precisa conter um dash (-), por exemplo minha-tag.
+
Opções{{optional_inline}}
+
+

Um projeto com propriedades protótipo como base para o elememento personalizado, e extends, uma existente tag para estender. Ambos são opcionais.

+
+
+ +

Exemplo

+ +

Aqui é um exemplo muito simples:

+ +
var Mytag = document.registerElement('my-tag');
+
+ +

Agora as novas tags são registradas no browser.

+ +

Uma variável Mytag tem um construtor que você pode usar para criar um elemento my-tag nos documentos como seguem:

+ +
document.body.appendChild(new Mytag());
+ +

Isto insere um elemento vazio my-tag que será visível se você usar o browser para desenvolvedores. Isto não será visível se você usar a ferramenta visão da capacidade do código fonte do browser. E isto não será visível no browser a menos que você adicione alguns conteúdos para a tag. Aqui está um caminho para adicionar conteúdo a nova tag:

+ +
var mytag = document.getElementsByTagName("my-tag")[0];
+mytag.textContent = "I am a my-tag element.";
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('Custom Elements')}}{{Spec2('Custom Elements')}} +

definição inicial

+
+ +

Compatibilidade do Browser

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico3531[1]{{CompatNo}}25{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico4.4.431[1]{{CompatNo}}25{{CompatNo}}
+
+ +

[1] Esta API é implementada uma preferência

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/document/execcommand/index.html b/files/pt-br/web/api/document/execcommand/index.html new file mode 100644 index 0000000000..cc5e3d3da8 --- /dev/null +++ b/files/pt-br/web/api/document/execcommand/index.html @@ -0,0 +1,174 @@ +--- +title: Document.execCommand() +slug: Web/API/Document/execCommand +translation_of: Web/API/Document/execCommand +--- +
{{ApiRef("DOM")}}{{Obsolete_header}}
+ +

Quando um documento HTML está em designMode, seu objeto document  expõe um metodo execCommand para editar a região editável corrente, algo como elementos form inputs ou contentEditable.

+ +

A maioria dos comandos afetam apaenas uma área selecionada [seleção] (negrito, itálico, etc.), enquantos outros adicionam novos elementos (adicionar um link por exemplo), ou afetam uma linha toda (identação). Quando usando contentEditable, o metódo execCommand() afeta o elemento editável ativo.

+ +

Síntaxe

+ +
document.execCommand(aCommandName, aShowDefaultUI, aValueArgument)
+
+ +

Valor de Retorno

+ +

Um {{jsxref('Boolean')}} que tem valor false se o comando não é válido ou está desabilitado.

+ +
+

Nota: Retorna true se for parte da interação do usuário. Não tente utilizar o retorno para verificar o suporte do browser antes de chamar o comando.

+
+ +

Parâmetros

+ +
+
aCommandName
+
Uma {{domxref("DOMString")}} especificando o nome do comando a ser executado. Veja {{anch("Comandos")}} para um lista dos possíveis comandos.
+
aShowDefaultUI
+
Um {{jsxref("Boolean")}} indicando se a interface padrão do usuário deve ser mostrada. Isso não é implementado no Mozilla.
+
aValueArgument
+
Para comandos que requerem um argumento de entrada. É uma {{domxref("DOMString")}} provendo a informação. Por exemplo, insertImage requer uma URL da imagem a ser inserida. Use null se nenhum argumento é necessário.
+
+ +

Comandos

+ +
+
backColor
+
Muda a cor de fundo do documento. No modo styleWithCss, ele afeta a cor de fundo do bloco que contém. Isso requer um valor de {{cssxref("<color>")}} passado como argumento. Observe que o Internet Explorer usa isso para definir a cor do plano de fundo do texto.
+
bold
+
Ativa / desativa negrito na seleção ou no ponto de inserção. O Internet Explorer usa a tag {{HTMLElement("strong")}} no lugar de {{HTMLElement("b")}}.
+
ClearAuthenticationCache
+
Limpa todas as credenciais de autenticação do cache.
+
contentReadOnly
+
Torna o documento de conteúdo somente leitura ou editável. Isso requer um valor booleano true / false como argumento. (Não é suportado pelo Internet Explorer.)
+
copy
+
Copia a seleção atual para a área de transferência. As condições para ativar esse comportamento variam de um navegador para outro e evoluíram com o tempo. Verifique a Tabela de {{anch("Compatibilidade entre Browsers")}} para determinar se você pode usar no seu caso.
+
createLink
+
Cria um hiperlink a partir da seleção, mas apenas se houver uma seleção. Requer uma string URI como argumento para o href do link.  O URI deve conter pelo menos um único caractere, que pode ser um espaço em branco. (O Internet Explorer criará um link com um valor nulo.)
+
cut
+
Remove a seleção atual e a copia para a área de transferência. Quando esse comportamento é ativado, varia entre os navegadores e suas condições evoluíram com o tempo. Verifique a Tabela de {{anch("Compatibilidade entre Browsers")}} para mais detalhes.
+
decreaseFontSize
+
Adiciona a tag {{HTMLElement("small")}} ao redor da seleção ou no ponto de inserção. (Não é suportado pelo Internet Explorer.)
+
defaultParagraphSeparator
+
Altera o separador de parágrafos usado quando novos parágrafos são criados em regiões de texto editáveis. Veja Diferenças na geração de marcação para mais detalhes.
+
delete
+
Exclui o conteúdo da seleção atual.
+
enableAbsolutePositionEditor
+
Habilita ou desabilita a garra que permite mover elementos absolutamente posicionados. Está desabilitado por padrão no Firefox 63 Beta / Dev Edition ({{bug(1449564)}})
+
enableInlineTableEditing
+
Ativa ou desativa os controles de inserção e exclusão de linhas / colunas da tabela. Está desabilitado por padrão no Firefox 63 Beta / Dev Edition ({{bug(1449564)}}).
+
enableObjectResizing
+
Ativa ou desativa as alças de redimensionamento em imagens, tabelas e elementos absolutamente posicionados e outros objetos redimensionáveis. Está desabilitado por padrão no Firefox 63 Beta / Dev Edition ({{bug(1449564)}}).
+
fontName
+
Altera o nome da fonte para a seleção ou no ponto de inserção. Isso requer uma string com o nome da fonte (como "Arial") como argumento.
+
fontSize
+
Altera o tamanho da fonte para a seleção ou no ponto de inserção. Isso requer um número inteiro de 1-7 como argumento.
+
foreColor
+
Altera a cor da fonte para a seleção ou no ponto de inserção. Isso requer uma string de cor (hexadecimal) como argumento.
+
formatBlock
+
Adiciona um elemento de nível de bloco HTML ao redor da linha que contém a seleção atual, substituindo o elemento de bloco que contém a linha, se houver (no Firefox,  {{HTMLElement("blockquote")}} é a exceção - envolverá qualquer elemento de bloco que contenha). Requer uma sequência de nome de tag como argumento de valor. Praticamente todos os elementos em nível de bloco podem ser usados. (Internet Explorer e Edge suportam apenas tags de cabeçalho  H1H6, ADDRESS, e PRE, que devem estar entre colchetes angulares, como "<H1>".)
+
forwardDelete
+
Exclui o caractere depois da posição do cursor, idêntico a pressionar a tecla Delete em um teclado do Windows.
+
heading
+
Adiciona um elemento de cabeçalho ao redor de uma linha de seleção ou ponto de inserção. Requer uma string com o nome da tag como argumento (ex. "H1", "H6"). (Não suportado pelo Internet Explorer e Safari.)
+
hiliteColor
+
Altera a cor do plano de fundo para a seleção ou no ponto de inserção. Requer uma sequência de valores de cores como argumento. useCSS tem de ser true para essa função. (Não é suportado pelo Internet Explorer.)
+
increaseFontSize
+
Adiciona uma tag {{HTMLElement("big")}} ao redor da seleção ou no ponto de inserção. (Não é suportado pelo Internet Explorer.)
+
indent
+
Recua a linha que contém o ponto de seleção ou inserção. No Firefox, se a seleção abranger várias linhas em diferentes níveis de recuo, apenas as linhas menos recuadas na seleção serão recuadas.
+
insertBrOnReturn
+
Controla se a tecla Enter insere um elemento {{HTMLElement("br")}}, ou divide o elemento do bloco atual em dois. (Não é suportado pelo Internet Explorer.)
+
insertHorizontalRule
+
Insere um elemento {{HTMLElement("hr")}} no ponto de inserção ou substitui a seleção por ele.
+
insertHTML
+
Insere uma string HTML no ponto de inserção (exclui a seleção). Requer uma string HTML válida como argumento. (Não é suportado pelo Internet Explorer.)
+
insertImage
+
Insere uma imagem no ponto de inserção (exclui a seleção). Requer uma string de URL para o src da imagem como argumento. Os requisitos para essa string são os mesmos que createLink.
+
insertOrderedList
+
Cria uma lista ordenada e numerada para a seleção ou no ponto de inserção.
+
insertUnorderedList
+
Cria uma lista não ordenada para a seleção ou no ponto de inserção.
+
insertParagraph
+
Insere um parágrafo ao redor da seleção ou da linha atual. (O Internet Explorer insere um parágrafo no ponto de inserção e exclui a seleção.)
+
insertText
+
Insere o texto fornecido no ponto de inserção (exclui a seleção).
+
italic
+
Ativa / desativa o itálico para a seleção ou no ponto de inserção. (O Internet Explorer usa o elemento {{HTMLElement("em")}} no lugar de {{HTMLElement("i")}}.)
+
justifyCenter
+
Centraliza o ponto de seleção ou inserção.
+
justifyFull
+
Justifica o ponto de seleção ou inserção.
+
justifyLeft
+
Justifica o ponto de seleção ou inserção à esquerda.
+
justifyRight
+
Justifica à direita a seleção ou o ponto de inserção.
+
outdent
+
Supera a linha que contém o ponto de seleção ou inserção.
+
paste
+
Cola o conteúdo da área de transferência no ponto de inserção (substitui a seleção atual). Desativado para conteúdo da web. Veja [1].
+
redo
+
Refaz o comando desfazer anterior.
+
removeFormat
+
Remove toda a formatação da seleção atual.
+
selectAll
+
Seleciona todo o conteúdo da região editável.
+
strikeThrough
+
Ativa / desativa o strikethrough(linha riscada) para a seleção ou no ponto de inserção.
+
subscript
+
Ativa / desativa o subscrito para a seleção ou no ponto de inserção.
+
superscript
+
Ativa / desativa o superscript para a seleção ou no ponto de inserção.
+
underline
+
Ativa / desativa o underline para a seleção ou no ponto de inserção.
+
undo
+
Desfaz o último comando executado.
+
unlink
+
Remove o elemento âncora de um hiperlink selecionado.
+
useCSS {{Deprecated_inline}}
+
Alterna o uso de tags HTML ou CSS para a marcação gerada. Requer um booleano true / false como argumento.
+

+ NOTA: Este argumento é logicamente reverso (ou seja, use false para usar CSS, true para usar HTML) e não é suportado pelo Internet Explorer. Isso foi preterido em favor do styleWithCSS.
+
styleWithCSS
+
Substitui o comando useCSS. true modifica / gera atributos de style na marcação, false gera elementos de apresentação(html).
+
+
+ +

Exemplo

+ +

Um exemplo de como usar a funcionalidade no CodePen.

+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
execCommand
+ +

Compatibilidade entre Browsers

+ + + +

{{Compat("api.Document.execCommand")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/document/fullscreen/index.html b/files/pt-br/web/api/document/fullscreen/index.html new file mode 100644 index 0000000000..6ad6fc604f --- /dev/null +++ b/files/pt-br/web/api/document/fullscreen/index.html @@ -0,0 +1,83 @@ +--- +title: Document.fullscreen +slug: Web/API/Document/fullscreen +tags: + - API + - Documento + - Javascript tela cheia + - Propriedade + - Referencia + - Somente Leitura + - Tela + - Tela Cheia + - display +translation_of: Web/API/Document/fullscreen +--- +
{{APIRef("Fullscreen API")}}{{Deprecated_Header}}
+ +

A propriedade de somente leitura da interface fullscreen retorna se o documento correspondente está mostrando conteúdo em modo de tela cheia (full-screen). 

+ +

Apesar dessa propriedade ser de somente leitura, ela não será executa se for modificada (mesmo em modo estrito); o setter não é um operador e não será modificado.

+ +
+

Nota: Desde que esta propriedade foi descontinuada, você pode determinar se o modo full-screen está ativo no documento checando se {{DOMxRef("Document.fullscreenElement")}} não é null.

+
+ +

Síntaxe

+ +
var isFullScreen = document.fullscreen;
+
+ +

Valor

+ +

Um valor booleano é true se o documento está mostrando um elemento no modo full-screen; se não, o valor é false.

+ +

Exemplo

+ +

Esta simples função retorna se o modo full-sreen está ativo, usando a obsoleta propriedade fullscreen.

+ +
function isDocumentInFullScreenMode() {
+  return document.fullscreen;
+}
+
+ +

Neste próximo exemplo, de outra maneira, usa a propriedade atual fullscreenElement para determinar a mesma coisa:

+ +
function isDocumentInFullScreenMode() {
+  return document.fullscreenElement !== null;
+}
+ +

Se fullscreenElement  não é null, retorna true, indicando se modo full-screen está sendo usado.

+ +

Específicações

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Fullscreen", "#dom-document-fullscreen", "Document.fullscreen")}}{{Spec2("Fullscreen")}}Definição inicial (como uma proprieda obsoleta).
+ +

Compatibilidade de navegadores

+ + + +

{{Compat("api.Document.fullscreen")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/document/getelementbyid/index.html b/files/pt-br/web/api/document/getelementbyid/index.html new file mode 100644 index 0000000000..c77a93fed9 --- /dev/null +++ b/files/pt-br/web/api/document/getelementbyid/index.html @@ -0,0 +1,133 @@ +--- +title: document.getElementById() +slug: Web/API/Document/getElementById +tags: + - API + - DOM + - Document + - Elements + - Method + - Reference + - Web + - getElementById + - id +translation_of: Web/API/Document/getElementById +--- +
{{ ApiRef("DOM") }}
+ +

Sumário

+ +

Retorna a referência do elemento através do seu ID.

+ +

Sintaxe

+ +
var elemento = document.getElementById(id);
+
+ +

onde

+ + + +

Exemplo

+ +
<!DOCTYPE html>
+<html>
+<head>
+  <title>Exemplo getElementById</title>
+  <script>
+  function mudarCor(novaCor) {
+    var elemento = document.getElementById("para1");
+    elemento.style.color = novaCor;
+  }
+  </script>
+</head>
+<body>
+  <p id="para1">Algum texto de exemplo</p>
+  <button onclick="mudarCor('blue');">Azul</button>
+  <button onclick="mudarCor('red');">Vermelho</button>
+</body>
+</html>
+
+ +

Notas

+ +

Os novatos devem notar que a caixa de 'Id' no nome deste método deve estar correta para o código da função - 'getElementByID não funciona, por mais natural que possa parecer.

+ +

Se não existe um elemento com o id fornecido, esta função retorna null. Note que o parâmetro ID diferência maiúsculas e minúsculas. Assim document.getElementById("Main") retornará null ao invés do elemento <div id="main">, devido a "M" e "m" serem diferentes para o objetivo deste método.

+ +

Elementos que não estão no documento não são procurados por getElementById. Quando criar um elemento e atribuir um ID ao mesmo, você deve inserir o elemento na árvore do documento com insertBefore ou método similar antes que você possa acessá-lo com getElementById:

+ +
var elemento = document.createElement("div");
+elemento.id = 'testqq';
+var el = document.getElementById('testqq'); // el será null!
+
+ +

Documentos não-HTML. A implementação do DOM deve ter informações que diz quais atributos são do tipo ID.  Atributos com o nome "id" não são do tipo ID a menos que assim sejam definidos nos documentos DTD. O atributo id é definido para ser um tipo ID em casos comuns de  XHTML, XUL, e outros. Implementações que não reconhecem se os atributos são do tipo ID, ou não são esperados retornam null.

+ +

Compatibilidade do Navegador

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
RecursoChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico1.0{{ CompatGeckoDesktop(1.0) }}5.57.01.0
+
+ +
+ + + + + + + + + + + + + + + + + + + +
RecursoAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Suporte básico1.0{{ CompatGeckoMobile(1.0) }}6.06.01.0
+
+ +

Especificações

+ +

getElementById foi introduzido no DOM Level 1 para documentos HTML e movidos para todos documentos no DOM Level 2

+ + + +

Veja também

+ + diff --git a/files/pt-br/web/api/document/getelementsbyclassname/index.html b/files/pt-br/web/api/document/getelementsbyclassname/index.html new file mode 100644 index 0000000000..44fa28f840 --- /dev/null +++ b/files/pt-br/web/api/document/getelementsbyclassname/index.html @@ -0,0 +1,104 @@ +--- +title: Document.getElementsByClassName() +slug: Web/API/Document/getElementsByClassName +tags: + - API + - DOM + - Gecko + - HTML5 + - Métodos de Elementos DOM + - Referencia + - metodo +translation_of: Web/API/Document/getElementsByClassName +--- +

{{APIRef("DOM")}}

+ +

Retorna um vetor de objetos com todos os elementos filhos que possuem o nome da classe dada.  Quando invocado no objeto document, o documento é examinado por completo, incluindo o nó raiz. Você também pode invocar {{domxref("Element.getElementsByClassName", "getElementsByClassName()")}} em qualquer elemento; isso retornaria somente elementos que são descendentes do nó raiz especificado com o nome da classe.

+ +

Sintaxe

+ +
var elementos = document.getElementsByClassName(nomes); // ou:
+var elementos = rootElement.getElementsByClassName(nomes);
+ + + +

Exemplos

+ +

Retorna todos os elementos que possuem a classe 'teste'

+ +
document.getElementsByClassName('teste');
+ +

Retorna todos os elementos que possuem as classes 'vermelho' e 'teste'

+ +
document.getElementsByClassName('vermelho teste');
+ +

Retorna todos os elementos que possuem a classe 'teste' dentro do elemento que possui o ID 'principal'

+ +
document.getElementById('principal').getElementsByClassName('teste');
+ +

Nós podemos também usar os métodos do Array.prototype em qualquer dos elementos {{ domxref("HTMLCollection") }} passando o HTMLCollection como valor deste método. Aqui podemos encontrar todos os elementos do tipo div que possuem a classe 'teste':

+ +
var elementosTeste = document.getElementsByClassName('teste');
+var divsTeste = Array.prototype.filter.call(elementosTeste, function(elementoTeste) {
+    return elementoTeste.nodeName === 'DIV';
+});
+ +

Compatibilidade com navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticasChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{ CompatVersionUnknown() }}3.09.0{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticasAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

Especificação

+ + diff --git a/files/pt-br/web/api/document/getelementsbyname/index.html b/files/pt-br/web/api/document/getelementsbyname/index.html new file mode 100644 index 0000000000..8793259751 --- /dev/null +++ b/files/pt-br/web/api/document/getelementsbyname/index.html @@ -0,0 +1,90 @@ +--- +title: Document.getElementsByName() +slug: Web/API/Document/getElementsByName +translation_of: Web/API/Document/getElementsByName +--- +
{{APIRef("DOM")}}
+ +

O métodogetElementsByName() do objeto {{domxref("Document")}} retorna uma coleção de elementos {{domxref("NodeList")}} com um dado {{domxref("element.name","name")}} no documento.

+ +

Sintaxe

+ +
var elementos = document.getElementsByName(nome);
+
+ + + +

Exemplo

+ +
<!DOCTYPE html>
+<html lang="en">
+<title>Exemplo: usando document.getElementsByName</title>
+
+<input type="hidden" name="up">
+<input type="hidden" name="down">
+
+<script>
+  var up_nomes = document.getElementsByName("up");
+  console.log(up_nomes[0].tagName); // exibindo o campo "INPUT"
+</script>
+</html>
+
+ +

Notas

+ +

O atributo {{domxref("element.name","name")}} pode somente ser aplicado nos documentos (X)HTML.

+ +

A coleção retornada {{domxref("NodeList")}} contém todos os elementos com o respectivo nome, tal como {{htmlelement("meta")}}, {{htmlelement("object")}}, e até os elementos o qual não suporta o atributo nome para todos.

+ +
+

O método getElementsByName trabalha diferentemente em IE10 e anteriores. Além de que, getElementsByName() também retorna elementos que tem um atributo id com o valor especificado. Seja cuidadoso para não usar a mesma string como ambos nome e id.

+
+ +
+

O método getElementsByName trabalha diferentemente no IE. Portanto, getElementsByName() não retorna todos os elementos no qual não pode ter um atributo nome (tal como <span>).

+
+ +
+

Ambos IE e Edge retorna um {{domxref("HTMLCollection")}}, e não um {{domxref("NodeList")}}

+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + +
EpecificaçãoStatusComentário
{{SpecName('HTML WHATWG', '#dom-document-getelementsbyname', "Document.getElementsByName()")}}{{ Spec2('HTML WHATWG') }}
{{SpecName("DOM2 HTML", "html.html#ID-71555259", "Document.getElementsByName()")}}{{Spec2("DOM2 HTML")}}Definição Inicial
+ +

Compatibilidade com Nagevagores

+ + + +

{{Compat("api.Document.getElementsByName")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/document/getelementsbytagname/index.html b/files/pt-br/web/api/document/getelementsbytagname/index.html new file mode 100644 index 0000000000..3e786ed2f6 --- /dev/null +++ b/files/pt-br/web/api/document/getelementsbytagname/index.html @@ -0,0 +1,113 @@ +--- +title: Document.getElementsByTagName() +slug: Web/API/Document/getElementsByTagName +translation_of: Web/API/Document/getElementsByTagName +--- +
{{APIRef("DOM")}}
+ +

O método getElementsByTagName da interface Document retorna um HTMLCollection de elementos com o nome da tag fornecido. O documento completo é pesquisado, incluindo o nó raiz. A HTMLCollection retornada é ao vivo, o que significa que ela se atualiza automaticamente para permanecer em sincronia com a árvore DOM sem ter que chamar document.getElementsByTagName () novamente.

+ +

O método getElementsByTagName da {{domxref("Document")}} interface returns an {{domxref("HTMLCollection")}} of elements with the given tag name. The complete document is searched, including the root node. The returned HTMLCollection is live, meaning that it updates itself automatically to stay in sync with the DOM tree without having to call document.getElementsByTagName() again.

+ +

Syntax

+ +
var elements = document.getElementsByTagName(name);
+ + + +
The latest W3C specification says elements is an HTMLCollection; however, this method returns a {{domxref("NodeList")}} in WebKit browsers. See {{bug(14869)}} for details.
+ +

Example

+ +

In the following example, getElementsByTagName() starts from a particular parent element and searches top-down recursively through the DOM from that parent element, building a collection of all descendant elements which match the tag name parameter. This demonstrates both document.getElementsByTagName() and the functionally identical {{domxref("Element.getElementsByTagName()")}}, which starts the search at a specific element within the DOM tree.

+ +

Clicking the buttons uses getElementsByTagName() to count the descendant paragraph elements of a particular parent (either the document itself or one of two nested {{HTMLElement("div")}} elements).

+ +
<!DOCTYPE html>
+<html lang="en">
+<head>
+  <meta charset="UTF-8" />
+  <title>getElementsByTagName example</title>
+  <script>
+    function getAllParaElems() {
+      var allParas = document.getElementsByTagName('p');
+      var num = allParas.length;
+      alert('There are ' + num + ' paragraph in this document');
+    }
+
+    function div1ParaElems() {
+      var div1 = document.getElementById('div1');
+      var div1Paras = div1.getElementsByTagName('p');
+      var num = div1Paras.length;
+      alert('There are ' + num + ' paragraph in #div1');
+    }
+
+    function div2ParaElems() {
+      var div2 = document.getElementById('div2');
+      var div2Paras = div2.getElementsByTagName('p');
+      var num = div2Paras.length;
+      alert('There are ' + num + ' paragraph in #div2');
+    }
+  </script>
+</head>
+<body style="border: solid green 3px">
+  <p>Some outer text</p>
+  <p>Some outer text</p>
+
+  <div id="div1" style="border: solid blue 3px">
+    <p>Some div1 text</p>
+    <p>Some div1 text</p>
+    <p>Some div1 text</p>
+
+    <div id="div2" style="border: solid red 3px">
+      <p>Some div2 text</p>
+      <p>Some div2 text</p>
+    </div>
+  </div>
+
+  <p>Some outer text</p>
+  <p>Some outer text</p>
+
+  <button onclick="getAllParaElems();">
+    show all p elements in document</button><br />
+
+  <button onclick="div1ParaElems();">
+    show all p elements in div1 element</button><br />
+
+  <button onclick="div2ParaElems();">
+    show all p elements in div2 element</button>
+
+</body>
+</html>
+
+ +

Notes

+ +

When called on an HTML document, getElementsByTagName() lower-cases its argument before proceeding. This is undesirable when trying to match camelCase SVG elements in a subtree in an HTML document. {{Domxref("document.getElementsByTagNameNS()")}} is useful in that case. See also {{Bug(499656)}}.

+ +

document.getElementsByTagName() is similar to {{domxref("Element.getElementsByTagName()")}}, except that its search encompasses the whole document.

+ +

Specifications

+ + + +

Browser compatibility

+ + + +

{{Compat("api.Document.getElementsByTagName")}}

+ +

See also

+ + diff --git a/files/pt-br/web/api/document/getselection/index.html b/files/pt-br/web/api/document/getselection/index.html new file mode 100644 index 0000000000..9a2aab76d5 --- /dev/null +++ b/files/pt-br/web/api/document/getselection/index.html @@ -0,0 +1,8 @@ +--- +title: Document.getSelection() +slug: Web/API/Document/getSelection +translation_of: Web/API/DocumentOrShadowRoot/getSelection +--- +

{{APIRef("DOM")}}

+ +

Esse método funciona de forma idêntica ao método {{domxref("Window.getSelection()")}};  Ele retorna um objeto {{domxref("Selection")}} representando o texto atualmente selecionado no documento.

diff --git a/files/pt-br/web/api/document/hasfocus/index.html b/files/pt-br/web/api/document/hasfocus/index.html new file mode 100644 index 0000000000..0d238ec062 --- /dev/null +++ b/files/pt-br/web/api/document/hasfocus/index.html @@ -0,0 +1,146 @@ +--- +title: Document.hasFocus() +slug: Web/API/Document/hasFocus +tags: + - API + - Compatibilidade + - DOM + - Focus + - Referencia + - metodo +translation_of: Web/API/Document/hasFocus +--- +
{{APIRef}}
+ +
O método Document.hasFocus() retorna um valor {{jsxref("Boolean")}} que indica se o documento ou qualquer elemento dentro do documento está com o foco ativo. Este método pode ser usado para determinar se o elemento ativo em um documento tem foco.
+ +
+

Quando se está visualizando um documento, um elemento com focus é sempre o ativo no mesmo, mas um elemento ativo não necessariamente tem o foco. Por exemplo, um elemento ativo com uma janela (popup) que não é a principal não tem foco.

+
+ +

Sintaxe

+ +
focused = document.hasFocus();
+ +

Valor retornado

+ +

false se o elemento ativo no documento não tem foco; true se o elemento ativo no documento tem foco.

+ +

Exemplo

+ +
<!DOCTYPE html>
+<html lang="en">
+<head>
+<meta charset="UTF-8" />
+<title>TEST</title>
+<style>
+#message { font-weight: bold; }
+</style>
+<script>
+setInterval( checkPageFocus, 200 );
+
+function checkPageFocus() {
+  var info = document.getElementById("message");
+
+  if ( document.hasFocus() ) {
+    info.innerHTML = "O documento tem o foco.";
+  } else {
+    info.innerHTML = "O documento não tem o foco.";
+  }
+}
+
+function openWindow() {
+  window.open (
+    "http://developer.mozilla.org/",
+    "mozdev",
+    "width=640,
+    height=300,
+    left=150,
+    top=260"
+  );
+}
+</script>
+</head>
+<body>
+  <h1>Exemplo do JavaScript hasFocus</h1>
+  <div id="message">Esperando por ação do usuário</div>
+  <div><button onclick="openWindow()">Abre uma nova janela</button></div>
+</body>
+</html>
+ +

Especificação

+ + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('HTML WHATWG', 'interaction.html#dom-document-hasfocus', 'Document.hasFocus()')}}{{Spec2('HTML WHATWG')}}Definição inicial
+ +

Compatibilidade de navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico30{{ CompatGeckoDesktop("1.9") }}6.0{{ CompatNo() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FuncionalidadeAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{ CompatUnknown() }}{{ CompatGeckoMobile("1.9") }}{{ CompatUnknown() }}{{ CompatNo() }}{{ CompatUnknown() }}
+
+ +

 

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/document/head/index.html b/files/pt-br/web/api/document/head/index.html new file mode 100644 index 0000000000..af0331459f --- /dev/null +++ b/files/pt-br/web/api/document/head/index.html @@ -0,0 +1,102 @@ +--- +title: Document.head +slug: Web/API/Document/head +translation_of: Web/API/Document/head +--- +

{{APIRef("DOM")}}

+ +

Retorna o elemento {{HTMLElement("head")}} do documento atual. Se existir mais de um elemento <head>, apenas o primeiro será devolvido.

+ +

Sintaxe

+ +
var objRef = document.head;
+
+ +

Exemplo

+ +
// No HTML: <head id="my-document-head">
+var aHead = document.head;
+
+alert(aHead.id); // "my-document-head";
+
+alert( document.head === document.querySelector("head") ); // true
+
+ +

Notas

+ +

document.head suporta apenas leitura. Qualquer tentativa de atribuir um valor a essa propriedade irá falhar silenciosamente ou irá, usando o modo ECMAScript Strict de um browser Gecko, disparar um TypeError.

+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName("HTML5 W3C", "dom.html#dom-tree-accessors", "document.head")}}{{Spec2("HTML5 W3C")}}Definição inicial
+ +

Compatibilidade entre Browsers

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
RecursoChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico4.0{{CompatGeckoDesktop("2")}}9.011.05.0
+
+ +
+ + + + + + + + + + + + + + + + + + + +
RecursoAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatGeckoMobile("2")}}9.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

 

+ +

Veja Também

+ + diff --git a/files/pt-br/web/api/document/height/index.html b/files/pt-br/web/api/document/height/index.html new file mode 100644 index 0000000000..5dedba8f99 --- /dev/null +++ b/files/pt-br/web/api/document/height/index.html @@ -0,0 +1,44 @@ +--- +title: Document.height +slug: Web/API/Document/height +translation_of: Web/API/Document/height +--- +
{{APIRef("DOM")}} {{Obsolete_header}}
+ +
+

Nota: A partir do {{Gecko("6.0")}}, document.height  não é mais suportado. Em seu lugar use document.body.clientHeight. Veja {{domxref("element.clientHeight")}}.

+
+ +

Sumário

+ +

Retorna a altura do objeto {{domxref("document")}}. Em muitos casos, isto é igual à do elemento {{HTMLElement("body")}} do documento atual.

+ +

Sintaxe

+ +
height_value = document.height
+
+ +

Exemplo

+ +
// alert document height
+alert(document.height);
+
+ +

Alternativas

+ +
document.body.clientHeight
+document.documentElement.clientHeight
+document.documentElement.scrollHeight
+
+ +

Especificação

+ +

HTML5

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/document/images/index.html b/files/pt-br/web/api/document/images/index.html new file mode 100644 index 0000000000..f5021122a9 --- /dev/null +++ b/files/pt-br/web/api/document/images/index.html @@ -0,0 +1,38 @@ +--- +title: Document.images +slug: Web/API/Document/images +translation_of: Web/API/Document/images +--- +
+
{{ ApiRef("DOM") }}
+
+ +

Summary

+ +

document.images retorna uma coleção de imagens do documento HTML.

+ +

Sintaxe

+ +
var htmlCollection = document.images;
+ +

Exemplo

+ +
var ilist = document.images;
+
+for(var i = 0; i < ilist.length; i++) {
+    if(ilist[i].src == "banner.gif") {
+        // found the banner
+    }
+}
+ +

Notas

+ +

document.images.length – propriedade, retorna o número de imagens na página.

+ +

document.images é parte do DOM HTML, e só trabalho com documentos HTML.

+ +

Especificação

+ + diff --git a/files/pt-br/web/api/document/implementation/index.html b/files/pt-br/web/api/document/implementation/index.html new file mode 100644 index 0000000000..2f7b5ca992 --- /dev/null +++ b/files/pt-br/web/api/document/implementation/index.html @@ -0,0 +1,52 @@ +--- +title: Document.implementation +slug: Web/API/Document/implementation +tags: + - API + - DOM + - Propriedade + - Referencia +translation_of: Web/API/Document/implementation +--- +
{{ ApiRef("DOM") }}
+ +
 
+ +

Sumário

+ +

Retorna um objeto {{domxref("DOMImplementation")}} associado ao documento atual.

+ +

Sintaxe

+ +
DOMImpObj = document.implementation;
+
+ +

Exemplo

+ +
var modName = "HTML";
+var modVer = "2.0";
+var conformTest = document.implementation.hasFeature( modName, modVer );
+
+alert( "DOM " + modName + " " + modVer + " supported?: " + conformTest );
+
+// alerts with: "DOM HTML 2.0 supported?: true" if DOM Level 2 HTML module is supported.
+
+ +

Uma lista dos nomes de módulos (ex., Core, HTML, XML, etc) está disponível na DOM Level 2 Conformance Section

+ +

Notas

+ +

A Recomendação do W3C DOM Level 1 apenas especifica o método hasFeature, que é o único meio de verificar se o módulo DOM é suportado pelo navegador (veja exemplo acima e What does your user agent claim to support?). Quando disponível, outros métodos DOMImplementation proverão serviços para controlar coisas fora deste único documento. Por exemplo, a interface DOMImplementation inclui um método createDocumentType com o qual DTD's podem ser criados para um ou mais documentos gerenciados pela implementação.

+ +

Especificação

+ + + +

Notas específicas para o Gecko

+ + diff --git a/files/pt-br/web/api/document/importnode/index.html b/files/pt-br/web/api/document/importnode/index.html new file mode 100644 index 0000000000..831879f58f --- /dev/null +++ b/files/pt-br/web/api/document/importnode/index.html @@ -0,0 +1,84 @@ +--- +title: Document.importNode() +slug: Web/API/Document/importNode +translation_of: Web/API/Document/importNode +--- +

{{APIRef("DOM")}}

+ +

Cria uma cópia de um nó a partir de um documento externo para ser inserido no document atual.

+ +

Sintaxe

+ +
var node = document.importNode(externalNode, deep);
+
+ +
+
node
+
O novo nó que será importado no documento. A propriedade parentNode do novo nó é null, desde que ele não foi inserido na árvores do documento.
+
externalNode
+
O nó de outro documento para ser importado.
+
deep
+
Um boolean, indicando se os nós filhos, do nó a ser importado, devem ser importados também.
+
+ +
+

Note: In the DOM4 specification (as implemented in Gecko 13.0 {{geckoRelease(13)}}), deep is an optional argument. If omitted, the method acts as if the value of deep was true, defaulting to using deep cloning as the default behavior. To create a shallow clone, deep must be set to false.

+ +

This behavior has been changed in the latest spec, and if omitted, the method will act as if the value of deep was false. Though It's still optional, you should always provide the deep argument both for backward and forward compatibility. With Gecko 28.0 {{geckoRelease(28)}}, the console warned developers not to omit the argument. Starting with Gecko 29.0 {{geckoRelease(29)}}), a shallow clone is defaulted instead of a deep clone.

+
+ +

Exemplo

+ +
var iframe = document.getElementsByTagName("iframe")[0];
+var oldNode = iframe.contentWindow.document.getElementById("myNode");
+var newNode = document.importNode(oldNode, true);
+document.getElementById("container").appendChild(newNode);
+
+ +

Notas

+ +

O nó original não é removido do documento de origem. O nó importado é um clone do original.

+ +

 

+ +

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

+ +

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

+ +

 

+ +

Especificação

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("DOM WHATWG", "#dom-document-importnode", "document.importNode()")}}{{Spec2("DOM WHATWG")}} 
{{SpecName("DOM2 Core", "core.html#Core-Document-importNode", "document.importNode()")}}{{Spec2("DOM2 Core")}}Initial definition
+ +

Compatibilidade nos Browsers

+ +
+ + +

{{Compat("api.Document.importNode")}}

+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/document/index.html b/files/pt-br/web/api/document/index.html new file mode 100644 index 0000000000..1fc11a79ba --- /dev/null +++ b/files/pt-br/web/api/document/index.html @@ -0,0 +1,402 @@ +--- +title: Document +slug: Web/API/Document +translation_of: Web/API/Document +--- +
{{ ApiRef("DOM") }}
+ +
+ +

Para cada página carregada no browser, existe um objeto Document. A interface Document serve como um ponto de entrada para o conteúdo da Página ( a árvore DOM, incluindo elementos como {{HTMLElement("body")}} e {{HTMLElement("table")}}) e provê funcionalidades globais ao documento (como obter a URL da página e criar novos elementos no documento).

+ +

{{inheritanceDiagram}}

+ +

Um objeto document pode ser obtido por meio de várias APIs:

+ + + +

Dependendo do tipo do documento (e.g. HTML ou XML), diferentes APIs estarão disponívels no objeto Document.

+ +

Todo objeto Document implementa a interface Document (e consequentemente as interfaces {{domxref("Node")}} e {{domxref("EventTarget")}}). Portanto, as principais propriedades e métodos documentados nesta página estarão disponíveis para todos os tipos de documents.

+ + + +

No futuro, todas essas interfaces irão ser divididas na interface Document.

+ +

Propriedades

+ +
+

Nota: A interface Document também herda das interfaces {{domxref("Node")}} e {{domxref("EventTarget")}}.

+
+ +
+
{{domxref("Document.all")}} {{Deprecated_inline}} {{non-standard_inline}}
+
Da acesso a todos os elementos do documento.È uma interface legada não padrão, voce deve usar o método {{domxref("Document.getElementById()")}} como alternativa.
+
{{domxref("Document.async")}} {{Deprecated_inline}}
+
Usado como {{domxref("document.load")}} que indica uma requisição asyncroma.
+
{{domxref("Document.characterSet")}} {{experimental_inline}}
+
Retorna a codificação de caracteres que está sendo usado pelo documento.
+
{{domxref("Document.compatMode")}} {{experimental_inline}}
+
indica se o documento é renderizado no modo Quirks ou Strict.
+
{{domxref("Document.contentType")}} {{experimental_inline}}
+
Retorna o tipo de conteúdo do cabeçalho MIME do documento atual.
+
{{domxref("Document.doctype")}}
+
Retorna o nome do tipo de conteudo do documento HTML.
+
{{domxref("Document.documentElement")}}
+
Returns the Element that is a direct child of the document. For HTML documents, this is normally the HTML element.
+
{{domxref("Document.documentURI")}}
+
Returns the document URL.
+
{{domxref("Document.domConfig")}} {{Deprecated_inline}}
+
Should return a {{domxref("DOMConfiguration")}} object.
+
{{domxref("Document.implementation")}}
+
Returns the DOM implementation associated with the current document.
+
{{domxref("Document.inputEncoding")}} {{Deprecated_inline}}
+
Returns the encoding used when the document was parsed.
+
{{domxref("Document.lastStyleSheetSet")}}
+
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")}}
+
true if this document is synthetic, such as a standalone image, video, audio file, or the like.
+
{{domxref("Document.mozFullScreen")}} {{non-standard_inline}} {{gecko_minversion_inline("9.0")}}
+
true when the document is in {{domxref("Using_full-screen_mode","full-screen mode")}}.
+
{{domxref("Document.mozFullScreenElement")}} {{non-standard_inline}} {{gecko_minversion_inline("9.0")}}
+
The element that's currently in full screen mode for this document.
+
{{domxref("Document.mozFullScreenEnabled")}} {{non-standard_inline}} {{gecko_minversion_inline("9.0")}}
+
true if calling {{domxref("element.mozRequestFullscreen()")}} would succeed in the curent document.
+
{{domxref("Document.pointerLockElement")}} {{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")}}
+
Returns the preferred style sheet set as specified by the page author.
+
{{domxref("Document.selectedStyleSheetSet")}}
+
Returns which style sheet set is currently in use.
+
{{domxref("Document.styleSheets")}}
+
Returns a list of the style sheet objects on the current document.
+
{{domxref("Document.styleSheetSets")}}
+
Returns a list of the style sheet sets available on the document.
+
{{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")}}

+ +

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.activeElement")}}
+
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")}}
+
Returns a reference to the window object.
+
{{domxref("Document.designMode")}}
+
Gets/sets the ability to edit the whole document.
+
{{domxref("Document.dir")}}
+
Gets/sets directionality (rtl/ltr) of the document.
+
{{domxref("Document.domain")}}
+
Returns the domain of the current document.
+
{{domxref("Document.embeds")}}
+
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")}}
+
Returns a list of the {{HTMLElement("form")}} elements within the current document.
+
{{domxref("Document.head")}}
+
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")}}
+
Returns a list of the images in the current document.
+
{{domxref("Document.lastModified")}}
+
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")}}
+
Returns a list of all the hyperlinks in the document.
+
{{domxref("Document.location")}}
+
Returns the URI of the current document.
+
{{domxref("Document.plugins")}}
+
Returns a list of the available plugins.
+
{{domxref("Document.readyState")}} {{gecko_minversion_inline("1.9.2")}}
+
Returns loading status of the document.
+
{{domxref("Document.referrer")}}
+
Returns the URI of the page that linked to this page.
+
{{domxref("Document.scripts")}}
+
Returns all the {{HTMLElement("script")}} elements on the document.
+
{{domxref("Document.title")}}
+
Returns the title of the current document.
+
{{domxref("Document.URL")}}
+
Returns a string containing the URL of the current document.
+
{{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.onpointerlockchange")}} {{experimental_inline}}
+
Returns the event handling code for the {{event("pointerlockchange")}} event.
+
{{domxref("Document.onpointerlockerror")}} {{experimental_inline}}
+
Returns the event handling code for the {{event("pointerlockerror")}} event.
+
{{domxref("Document.onreadystatechange")}} {{gecko_minversion_inline("1.9.2")}}
+
Returns the event handling code for the readystatechange event.
+
+ +

Methods

+ +
+

Note: The Document interface also inherits from the {{domxref("Node")}} and {{domxref("EventTarget")}} interfaces.

+
+ +
+
{{domxref("Document.adoptNode","Document.adoptNode(Node node)")}}
+
Adopt node from an external document.
+
{{domxref("Document.captureEvents","Document.captureEvents(String eventName)")}} {{Deprecated_inline}}
+
See {{domxref("window.captureEvents")}}.
+
{{domxref("Document.caretPositionFromPoint","Document.caretPositionFromPoint(Number x, Number y)")}}
+
Gets a {{domxref("CaretPosition")}} based on two coordinates.
+
{{domxref("Document.createAttribute","Document.createAttribute(String name)")}}
+
Creates a new {{domxref("Attr")}} object and returns it.
+
{{domxref("Document.createAttributeNS","Document.createAttributeNS(String namespace, String name)")}}
+
Creates a new attribute node in a given namespace and returns it.
+
{{domxref("Document.createCDATASection","Document.createCDATASection(String data)")}}
+
Creates a new CDATA node and returns it.
+
{{domxref("Document.createComment","Document.createComment(String comment)")}}
+
Creates a new comment node and returns it.
+
{{domxref("Document.createDocumentFragment()")}}
+
Creates a new document fragment.
+
{{domxref("Document.createElement","Document.createElement(String name)")}}
+
Creates a new element with the given tag name.
+
{{domxref("Document.createElementNS","Document.createElementNS(String namespace, String name)")}}
+
Creates a new element with the given tag name and namespace URI.
+
{{domxref("Document.createEntityReference","Document.createEntityReference(String name)")}} {{obsolete_inline}}
+
Creates a new entity reference object and returns it.
+
{{domxref("Document.createEvent","Document.createEvent(String interface)")}}
+
Creates an event object.
+
{{domxref("Document.createNodeIterator","Document.createNodeIterator(Node root[, Number whatToShow[, NodeFilter filter]])")}}
+
Creates a {{domxref("NodeIterator")}} object.
+
{{domxref("Document.createProcessingInstruction","Document.createProcessingInstruction(String target, String data)")}}
+
Creates a new {{domxref("ProcessingInstruction")}} object.
+
{{domxref("Document.createRange()")}}
+
Creates a {{domxref("Range")}} object.
+
{{domxref("Document.createTextNode","Document.createTextNode(String text)")}}
+
Creates a text node.
+
{{domxref("Document.createTreeWalker","Document.createTreeWalker(Node root[, Number whatToShow[, NodeFilter filter]])")}}
+
Creates a {{domxref("TreeWalker")}} object.
+
{{domxref("Document.elementFromPoint","Document.elementFromPoint(Number x, Number y)")}}
+
Returns the element visible at the specified coordinates.
+
{{domxref("Document.enableStyleSheetsForSet","Document.enableStyleSheetsForSet(String name)")}}
+
Enables the style sheets for the specified style sheet set.
+
{{domxref("Document.exitPointerLock()")}} {{experimental_inline}}
+
Release the pointer lock.
+
{{domxref("Document.getElementsByClassName","Document.getElementsByClassName(String className)")}}
+
Returns a list of elements with the given class name.
+
{{domxref("Document.getElementsByTagName","Document.getElementsByTagName(String tagName)")}}
+
Returns a list of elements with the given tag name.
+
{{domxref("Document.getElementsByTagNameNS","Document.getElementsByTagNameNS(String namespace, String tagName)")}}
+
Returns a list of elements with the given tag name and namespace.
+
{{domxref("Document.importNode","Document.importNode(Node node, Boolean deep)")}}
+
Returns a clone of a node from an external document.
+
{{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.
+
{{domxref("Document.normalizeDocument()")}} {{obsolete_inline}}
+
Replaces entities, normalizes text nodes, etc.
+
{{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")}}.
+
+ +

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 formatting command.
+
{{domxref("Document.registerElement","Document.registerElement(String tagname[, Object options])")}}
+
Registers a new custom element in the browser and returns a constructor for the new element.
+
{{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.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{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('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
+ +

Browser compatibility

+ +

Firefox notes

+ +

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

+ +
+
{{domxref("document.currentScript")}} {{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")}}.
+
+ +

Internet Explorer notes

+ +

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-br/web/api/document/keydown_event/index.html b/files/pt-br/web/api/document/keydown_event/index.html new file mode 100644 index 0000000000..4abd69eab7 --- /dev/null +++ b/files/pt-br/web/api/document/keydown_event/index.html @@ -0,0 +1,178 @@ +--- +title: keydown +slug: Web/API/Document/keydown_event +translation_of: Web/API/Document/keydown_event +--- +

O evento keydown é disparado quando uma tecla é pressionada. Diferente do evento keypress, o keydown é disparado para teclas que produzem e que não produzem um caractere.

+ +

Informações gerais

+ +
+
Especificação
+
DOM L3
+
Interface
+
KeyboardEvent
+
Burbulha
+
Sim
+
Cancelável
+
Sim
+
Alvo
+
Document, Element
+
Ação Padrão
+
Variações: evento keypress; carrega sistema de composição de texto; eventos blur e focus; evento DOMActivate; outro evento
+
+ +

Propriedades

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropriedadeTipoDescrição
target {{readonlyInline}}EventTargetO alvo do evento (o alvo de nível mais alto na árvore DOM).
type {{readonlyInline}}DOMStringO tipo do evento.
bubbles {{readonlyInline}}BooleanSe o evento normalmente burbulha ou não
cancelable {{readonlyInline}}BooleanSe o evento é cancelável ou não
view {{readonlyInline}}WindowProxydocument.defaultView (window do documento)
detail {{readonlyInline}}long (float)0.
target {{readonlyInline}}EventTarget (elemento DOM)Elemento focado processando o evento, elemento raiz se nenhum elemento input adequado está focado.
char {{readonlyInline}}DOMString (string)O caractere correspondente à tecla. Se a tecla corresponde a um caractere imprimível, este valor é uma string Unicode não vazia, contendo o caractere. Se a tecla não tem uma representação imprimível, o valor é uma string vazia. Veja key names and char values para detalhes. +
Nota: Se a tecla for usada como uma macro que insere múltiplos caracteres, o valor deste atributo é toda a string, não apenas o primeiro caractere.
+
key {{readonlyInline}}DOMString (string)O valor da tecla pressionada. Se a tecla tem uma representação imprimível, o valor deste atributo é o mesmo do atributo char. Caso contrário, é uma das strings key especificadas em Key Values. Se a tecla não pode ser identificada, o valor do atributo é a string "Unidentified". Veja key names and char values para detalhes. Somente Leitura.
code {{readonlyInline}}DOMString (string)Mantém uma string que identifica a tecla física sendo pressionada. O valor não é afetado pelo layout atual do teclado ou estado de modificador, portando uma tecla particular sempre retornará o mesmo valor. 
charCode {{readonlyInline}}Unsigned long (int)O número de referência Unicode da tecla; este atributo é usado somente pelo evento keypress. Para teclas cujo atributo char contém múltiplos caracteres, este é o valor Unicode do primeiro caractere daquele atributo. +
Aviso: Este atributo está obsoleto; você deve usar char no lugar, se disponível.
+
keyCode {{readonlyInline}}Unsigned long (int)Um código numérico, dependente do sistema e da implementação, identificando o valor não modificado da tecla pressionada. Este é usualmente o código decimal ASCII ({{ RFC(20) }}) ou código Windows 1252 correspondente à tecla; veja {{ anch("Virtual key codes") }} para uma lista de valores comuns. Se a tecla não pode ser identificada, este valor é 0. +
Aviso: Este atributo está obsoleto; você deve usar key no lugar, se disponível.
+
which {{readonlyInline}}Unsigned long (int)Um código numérico, dependente do sistema e da implementação, identificando o valor não modificado da tecla pressionada; este é usualmente o mesmo que keyCode. +
Aviso: Este atributo está obsoleto; você deve usar key no lugar, se disponível.
+
location {{readonlyInline}}long (float)A localização da tecla no dispositivo.
repeat {{readonlyInline}}booleantrue se a tecla foi pressionada tempo suficiente para disparar repetição de tecla, false caso contrário.
locale {{readonlyInline}}stringO código do idioma para o evento, se disponível; uma string vazia caso contrário.
ctrlKey {{readonlyInline}}booleantrue se a tecla control estava pressionada quando o evento foi disparado. false caso contrário.
shiftKey {{readonlyInline}}booleantrue se a tecla shift estava pressionada quando o evento foi disparado. false caso contrário.
altKey {{readonlyInline}}booleantrue se a tecla alt estava pressionada quando o evento foi disparado. false caso contrário.
metaKey {{readonlyInline}}booleantrue se a tecla meta estava pressionada quando o evento foi disparado. false caso contrário.
+ +

preventDefault() do evento keydown

+ +

Iniciando com o Gecko 25, uma chamada para o método preventDefault() do evento keydown evita dispachar o evento keypress seguinte. Este é um comportamento válido para a especificação D3E e os principais navegadores web se comportam desta forma. Por outro lado, o Gecko 24 e anteriores dispachavam o evento keypress mesmo que o método preventDefault() do evento keydown anterior fosse chamado, embora o atributo  defaultPrevented do evento keypress fosse true neste caso.

+ +

Eventos Relacionados

+ + + +

Exemplo

+ +
<!DOCTYPE html>
+<html>
+<head>
+<script>
+
+'use strict';
+
+document.addEventListener('keydown', (event) => {
+  const keyName = event.key;
+  alert('keydown event\n\n' + 'key: ' + keyName);
+});
+
+</script>
+</head>
+<body>
+</body>
+</html>
diff --git a/files/pt-br/web/api/document/keypress_event/index.html b/files/pt-br/web/api/document/keypress_event/index.html new file mode 100644 index 0000000000..e22242028b --- /dev/null +++ b/files/pt-br/web/api/document/keypress_event/index.html @@ -0,0 +1,170 @@ +--- +title: keypress +slug: Web/API/Document/keypress_event +translation_of: Web/API/Document/keypress_event +--- +
{{APIRef}}
+ +

O evento keypress é disparado quando uma tecla que produz um valor do tipo caractere é pressionada. Exemplos de chaves que produzem um valor de caractere são chaves alfabéticas, numéricas e de pontuação. Exemplos de chaves que não produzem um valor de caractere são as teclas modificadoras, como Alt, Shift, Ctrl, ou Meta.

+ +

Informações gerais

+ +
+
Especificação
+
DOM L3 {{deprecated_inline ()}}
+
Interface
+
KeyboardEvent
+
Bolhas
+
sim
+
Cancelável
+
sim
+
Alvo
+
Documento, Elemento
+
Ação padrão
+
Varia: keypressevento; lançar sistema de composição de texto; blure focuseventos; DOMActivateevento; outro evento
+
+ +

Propriedades

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropriedadeTipoDescrição
target {{readonlyInline}}EventTargetO destino do evento (o destino mais alto na árvore do DOM).
type {{readonlyInline}}DOMStringO tipo de evento.
bubbles {{readonlyInline}}boleanoSe o evento normalmente borbulha ou não
cancelable {{readonlyInline}}boleanoSe o evento é cancelável ou não
view {{readonlyInline}}WindowProxydocument.defaultView( windowdo documento)
detail {{readonlyInline}}long( float)0
target {{readonlyInline}}EventTarget (elemento DOM)Elemento focalizado processando o evento chave, elemento raiz se nenhum elemento de entrada adequado estiver focalizado.
char {{readonlyInline}}DOMString (string)O valor do caractere da chave. Se a chave corresponder a um caractere imprimível, esse valor será uma string Unicode não vazia contendo esse caractere. Se a chave não tiver uma representação imprimível, esta é uma string vazia. Veja nomes de chaves e valores de caracteres para os detalhes. +
Nota: Se a chave for usada como uma macro que insere vários caracteres, o valor desse atributo é a cadeia inteira, não apenas o primeiro caractere.
+
key {{readonlyInline}}DOMString (string) +

O valor-chave da chave representada pelo evento. Se o valor tiver uma representação impressa, o valor desse atributo será o mesmo da charpropriedade. Caso contrário, é uma das cadeias de valores de chave especificadas nos valores de chave . Se a chave não puder ser identificada, seu valor será a string "Unidentified". Veja os nomes das chaves e os valores de caracteres para mais detalhes. Somente leitura.

+
code {{readonlyInline}}DOMString (string)Contém uma string que identifica a tecla física sendo pressionada. O valor não é afetado pelo layout do teclado atual ou pelo estado do modificador, portanto, uma chave específica sempre retornará o mesmo valor.
charCode {{readonlyInline}}Longo não assinado (int)O número de referência Unicode da chave; esse atributo é usado apenas pelo keypressevento. Para chaves cujo charatributo contém vários caracteres, esse é o valor Unicode do primeiro caractere nesse atributo. +
Aviso: este atributo está obsoleto; você deve usar em charvez disso, se disponível.
+
keyCode {{readonlyInline}}Longo não assinado (int)Um código numérico dependente do sistema e da implementação que identifica o valor não modificado da tecla pressionada. Este é geralmente o código ASCII decimal ({{RFC (20)}}) ou Windows 1252 correspondente à chave; veja {{anch ("Códigos de teclas virtuais")}} para uma lista de valores comuns. Se a chave não puder ser identificada, esse valor será 0. +
Aviso: este atributo está obsoleto; você deve usar em keyvez disso, se disponível.
+
which {{readonlyInline}}Longo não assinado (int)Um código numérico dependente do sistema e da implementação identificando o valor não modificado da tecla pressionada; isso geralmente é o mesmo que keyCode. +
Aviso: este atributo está obsoleto; você deve usar em keyvez disso, se disponível.
+
location {{readonlyInline}}longo (flutuar)A localização da chave no dispositivo.
repeat {{readonlyInline}}boleanotruese uma tecla foi pressionada o tempo suficiente para disparar a repetição da tecla, caso contrário false.
locale {{readonlyInline}}cordaO código do idioma para o evento principal, se disponível; caso contrário, a cadeia vazia.
ctrlKey {{readonlyInline}}boleanotruese a chave de controle estava inativa quando o evento foi disparado. falsede outra forma.
shiftKey {{readonlyInline}}boleanotruese a tecla shift estava inativa quando o evento foi disparado. falsede outra forma.
altKey {{readonlyInline}}boleanotruese a tecla ALT estava desativada quando o evento foi disparado. falsede outra forma.
metaKey {{readonlyInline}}boleanotruese a meta key estava desativada quando o evento foi disparado. falsede outra forma.
+ +

Exemplo

+ +
document.addEventListener ('keypress', (event) => {
+  const keyName = event.key;
+  alert ('keypress event \ n \ n' + 'chave:' + nome da chave);
+});
+
+ +

Compatibilidade do navegador

+ +

O Chrome não dispara o keypressevento para atalhos de teclado conhecidos ( referência ). Quais atalhos de teclado são conhecidos depende do sistema do usuário. Use o keydownevento para implementar atalhos de teclado.

+ +

Eventos Relacionados

+ + diff --git a/files/pt-br/web/api/document/keyup_event/index.html b/files/pt-br/web/api/document/keyup_event/index.html new file mode 100644 index 0000000000..6423993b63 --- /dev/null +++ b/files/pt-br/web/api/document/keyup_event/index.html @@ -0,0 +1,151 @@ +--- +title: keyup +slug: Web/API/Document/keyup_event +tags: + - Evento de teclado +translation_of: Web/API/Document/keyup_event +--- +

O evento keyup é acionado quando uma tecla é liberada.

+ +

Informações gerais

+ +
+
Especificação
+
DOM L3
+
Interface
+
KeyboardEvent
+
Método Bolha
+
Sim
+
Cancelável
+
Sim
+
Alvo
+
Documento, Elemento
+
Ação Padrão
+
Nenhuma
+
+ +

Propriedades

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
target {{readonlyInline}}EventTargetThe event target (the topmost target in the DOM tree).
type {{readonlyInline}}DOMStringThe type of event.
bubbles {{readonlyInline}}BooleanWhether the event normally bubbles or not
cancelable {{readonlyInline}}BooleanWhether the event is cancellable or not?
view {{readonlyInline}}WindowProxydocument.defaultView (window of the document)
detail {{readonlyInline}}long (float)0.
target {{readonlyInline}}EventTarget (DOM element)Focused element processing the key event, root element if no suitable input element focused.
char {{readonlyInline}}DOMString (string)The character value of the key. If the key corresponds to a printable character, this value is a non-empty Unicode string containing that character. If the key doesn't have a printable representation, this is an empty string. See key names and char values for the detail. +
Note: If the key is used as a macro that inserts multiple characters, this attribute's value is the entire string, not just the first character.
+
key {{readonlyInline}}DOMString (string)The key value of the key represented by the event. If the value has a printed representation, this attribute's value is the same as the char attribute. Otherwise, it's one of the key value strings specified in {{ anch("Key values") }}. If the key can't be identified, this is the string "Unidentified". See key names and char values for the detail. Read Only.
charCode {{readonlyInline}}Unsigned long (int)The Unicode reference number of the key; this attribute is used only by the keypress event. For keys whose char attribute contains multiple characters, this is the Unicode value of the first character in that attribute. +
Warning: This attribute is deprecated; you should use char instead, if available.
+
keyCode {{readonlyInline}}Unsigned long (int)A system and implementation dependent numerical code identifying the unmodified value of the pressed key. This is usually the decimal ASCII ({{ RFC(20) }}) or Windows 1252 code corresponding to the key; see {{ anch("Virtual key codes") }} for a list of common values. If the key can't be identified, this value is 0. +
Warning: This attribute is deprecated; you should use key instead, if available.
+
which {{readonlyInline}}Unsigned long (int)A system and implementation dependent numeric code identifying the unmodified value of the pressed key; this is usually the same as keyCode. +
Warning: This attribute is deprecated; you should use key instead, if available.
+
location {{readonlyInline}}long (float)The location of the key on the device.
repeat {{readonlyInline}}booleantrue if a key has been depressed long enough to trigger key repetition, otherwise false.
locale {{readonlyInline}}stringThe language code for the key event, if available; otherwise, the empty string.
ctrlKey {{readonlyInline}}booleantrue if the control key was down when the event was fired. false otherwise.
shiftKey {{readonlyInline}}booleantrue if the shift key was down when the event was fired. false otherwise.
altKey {{readonlyInline}}booleantrue if the alt key was down when the event was fired. false otherwise.
metaKey {{readonlyInline}}booleantrue if the meta key was down when the event was fired. false otherwise.
+ +

Eventos Relacionados

+ + diff --git a/files/pt-br/web/api/document/location/index.html b/files/pt-br/web/api/document/location/index.html new file mode 100644 index 0000000000..ebf1f2aa27 --- /dev/null +++ b/files/pt-br/web/api/document/location/index.html @@ -0,0 +1,108 @@ +--- +title: Document.location +slug: Web/API/Document/location +translation_of: Web/API/Document/location +--- +

{{APIRef("DOM")}}

+ +

A propriedade, de apenas leitura, Document.location retorna um objeto {{domxref("Location")}}, que contém informações sobre a URL do documento e provém métodos para mudar a URL e carregar outra URL.

+ +

Embora Document.location seja um objeto Location de apenas leitura,  você pode atribuir um {{domxref("DOMString")}} para ele. Isso significa que você pode trabalhar com document.location, na maioria dos casos, como se fosse uma string: document.location = 'http://www.example.com' é um sinônimo de document.location.href = 'http://www.example.com'.

+ +

Para recuperar somente a URL como uma string, a propriedade de apenas leitura {{domxref("document.URL")}} pode ser utilizada.

+ +

Se o documento atual não estiver no contexto de navegação, o valor retornado será null.

+ +

Sintaxe

+ +
locationObj = document.location
+document.location = 'http://www.mozilla.org' // Equivalente a document.location.href = 'http://www.mozilla.org'
+
+ +

Exemplo

+ +
dump(document.location);
+// Imprime uma string como
+// "http://www.example.com/juicybits.html" to the console
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG', "history.html#the-location-interface", "Document.location")}}{{Spec2('HTML WHATWG')}}Nenhuma mudança de {{SpecName("HTML5 W3C")}}.
{{SpecName('HTML5 W3C', "browsers.html#the-location-interface", "Document.location")}}{{Spec2('HTML5 W3C')}}Definição inicial.
+ +

Compatibilidade de navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticasChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticasAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Veja também

+ + + +

 

diff --git a/files/pt-br/web/api/document/origin/index.html b/files/pt-br/web/api/document/origin/index.html new file mode 100644 index 0000000000..b31decf05f --- /dev/null +++ b/files/pt-br/web/api/document/origin/index.html @@ -0,0 +1,60 @@ +--- +title: Document.origin +slug: Web/API/Document/origin +translation_of: Web/API/Document/origin +--- +
{{APIRef("DOM")}}{{SeeCompatTable}}
+ +

A propriedade read-only Document.origin retorna a origem do documento. Na maioria dos casos, essa propriedade é equivalente a document.defaultView.location.origin.

+ +

Sintaxe

+ +
var origin = document.origin;
+ +

Exemplos

+ +
var origin = document.origin;
+// Nesta página, retorna:'https://developer.mozilla.org'
+
+var origin = document.origin;
+// Em "about:blank", retorna:'null'
+
+var origin = document.origin;
+// Em "data:text/html,<b>foo</b>", retorna:'null'
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('DOM WHATWG', '#dom-document-origin', 'Document.origin')}}{{Spec2('DOM WHATWG')}}Definição inicial.
{{SpecName('HTML WHATWG', '#concept-origin', 'origin for various objects (including Document objects)')}}{{Spec2('HTML WHATWG')}}Definição inicial.
+ +

Compatibilidade entre navegadores

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

Veja também 

+ + diff --git a/files/pt-br/web/api/document/queryselector/index.html b/files/pt-br/web/api/document/queryselector/index.html new file mode 100644 index 0000000000..4489a2e823 --- /dev/null +++ b/files/pt-br/web/api/document/queryselector/index.html @@ -0,0 +1,107 @@ +--- +title: Document.querySelector() +slug: Web/API/Document/querySelector +translation_of: Web/API/Document/querySelector +--- +
+
{{ ApiRef("DOM") }}
+
+ +

Sumário

+ +

Retorna o primeiro elemento dentro do documento (usando ordenação em profundidade, pré-ordenada e transversal dos nós do documento) que corresponde ao grupo especificado de seletores.

+ +

Sintaxe

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

Onde:

+ + + +

Exemplo

+ +

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

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

Notas

+ +

Retorna null se nenhum resultado for encontrado; caso contrário, retorna o primeiro elemento correspondente.

+ +

Se o seletor utilizado for um ID e este ID foi erroneamente utilizado várias vezes no documento, ele retorna somente o primeiro elemento correspondente.

+ +

Gera uma exceção SYNTAX_ERR se o grupo de seletores utilizado for inválido.

+ +

querySelector() foi introduzido com a API de seletores.

+ +

Compatibilidade dos navegadores

+ +

{{CompatibilityTable()}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support13.5 (1.9.1)
+ {{bug(416317)}}
8103.2 (525.3)
+ {{Webkitbug("16587")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support2.1yes910.03.2
+
+ +

Especificação

+ + + +

Veja também:

+ + diff --git a/files/pt-br/web/api/document/queryselectorall/index.html b/files/pt-br/web/api/document/queryselectorall/index.html new file mode 100644 index 0000000000..0a05a06180 --- /dev/null +++ b/files/pt-br/web/api/document/queryselectorall/index.html @@ -0,0 +1,110 @@ +--- +title: Document.querySelectorAll() +slug: Web/API/Document/querySelectorAll +tags: + - CSS + - JavaScript + - querySelector +translation_of: Web/API/Document/querySelectorAll +--- +

{{ ApiRef("DOM") }}

+ +

Introdução

+ +

Retorna uma lista de elementos presentes no documento (usando ordenação em profundidade, pré-ordenada e transversal dos nós do documento) que coincidam com o grupo de seletores especificado. O objeto retornado é uma {{ domxref("NodeList") }}.

+ +

Sintaxe

+ +
elementList = document.querySelectorAll(selectors);
+
+ +

onde

+ + + +

A NodeList retornada irá conter todos os elementos do documento que coincidam com os seletores especificados. Se a string selectors conter um CSS {{ cssxref("PseudoElements") }}, o retorno será uma NodeList vazia.

+ +

Exemplo

+ +

Esse exemplo retorna uma lista de todos os elementos div presentes no document que contenham as classes "note" ou "alert":

+ +
var matches = document.querySelectorAll("div.note, div.alert");
+
+ +

Notas

+ +

Retorna uma {{ jsxref("NodeList") }} não-viva (alterações no DOM não refletem na lista) de todos os elementos que coincidam com os seletores informados.

+ +

Lança uma exceção SYNTAX_ERR se o grupo especificado de seletores for inválido.

+ +

querySelectorAll() foi introduzida na WebApps API.

+ +

Navegadores baseados em WebKit têm um bug: quando a string seletores contém um pseudo-elemento CSS, a {{ jsxref("NodeList") }} retornada não esta vazia, neste caso ela contém o elemento {{ HTMLElement("html") }}.

+ +

Compatibilidade nos navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
PossuiChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico13.5 (1.9.1)8103.2 (525.3)
+
+ +
+ + + + + + + + + + + + + + + + + + + +
PossuiAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico2.1sim910.03.2
+
+ +

Especificação

+ + + +

Veja também

+ + diff --git a/files/pt-br/web/api/document/readystate/index.html b/files/pt-br/web/api/document/readystate/index.html new file mode 100644 index 0000000000..d5d2cea5cd --- /dev/null +++ b/files/pt-br/web/api/document/readystate/index.html @@ -0,0 +1,102 @@ +--- +title: Document.readyState +slug: Web/API/Document/readyState +tags: + - API + - HTML DOM + - Propriedade + - Referencia + - eventos +translation_of: Web/API/Document/readyState +--- +
{{APIRef("DOM")}} {{ gecko_minversion_header("1.9.2") }}
+ +

Sumário

+ +

Retorna "loading" enquanto {{ domxref("document") }} está carregando, "interactive" quando foi carregado porém seus sub-recursos (como imagens, por exemplo) ainda não, e "complete" quando foi totalmente carregado.

+ +
O evento readystatechange é acionado no objeto {{ domxref("document") }} quando esse valor é alterado.
+ +

Sintaxe

+ +
var string = document.readyState;
+
+ + + +

Valores

+ +

readyState de um documento pode ser um dos seguintes:

+ +
+
loading
+
O {{domxref("document")}} ainda está carregando.
+
interactive
+
O documento terminou de ser carregado e o documento foi analisado, mas sub-recursos, como imagens, folhas de estilo e quadros, ainda estão sendo carregados.
+
complete
+
O documento e todos os sub-recursos terminaram de carregar. O estado indica que o {{event("load")}} evento está prestes a disparar.
+
+ + + +

Exemplos

+ +

Diferentes estados de readyState

+ +
switch (document.readyState) {
+  case "loading":
+    // O documento esta carregando
+    break;
+  case "interactive":
+    // O documento acabou de carregar. Nós podemos acessar os elementos do DOM.
+    // mas sub-recursos, como imagens, folhas de estilo e quadros, ainda estão sendo carregados.
+    var span = document.createElement("span");
+    span.textContent = "A <span> element.";
+    document.body.appendChild(span);
+    break;
+  case "complete":
+    // A pagina carregou por completo.
+    console.log("The first CSS rule is: " + document.styleSheets[0].cssRules[0].cssText);
+    break;
+}
+ +

readystatechange como uma alternativa para DOMContentLoaded evento

+ +
// alternativa para DOMContentLoaded evento
+document.onreadystatechange = function () {
+  if (document.readyState === 'interactive') {
+    initApplication();
+  }
+}
+ +

readystatechange como uma alternativa para load evento

+ +
// ternativa para load evento
+document.onreadystatechange = function () {
+  if (document.readyState === 'complete') {
+    initApplication();
+  }
+}
+ +

readystatechange como ouvinte de evento para inserir ou modificar o DOM antes de DOMContentLoaded

+ +
document.addEventListener('readystatechange', event => {
+  if (event.target.readyState === 'interactive') {
+    initLoader();
+  }
+  else if (event.target.readyState === 'complete') {
+    initApp();
+  }
+});
+ +

Especificação

+ + + +

Veja também

+ + diff --git a/files/pt-br/web/api/document/referrer/index.html b/files/pt-br/web/api/document/referrer/index.html new file mode 100644 index 0000000000..cbf8da950d --- /dev/null +++ b/files/pt-br/web/api/document/referrer/index.html @@ -0,0 +1,33 @@ +--- +title: Document.referrer +slug: Web/API/Document/referrer +tags: + - API + - Anterior + - HTML DOM + - NeedsCompatTable + - NeedsMarkupWork + - NeedsSpecTable + - Propriedade + - Página(2) + - Referência(2) +translation_of: Web/API/Document/referrer +--- +
{{APIRef("DOM")}}
+ +

Retorna o URI da página que continha o link para a página atual.

+ +

Sintaxe

+ +
string = document.referrer;
+
+ +

Notas

+ +

O valor retornado será uma string vazia se o usuário tiver chegado na página diretamente (digitando o endereço no navegador ou como um item "Favorito"). Como essa propriedade retorna apenas uma string, ela não dá acesso DOM à página que fez a referência.

+ +

Especificação

+ + diff --git a/files/pt-br/web/api/document/scripts/index.html b/files/pt-br/web/api/document/scripts/index.html new file mode 100644 index 0000000000..f896f837e8 --- /dev/null +++ b/files/pt-br/web/api/document/scripts/index.html @@ -0,0 +1,84 @@ +--- +title: Document.scripts +slug: Web/API/Document/scripts +translation_of: Web/API/Document/scripts +--- +
+
{{ ApiRef("DOM") }}
+
+ +

Retorna uma lista dos elementos {{HTMLElement("script")}} no documento. O objeto retornado é um {{domxref("HTMLCollection")}}.

+ +

Sintaxe

+ +
var scriptList = document.scripts;
+
+ +

O scriptList retornado é um {{domxref("HTMLCollection")}}. Você pode usar isso apenas como um array para obter todos os elementos da lista.

+ +

Exemplo

+ +

Este exemplo é para ver se a página contém elementos {{HTMLElement("script")}}.

+ +
var scripts = document.scripts;
+
+if (scripts.length) {
+  alert("This page has scripts!");
+}
+
+ +

Compatibilidade do navegador

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop("9.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatGeckoMobile("9.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Especificação

+ + diff --git a/files/pt-br/web/api/document/url/index.html b/files/pt-br/web/api/document/url/index.html new file mode 100644 index 0000000000..e4a1d2eab7 --- /dev/null +++ b/files/pt-br/web/api/document/url/index.html @@ -0,0 +1,19 @@ +--- +title: Document.URL +slug: Web/API/Document/URL +translation_of: Web/API/Document/URL +--- +
{{APIRef("DOM")}}
+ +

A propriedade URL (usada apenas para leitura) da Interface {{domxref("Document")}} retorna a URL atual do navegador como um texto (string).

+ +

Síntaxe

+ +
var url_atual = document.URL
+
+ +

Documentação

+ + diff --git a/files/pt-br/web/api/document/write/index.html b/files/pt-br/web/api/document/write/index.html new file mode 100644 index 0000000000..4218430e88 --- /dev/null +++ b/files/pt-br/web/api/document/write/index.html @@ -0,0 +1,108 @@ +--- +title: Document.write() +slug: Web/API/Document/write +tags: + - API + - DOM + - Method + - Reference +translation_of: Web/API/Document/write +--- +
{{ApiRef("DOM")}}
+ +

O método Document.write() grava uma sequência de caracteres em um documento aberto por {{domxref("document.open()")}}.

+ +
Nota: à medida que document.write grava no fluxo de documentos, chamando document.write em um documento fechado (carregado) invoca automaticamente document.open, que limpará o documento.
+ +

Sintaxe

+ +
document.write(markup);
+
+ +

Parametros

+ +
+
markup
+
Uma string contendo o texto a ser gravado no documento.
+
+ +

Exemplo

+ +
<html>
+
+<head>
+  <title>Escreva exemplo</title>
+
+  <script>
+    function newContent() {
+      document.open();
+      document.write("<h1>Sair com o velho - entrar com o novo!</h1>");
+      document.close();
+    }
+  </script>
+</head>
+
+<body onload="newContent();">
+  <p>Algum conteúdo do documento original.</p>
+</body>
+
+</html>
+
+ +

{{EmbedLiveSample("Syntax")}}

+ +

Notas

+ +

Escrevendo em um documento que já foi carregado sem chamar {{domxref("document.open()")}} automaticamente vai chamar document.open. Ao términno da escrita, é recomendável chamar {{domxref("document.close()")}} para dizer ao navegador para encerrar o carregamento da página. O texto que você escreve é analisado no modelo de estrutura do documento. No exemplo acima, o elemento h1 se torna um nó (node) no documento.

+ +

Se chamar document.write() incorporada em uma tag HTML <script> embutida, então document.open() não será chamada. Por exemplo:

+ +
<script>
+  document.write("<h1>Título principal</h1>")
+</script>
+
+ +
Nota: document.write e {{domxref("document.writeln")}} não funcionam em documentos XHTML (você receberá o erro "Operation is not supported" [NS_ERROR_DOM_NOT_SUPPORTED_ERR] no console de erros). Isso acontece ao abrir um arquivo local com a extensão .xhtml ou em qualquer documento exibido com um MIME type application/xhtml+xml {{Glossary("MIME type")}}. Mais informações disponíveis em W3C XHTML FAQ.
+ +
Nota: document.write em deferred ou asynchronous scripts será ignorado, e você receberá uma mensagem como "A call to document.write() from an asynchronously-loaded external script was ignored" no console de erros.
+ +
Nota: Somente no Edge, chamando document.write mais de uma vez em {{HTMLElement("iframe")}} causa o erro "SCRIPT70: Permission denied".
+ +
Nota: A partir de 55, Chrome não executará elementos <script> injetados via document.write() caso haja falta de cache HTTP para usuários em uma conexão 2G. Há uma lista de condições que precisam ser atendidas para que isso seja verdade.
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + +
EspecificaçõesStatusComentario
{{SpecName("HTML WHATWG", "#dom-document-write", "document.write(...)")}}{{Spec2("HTML WHATWG")}}
{{SpecName("DOM2 HTML", "html.html#ID-75233634", "document.write(...)")}}{{Spec2("DOM2 HTML")}}
+ +

Compatibilidade de Browser

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

Veja também

+ + diff --git a/files/pt-br/web/api/document/writeln/index.html b/files/pt-br/web/api/document/writeln/index.html new file mode 100644 index 0000000000..ed2efb2b85 --- /dev/null +++ b/files/pt-br/web/api/document/writeln/index.html @@ -0,0 +1,43 @@ +--- +title: Document.writeln() +slug: Web/API/Document/writeln +tags: + - API + - DOM + - Gecko + - Referencia + - metodo +translation_of: Web/API/Document/writeln +--- +
{{ ApiRef("DOM") }}
+ +

Grava uma seqüência de texto, seguido por um caractere de nova linha a um documento.

+ +

Sintaxes

+ +
document.writeln(line);
+
+ +

Parâmetros

+ + + +

Exemplo

+ +
document.writeln("<p>enter password:</p>");
+
+ +

Notas

+ +

document.writeln é o mesmo que document.write mas acrescenta uma nova linha.

+ +
Note: document.writeln (like document.write) does not work in XHTML documents (you'll get a "Operation is not supported" (NS_ERROR_DOM_NOT_SUPPORTED_ERR) error on the error console). This is the case if opening a local file with a .xhtml file extension or for any document served with an application/xhtml+xml MIME type. More information is available in the W3C XHTML FAQ.
+ +

Especificação

+ +

writeln

diff --git a/files/pt-br/web/api/documentfragment/index.html b/files/pt-br/web/api/documentfragment/index.html new file mode 100644 index 0000000000..5744ea8afe --- /dev/null +++ b/files/pt-br/web/api/documentfragment/index.html @@ -0,0 +1,234 @@ +--- +title: DocumentFragment +slug: Web/API/DocumentFragment +translation_of: Web/API/DocumentFragment +--- +

{{ ApiRef("DOM") }}

+ +

A interface do DocumentFragment representa um objeto de documento mínimo que não possui pai. Ela é utilizada como uma versão leve de {{domxref("Document")}} para armazenar fragmentos bem formados ou fragments potencialmente mal formados de XML.

+ +

Vários outros métodos podem usar um document fragment como argumento (ex. qualquer interface de {{domxref("Node")}} como {{domxref("Node.appendChild")}} e {{domxref("Node.insertBefore")}}) em casos em que os filhos do fragment são acrescentados ou inseridos, e não o próprio fragment.

+ +

Essa interface também é excelente para ser usada com Web components: elementos {{HTMLElement("template")}}  contém um DocumentFragment na propriedade {{domxref("HTMLTemplateElement.content")}} deles.

+ +

Um DocumentFragment pode ser criado usando o método {{domxref("document.createDocumentFragment")}} ou o construtor.

+ +

Propriedades

+ +

Essa interface não tem uma propriedade específica, mas herda de seu pai, {{domxref("Node")}}, e implementa aquelas da interface {{domxref("ParentNode")}}.

+ +
+
{{ domxref("ParentNode.children") }} {{readonlyInline}}{{experimental_inline}}
+
Returns a live {{domxref("HTMLCollection")}} containing all objects of type {{domxref("Node")}} that are children of the DocumentFragment object.
+
{{ domxref("ParentNode.firstElementChild") }} {{readonlyInline}}{{experimental_inline}}
+
Returns the {{domxref("Element")}} that is the first child of the DocumentFragment object, or null if there is none.
+
{{ domxref("ParentNode.lastElementChild") }} {{readonlyInline}}{{experimental_inline}}
+
Returns the {{domxref("Element")}} that is the last child of the DocumentFragment object, or null if there is none.
+
{{ domxref("ParentNode.childElementCount") }} {{readonlyInline}}{{experimental_inline}}
+
Returns an unsigned long giving the amount of children that the DocumentFragment has.
+
+ +

Construtor

+ +
+
{{ domxref("DocumentFragment.DocumentFragment()", "DocumentFragment()") }} {{experimental_inline}}
+
Retorna um objeto DocumentFragment vazio.
+
+ +

Métodos

+ +

This interface inherits the methods of its parent, {{domxref("Node")}}, and implements those of the {{domxref("ParentNode")}} interface.

+ +
+
{{domxref("DocumentFragment.find()")}} {{experimental_inline}}
+
Returns the first matching {{domxref("Element")}} in the tree of the DocumentFragment.
+
{{domxref("DocumentFragment.findAll()")}} {{experimental_inline}}
+
Returns a {{domxref("NodeList")}} of matching {{domxref("Element")}} in the tree of the DocumentFragment.
+
{{domxref("DocumentFragment.querySelector()")}}
+
Returns the first {{domxref("Element")}} node within the DocumentFragment, in document order, that matches the specified selectors.
+
{{domxref("DocumentFragment.querySelectorAll()")}}
+
Returns a {{domxref("NodeList")}} of all the {{domxref("Element")}} nodes within the DocumentFragment that match the specified selectors.
+
+ +
+
{{domxref("DocumentFragment.getElementById()")}}
+
Returns the first {{domxref("Element")}} node within the DocumentFragment, in document order, that matches the specified ID.
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#documentfragment', 'DocumentFragment')}}{{Spec2('DOM WHATWG')}}Added the constructor and the implementation of {{domxref("ParentNode")}}.
{{SpecName('Selectors API Level 2', '#the-apis', 'DocumentFragment')}}{{Spec2('Selectors API Level 2')}}Added the find() and findAll() methods.
{{SpecName('Selectors API Level 1', '#the-apis', 'DocumentFragment')}}{{Spec2('Selectors API Level 1')}}Added the querySelector() and querySelectorAll() methods.
{{SpecName('DOM3 Core', 'core.html#ID-B63ED1A3', 'DocumentFragment')}}{{Spec2('DOM3 Core')}}No change from {{SpecName('DOM2 Core')}}
{{SpecName('DOM2 Core', 'core.html#ID-B63ED1A3', 'DocumentFragment')}}{{Spec2('DOM2 Core')}}No change from {{SpecName('DOM1')}}
{{SpecName('DOM1', 'level-one-core.html#ID-B63ED1A3', 'DocumentFragment')}}{{Spec2('DOM1')}}Initial definition
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1.0{{CompatGeckoDesktop("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
querySelector() and querySelectorAll()1.0{{CompatGeckoDesktop("1.9.1")}}8.010.03.2 (525.3)
findAll() and find() {{experimental_inline}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
DocumentFragment() constructor {{experimental_inline}}28.0{{CompatGeckoDesktop("24.0")}}{{CompatNo}}15.0{{CompatNo}}
ParentNode properties {{experimental_inline}}28.0{{CompatGeckoDesktop("25.0")}}{{CompatNo}}15.0{{CompatNo}}
ParentNode methods {{experimental_inline}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
querySelector() and querySelectorAll()2.1{{CompatGeckoDesktop("1.9.1")}}8.010.03.2 (525.3)
findAll() and find() {{experimental_inline}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
DocumentFragment() constructor {{experimental_inline}}{{CompatUnknown}}{{CompatGeckoMobile("24.0")}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
ParentNode properties {{experimental_inline}}28.0{{CompatGeckoMobile("25.0")}}{{CompatNo}}5.0{{CompatNo}}
ParentNode methods {{experimental_inline}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/domexception/index.html b/files/pt-br/web/api/domexception/index.html new file mode 100644 index 0000000000..743ef8602e --- /dev/null +++ b/files/pt-br/web/api/domexception/index.html @@ -0,0 +1,150 @@ +--- +title: DOMException +slug: Web/API/DOMException +translation_of: Web/API/DOMException +--- +

{{ APIRef("DOM") }}

+ +

A interface DOMException representa um evento anormal (denominado de exceção) durante a chamada ou a espera de um resultado do metodo ou uma solicitação a uma web API. Basicamente, falando, é o tratamento dos erros e condições, dos mesmos, nos processos web.

+ +

Cada exceção tem um nome, que é uma pequena string de estilo "CamelCase" que identifica o erro ou condição anormal.

+ +

Constructor

+ +
+
{{domxref("DOMException.DOMException()", "DOMException()")}} {{experimental_inline}}
+
Returns a DOMException object with a specified message and name.
+
+ +

Properties

+ +
+
{{domxref("DOMException.code")}} {{deprecated_inline}} {{readOnlyInline}}
+
Returns a short that contains one of the {{anch("Error codes", "error code constants")}}, or 0 if none match. This field is used for historical reasons. New DOM exceptions don't use this anymore: they put this info in the {{domxref("DOMException.name")}} attribute.
+
{{domxref("DOMException.message")}} {{readOnlyInline}}
+
Returns a {{ domxref("DOMString") }} representing a message or description associated with the given error name.
+
{{domxref("DOMException.name")}} {{readOnlyInline}}
+
Returns a {{domxref("DOMString")}} that contains one of the strings associated with an error name.
+
+ +

Error names

+ +

Common error names are listed here. Some APIs define their own sets of names, so this is not necessarily a complete list.

+ +
+

Note: Because historically the errors were identified by a numeric value which corresponded with a named variable defined to have that value, some of the entries below indicate the legacy code value and constant name that were used in the past.

+
+ +
+
IndexSizeError
+
The index is not in the allowed range. For example, this can be thrown by the {{ domxref("Range") }} object. (Legacy code value: 1 and legacy constant name: INDEX_SIZE_ERR)
+
HierarchyRequestError
+
The node tree hierarchy is not correct. (Legacy code value: 3 and legacy constant name: HIERARCHY_REQUEST_ERR)
+
WrongDocumentError
+
The object is in the wrong {{ domxref("Document") }}. (Legacy code value: 4 and legacy constant name: WRONG_DOCUMENT_ERR)
+
InvalidCharacterError
+
The string contains invalid characters. (Legacy code value: 5 and legacy constant name: INVALID_CHARACTER_ERR)
+
NoModificationAllowedError
+
The object cannot be modified. (Legacy code value: 7 and legacy constant name: NO_MODIFICATION_ALLOWED_ERR)
+
NotFoundError
+
The object cannot be found here. (Legacy code value: 8 and legacy constant name: NOT_FOUND_ERR)
+
NotSupportedError
+
The operation is not supported. (Legacy code value: 9 and legacy constant name: NOT_SUPPORTED_ERR)
+
InvalidStateError
+
The object is in an invalid state. (Legacy code value: 11 and legacy constant name: INVALID_STATE_ERR)
+
SyntaxError
+
The string did not match the expected pattern. (Legacy code value: 12 and legacy constant name: SYNTAX_ERR)
+
InvalidModificationError
+
The object cannot be modified in this way. (Legacy code value: 13 and legacy constant name: INVALID_MODIFICATION_ERR)
+
NamespaceError
+
The operation is not allowed by Namespaces in XML. (Legacy code value: 14 and legacy constant name: NAMESPACE_ERR)
+
InvalidAccessError
+
The object does not support the operation or argument. (Legacy code value: 15 and legacy constant name: INVALID_ACCESS_ERR)
+
TypeMismatchError {{deprecated_inline}}
+
The type of the object does not match the expected type. (Legacy code value: 17 and legacy constant name: TYPE_MISMATCH_ERR) This value is deprecated; the JavaScript {{jsxref("TypeError")}} exception is now raised instead of a DOMException with this value.
+
SecurityError
+
The operation is insecure. (Legacy code value: 18 and legacy constant name: SECURITY_ERR)
+
NetworkError {{experimental_inline}}
+
A network error occurred. (Legacy code value: 19 and legacy constant name: NETWORK_ERR)
+
AbortError {{experimental_inline}}
+
The operation was aborted. (Legacy code value: 20 and legacy constant name: ABORT_ERR)
+
URLMismatchError {{experimental_inline}}
+
The given URL does not match another URL. (Legacy code value: 21 and legacy constant name: URL_MISMATCH_ERR)
+
QuotaExceededError {{experimental_inline}}
+
The quota has been exceeded. (Legacy code value: 22 and legacy constant name: QUOTA_EXCEEDED_ERR)
+
TimeoutError
+
The operation timed out. (Legacy code value: 23 and legacy constant name: TIMEOUT_ERR)
+
InvalidNodeTypeError {{experimental_inline}}
+
The node is incorrect or has an incorrect ancestor for this operation. (Legacy code value: 24 and legacy constant name: INVALID_NODE_TYPE_ERR)
+
DataCloneError {{experimental_inline}}
+
The object can not be cloned. (Legacy code value: 25 and legacy constant name: DATA_CLONE_ERR)
+
EncodingError {{experimental_inline}}
+
The encoding or decoding operation failed (No legacy code value and constant name).
+
NotReadableError {{experimental_inline}}
+
The input/output read operation failed (No legacy code value and constant name).
+
UnknownError {{experimental_inline}}
+
The operation failed for an unknown transient reason (e.g. out of memory) (No legacy code value and constant name).
+
ConstraintError {{experimental_inline}}
+
A mutation operation in a transaction failed because a constraint was not satisfied (No legacy code value and constant name).
+
DataError {{experimental_inline}}
+
Provided data is inadequate (No legacy code value and constant name).
+
TransactionInactiveError {{experimental_inline}}
+
A request was placed against a transaction which is currently not active, or which is finished (No legacy code value and constant name).
+
ReadOnlyError {{experimental_inline}}
+
The mutating operation was attempted in a "readonly" transaction (No legacy code value and constant name).
+
VersionError {{experimental_inline}}
+
An attempt was made to open a database using a lower version than the existing version (No legacy code value and constant name).
+
OperationError {{experimental_inline}}
+
The operation failed for an operation-specific reason (No legacy code value and constant name).
+
NotAllowedError
+
The request is not allowed by the user agent or the platform in the current context, possibly because the user denied permission (No legacy code value and constant name).
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebIDL', '#idl-DOMException', 'constructor')}}{{Spec2('WebIDL')}}Adds the constructor for the DOMException class. Adds the NotReadableError, UnknownError, ConstraintError, DataError, TransactionInactiveError, ReadOnlyError, VersionError, OperationError, and NotAllowedError values.
{{SpecName('DOM4', '#exception-domexception', 'DOMException')}}{{Spec2('DOM4')}}Added SECURITY_ERR, NETWORK_ERR, ABORT_ERR, URL_MISMATCH_ERR, QUOTA_EXCEEDED_ERR, TIMEOUT_ERR, INVALID_NODE_TYPE_ERR, and DATA_CLONE_ERR. The property code has been deprecated for exception values. The EncodingError value added.
{{SpecName('DOM3 Core', 'core.html#ID-17189187', 'DOMException')}}{{Spec2('DOM3 Core')}}Added of VALIDATION_ERR and TYPE_MISMATCH_ERR.
{{SpecName('DOM2 Core', 'core.html#ID-17189187', 'DOMException')}}{{Spec2('DOM2 Core')}}Added of INVALID_STATE_ERR, SYNTAX_ERR, INVALID_MODIFICATION_ERR, NAMESPACE_ERR, and INVALID_ACCESS_ERR.
{{SpecName('DOM1', 'level-one-core.html#ID-17189187', 'DOMException')}}{{Spec2('DOM1')}}Initial definition.
+ +

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/pt-br/web/api/domimplementation/createdocument/index.html b/files/pt-br/web/api/domimplementation/createdocument/index.html new file mode 100644 index 0000000000..61c90cd7b8 --- /dev/null +++ b/files/pt-br/web/api/domimplementation/createdocument/index.html @@ -0,0 +1,83 @@ +--- +title: DOMImplementation.createDocument() +slug: Web/API/DOMImplementation/createDocument +translation_of: Web/API/DOMImplementation/createDocument +--- +

{{ApiRef("DOM")}}

+ +

O método DOMImplementation.createDocument() cria e retorna um {{domxref("XMLDocument")}}.

+ +

Sintaxe

+ +
doc = document.implementation.createDocument(namespaceURI, qualifiedNameStr, documentType);
+ +

Parâmetros

+ +
+
namespaceURI
+
É um {{domxref("DOMString")}} contendo a URI do namespace do documento que será criado, ou null se o documento não pertencer a nenhum.
+
+ +
+
qualifiedNameStr
+
Is a {{domxref("DOMString")}} containing the qualified name, that is an optional prefix and colon plus the local root element name, of the document to be created.
+
+ +
+
documentType {{optional_inline}}
+
+

Is the {{domxref("DocumentType")}} of the document to be created. It defaults to null.

+
+
+ + + +

Example

+ +
var doc = document.implementation.createDocument ('http://www.w3.org/1999/xhtml', 'html', null);
+var body = document.createElementNS('http://www.w3.org/1999/xhtml', 'body');
+body.setAttribute('id', 'abc');
+doc.documentElement.appendChild(body);
+alert(doc.getElementById('abc')); // [object HTMLBodyElement]
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-domimplementation-createdocument', 'DOMImplementation.createDocument')}}{{Spec2('DOM WHATWG')}}Modified the return type of createDocument() from {{domxref("Document")}} to {{domxref("XMLDocument")}}.
+ The third argument of createDocument(), doctype, is now optional and default to null.
{{SpecName('DOM3 Core', 'core.html#Level-2-Core-DOM-createDocument', 'DOMImplementation.createDocument')}}{{Spec2('DOM3 Core')}}No change from {{SpecName("DOM2 Core")}}
{{SpecName('DOM2 Core', 'core.html#Level-2-Core-DOM-createDocument', 'DOMImplementation.createDocument')}}{{Spec2('DOM2 Core')}}Initial definition.
+ +

Browser compatibility

+ + + +

{{Compat("api.DOMImplementation.createDocument")}}

+ +

See also

+ + diff --git a/files/pt-br/web/api/domimplementation/index.html b/files/pt-br/web/api/domimplementation/index.html new file mode 100644 index 0000000000..e49ceda64a --- /dev/null +++ b/files/pt-br/web/api/domimplementation/index.html @@ -0,0 +1,81 @@ +--- +title: DOMImplementation +slug: Web/API/DOMImplementation +tags: + - API + - DOM + - Interface + - NeedsTranslation + - Reference + - Référence(2) + - TopicStub +translation_of: Web/API/DOMImplementation +--- +

{{ ApiRef("DOM") }}

+ +

The DOMImplementation interface represent an object providing methods which are not dependent on any particular document. Such an object is returned by the {{domxref("Document.implementation")}} property.

+ +

Property

+ +

This interface has no specific property and doesn't inherit any.

+ +

Methods

+ +

No inherited method.

+ +
+
{{domxref("DOMImplementation.createDocument()")}}
+
Creates and returns an {{domxref("XMLDocument")}}.
+
{{domxref("DOMImplementation.createDocumentType()")}}
+
Creates and returns a {{domxref("DocumentType")}}.
+
{{domxref("DOMImplementation.createHTMLDocument()")}}
+
Creates and returns an HTML {{domxref("Document")}}.
+
{{domxref("DOMImplementation.hasFeature()")}}
+
Returns a {{domxref("Boolean")}} indicating if a given feature is supported or not. This function is unreliable and kept for compatibility purpose alone: except for SVG-related queries, it always returns true. Old browsers are very inconsistent in their behavior.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#domimplementation', 'DOMImplementation')}}{{Spec2('DOM WHATWG')}}Removed the getFeature() method.
+ Added the createHTMLDocument() method.
+ Modified the return type of createDocument() from {{domxref("Document")}} to {{domxref("XMLDocument")}}.
{{SpecName('DOM3 Core', 'core.html#ID-102161490', 'DOMImplementation')}}{{Spec2('DOM3 Core')}}Added the getFeature() method (never implemented by any user agent).
{{SpecName('DOM2 Core', 'core.html#ID-102161490', 'DOMImplementation')}}{{Spec2('DOM2 Core')}}Added the createDocument() and createDocumentType() methods.
{{SpecName('DOM1', 'level-one-core.html#ID-102161490', 'DOMImplementation')}}{{Spec2('DOM1')}}Initial definition.
+ +

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/pt-br/web/api/domstring/index.html b/files/pt-br/web/api/domstring/index.html new file mode 100644 index 0000000000..578e449d94 --- /dev/null +++ b/files/pt-br/web/api/domstring/index.html @@ -0,0 +1,52 @@ +--- +title: DOMString +slug: Web/API/DOMString +translation_of: Web/API/DOMString +--- +

{{APIRef("DOM")}}

+ +

DOMString é uma String UTF-16. Como o JavaScript já usa tais strings, uma DOMString é mapeada diretamente a uma {{jsxref("String")}}.

+ +

Passando null para um método ou parâmetro que aceite uma DOMString, tal valor é convertido para a string "null".

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebIDL', '#idl-DOMString', 'DOMString')}}{{Spec2('WebIDL')}}Reformulação da definição para remover alguns casos estranhos.
{{SpecName('DOM3 Core', 'core.html#DOMString', 'DOMString')}}{{Spec2('DOM3 Core')}}Nenhuma mudança da {{SpecName('DOM2 Core')}}
{{SpecName('DOM2 Core', 'core.html#ID-C74D1578', 'DOMString')}}{{Spec2('DOM2 Core')}}Nenhuma mudança da {{SpecName('DOM1')}}
{{SpecName('DOM1', 'level-one-core.html#ID-C74D1578', 'DOMString')}}{{Spec2('DOM1')}}Definição inicial.
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/domstringlist/index.html b/files/pt-br/web/api/domstringlist/index.html new file mode 100644 index 0000000000..48547f3d67 --- /dev/null +++ b/files/pt-br/web/api/domstringlist/index.html @@ -0,0 +1,43 @@ +--- +title: DOMStringList +slug: Web/API/DOMStringList +translation_of: Web/API/DOMStringList +--- +

{{ APIRef("DOM") }}

+ +

Um tipo retornado por algumas APIs, que contém uma lista de DOMString (strings).

+ +

Propriedades

+ +
+
{{domxref("DOMStringList.length")}} {{ReadOnlyInline}}
+
Retorna o número de itens da lista
+
+ +

Métodos

+ +
+
{{domxref("DOMStringList.item()")}}
+
Retorna uma {{domxref("DOMString")}}.
+
{{domxref("DOMStringList.contains()")}}
+
Retorna {{jsxref("Boolean")}} indicando se a string em questão está na lista
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName("HTML WHATWG", "common-dom-interfaces.html#the-domstringlist-interface", "DOMStringList")}}{{Spec2("HTML WHATWG")}}Especificação Inicial
diff --git a/files/pt-br/web/api/domstringmap/index.html b/files/pt-br/web/api/domstringmap/index.html new file mode 100644 index 0000000000..df9d74a7bd --- /dev/null +++ b/files/pt-br/web/api/domstringmap/index.html @@ -0,0 +1,141 @@ +--- +title: DOMStringMap +slug: Web/API/DOMStringMap +translation_of: Web/API/DOMStringMap +--- +

{{ APIRef("HTML DOM") }}

+ +

Usado pelo atributo HTML {{ htmlattrxref("dataset") }} para representar atributos próprios adicionados ao elemento.

+ +

Visão Geral do Método

+ + + + + + + + + + + + + + + + + + + +
DOMString getDataAttr(in DOMString prop);
boolean hasDataAttr(in DOMString prop);
void removeDataAttr(in DOMString prop);
void removeProp(in nsIAtom attr);
void setDataAttr(in DOMString prop, in DOMString value);
+ +

Métodos

+ +

hasDataAttr()

+ +
boolean hasDataAttr(
+  in DOMString prop
+);
+
+ +
Parâmetros
+ +
+
prop
+
Nome da propriedade a qual a existência deve ser verificada.
+
+ +
Retorno
+ +

true se a propriedade existir ou false se não existir.

+ +

removeDataAttr()

+ +
void removeDataAttr(
+  in DOMString prop
+);
+
+ +
Parâmetros
+ +
+
prop
+
Propriedade a ser removida do data set.
+
+ +

removeProp()

+ +

Remove a propriedade do dataset do objeto. Usada para atualizar o objeto de dataset do objeto quando o atributo data-* houver sido removido do elemento.

+ +
void removeProp(
+  in nsIAtom attr
+);
+
+ +
Parâmetros
+ +
+
attr
+
A propriedade a ser removida do dataset.
+
+ +

Compatibilidade

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{ CompatUnknown() }}{{CompatVersionUnknown}}{{ CompatGeckoDesktop("6.0") }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{ CompatUnknown() }}{{CompatVersionUnknown}}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/element/accesskey/index.html b/files/pt-br/web/api/element/accesskey/index.html new file mode 100644 index 0000000000..b05fb5e2b3 --- /dev/null +++ b/files/pt-br/web/api/element/accesskey/index.html @@ -0,0 +1,18 @@ +--- +title: Element.accessKey +slug: Web/API/Element/accessKey +translation_of: Web/API/HTMLElement/accessKey +--- +
{{APIRef("DOM")}}
+ +
 
+ +

A propriedade Element.accessKey define a tecla pelo qual o usuário pode pressionar para saltar para este elemento.

+ +
+

Nota: A propriedade Element.accessKey é raramente usada por causa dos conflitos múltiplos com os atalhos pré-definidos nos navegadores. Para contornar isto, os navegadores implementam o comportamento da tecla de acesso se as teclas são pressionadas com outras teclas "qualificadas" (como Alt + tecla de acesso).

+
+ +

 

+ +

 

diff --git a/files/pt-br/web/api/element/addeventlistener/index.html b/files/pt-br/web/api/element/addeventlistener/index.html new file mode 100644 index 0000000000..fea1e67e7b --- /dev/null +++ b/files/pt-br/web/api/element/addeventlistener/index.html @@ -0,0 +1,322 @@ +--- +title: Element.addEventListener() +slug: Web/API/Element/addEventListener +translation_of: Web/API/EventTarget/addEventListener +--- +

{{apiref("DOM Events")}}

+ +

addEventListener() registra uma única espera de evento em um único alvo. O alvo do evento pode ser um único elemento em um documento, o documento em si, uma janela, ou um XMLHttpRequest.

+ +

Para registrar mais de uma espera de evento como alvo, chame addEventListener() para o mesmo alvo mas com diferentes tipos de evento ou captura de parâmetros.

+ +

Sintaxe

+ +
alvo.addEventListener(type,listener[, options]);
+alvo.addEventListener(type,listener[, useCapture, wantUntrusted {{ Non-standard_inline() }}]); // Gecko/Mozilla only
+ +
+
type
+
Uma linha de texto que representa o tipo de evento a ser esperado.
+
listener
+
O objeto que recebe uma notificação quando um evento do tipo especificado ocorre. Esse objeto precisa implementar a interface do EventListener, ou simplesmente executar uma função JavaScript.
+
useCapture {{ optional_inline() }}
+
Se true, useCapture indica que o usuário deseja iniciar uma captura. Depois de iniciada a captura, todos os eventos do tipo especificado serão enviados à listener registrada antes de serem enviados à qualquer EventTarget abaixo dela na hierarquia de DOMs. Eventos que borbulharem para cima na hierarquia não acionarão a escuta designada  a usar a captura. Veja Eventos DOM Nível 3 para uma explicação detalhada. Perceba que esse parâmetro não é opcional em todos os navegadores. Se não for especificado, useCapture é false.
+
wantsUntrusted {{ Non-standard_inline() }}
+
Se true, o evento pode ser acionado por conteúdo não-confiável. Veja Interação entre páginas com e sem privilégios.
+
+ +
Nota: useCapture tornou-se opcional somente nas versões mais recentes dos principais navegadores; não era opcional antes do Firefox 6, por exemplo. Você deve especificar esse parâmetro para obter uma maior compatibilidade.
+ + +

Exemplo

+ +
<!DOCTYPE html>
+<html>
+<head>
+<title>Exemplo de Evento DOM</title>
+
+<style>
+#t { border: 1px solid red }
+#t1 { background-color: pink; }
+</style>
+
+<script>
+// Função para mudar o conteúdo de t2
+function modifyText() {
+  var t2 = document.getElementById("t2");
+  t2.firstChild.nodeValue = "three";
+}
+
+// Função para adicionar uma espera de evento em t
+function load() {
+  var el = document.getElementById("t");
+  el.addEventListener("click", modifyText, false);
+}
+
+document.addEventListener("DOMContentLoaded", load, false);
+</script>
+
+</head>
+<body>
+
+<table id="t">
+   <tr><td id="t1">one</td></tr>
+   <tr><td id="t2">two</td></tr>
+</table>
+
+</body>
+</html>
+
+ +

View on JSFiddle

+ +

No exemplo acima, modifyText() é uma escuta para eventos de click registrados usando addEventListener(). Um clique em qualquer lugar da tabela irá borbulhar para cima até o manipulador e executar modifyText().

+ +

Se você deseja passar parâmetros para a função de escuta, você deve usar uma função anônima.

+ +
<!DOCTYPE html>
+<html>
+<head>
+<title>Exemplo de Evento DOM</title>
+
+<style>
+#t { border: 1px solid red }
+#t1 { background-color: pink; }
+</style>
+
+<script>
+
+// Função para mudar o conteúdo de t2
+function modifyText(new_text) {
+  var t2 = document.getElementById("t2");
+  t2.firstChild.nodeValue = new_text;
+}
+
+// Função para adicionar uma espera de evento em t
+function load() {
+  var el = document.getElementById("t");
+  el.addEventListener("click", function(){modifyText("four")}, false);
+}
+</script>
+
+</head>
+<body onload="load();">
+
+<table id="t">
+  <tr><td id="t1">one</td></tr>
+  <tr><td id="t2">two</td></tr>
+</table>
+
+</body>
+</html>
+
+ +

Notas

+ +

Por que usar addEventListener?

+ +

addEventListener é a maneira de registrar uma espera de evento como especificada no W3C DOM. Seus benefícios são os seguintes:

+ + + +

Existe outra alternativa, uma maneira ultrapassada de registrar esperas de evento.

+ +

Adicionando uma espera de evento durante um disparo de evento

+ +

Se um EventListener for somado a um EventTarget enquanto está processando um evento, ele não será ativado pelas ações atuais, mas poderá ser ativado em um período posterior no fluxo de eventos, como na fase de borbulha.

+ +

Múltiplas esperas de evento idênticas

+ +

Se múltiplas esperas de evento idênticas forem registradas no mesmo EventTarget com os mesmos parâmetros, as versões duplicadas serão descartadas. Elas não fazem o EventListener ser disparado mais de uma vez, e, como as duplicatas são descartadas, elas não precisam ser removidas manualmente com o método removeEventListener.

+ +

O valor de this no manipulador

+ +

É preferível referenciar o elemento do qual a espera de evento foi disparada, como quando é usado um manipulador genérico para uma série de elementos similares. Quando anexar uma função usando addEventListener(), o valor de this é mudado — perceba que o valor de this é passado para uma função a partir do disparador.

+ +

Nos exemplos acima, o valor de this em modifyText(), quando disparado pelo evento de clique, é uma referência à tabela 't'. Isso é um contraste do comportamento que acontece se o manipulador é adicionado ao HTML fonte:

+ +
<table id="t" onclick="modifyText();">
+  . . .
+ +

O valor de this em modifyText(), quando disparado pelo evento de clique no HTML, será uma referência ao objeto global (no caso, a janela).

+ +
Nota: JavaScript 1.8.5 introduz o método Function.prototype.bind(), que permite especificar o valor que deve ser usado como this para todas as chamadas à uma determinada função. Isso evita problemas quando não é claro o que this será, dependendo do contexto do qual a sua função for chamada. Perceba, entretanto, que é preciso manter uma referência da escuta à mão, para que depois você possa removê-la.
+ +

Este é um exemplo com e sem bind:

+ +
var Algo = function(elemento)
+{
+  this.nome = 'Algo bom';
+  this.onclick1 = function(evento) {
+    console.log(this.nome); // indefinido, porque this é a função de escuta do clique
+  };
+  this.onclick2 = function(evento) {
+    console.log(this.nome); // 'Algo bom', porque this está como objeto Algo através do bind
+  };
+  elemento.addEventListener('click', this.onclick1, false);
+  elemento.addEventListener('click', this.onclick2.bind(this), false); // Truque de bind
+}
+
+ +

Outra solução é usar uma função especial chamada handleEvent para capturar quaisquer eventos:

+ +
var Algo = function(elemento)
+{
+  this.nome = 'Algo bom';
+  this.handleEvent = function(evento) {
+    console.log(this.nome); // 'Algo bom', porque this é o objeto Algo
+    switch(evento.type) {
+      case 'click':
+        // seu codigo aqui...
+        break;
+      case 'dblclick':
+        // seu codigo aqui...
+        break;
+    }
+  };
+  elemento.addEventListener('click', this, false); // Não this.handleEvent, só this
+  elemento.addEventListener('dblclick', this, false); // Não this.handleEvent, só this
+}
+
+ +

Internet Explorer antigos e attachEvent

+ +

Em versões do Internet Explorer anteriores ao IE9, você precisa usar attachEvent em vez do padrão addEventListener. Para dar suporte ao IE, o exemplo acima pode ser modificado para:

+ +
if (el.addEventListener) {
+  el.addEventListener('click', modifyText, false);
+} else if (el.attachEvent)  {
+  el.attachEvent('onclick', modifyText);
+}
+
+ +

Existe um porém com attachEvent: o valor de this será a referência ao objeto window em vez do elemento do qual foi disparado.

+ +

Uma maneira ultrapassada de registrar esperas de evento

+ +

addEventListener() foi introduzido com as especificações de Eventos DOM 2. Antes disso, esperas de evento eram registradas assim:

+ +
// Passe uma função de referência — não adicione '()' depois dela, o que chamaria a função!
+el.onclick = modifyText;
+
+// Usando uma expressão de função
+element.onclick = function() {
+    // ... lógica da função ...
+};
+
+ +

Esse método substitui as esperar de evento de click no elemento, se houve alguma. Igualmente para outros outros eventos e manipuladores de evento associados, como blur (onblur), keypress (onkeypress), e assim por diante.

+ +

Porque era essencialmente uma parte do DOM 0, esse método era largamente suportado e não necessitava de códigos entre-navegadores especiais; logo é normalmente usado para registrar esperas de evento dinâmicamente, a menos que atributos extras do addEventListener() sejam necessários.

+ +

Problemas de memória

+ +
var i;
+var els = document.getElementsByTagName('*');
+
+// Caso 1
+for(i=0 ; i<els.length ; i++){
+  els[i].addEventListener("click", function(e){/*fazer algo*/}, false});
+}
+
+// Caso 2
+function processarEvento(e){
+  /*fazer algo*/
+}
+
+for(i=0 ; i<els.length ; i++){
+  els[i].addEventListener("click", processarEvento, false});
+}
+
+
+ +

No primeiro caso, uma nova função (anônima) é criada em cada turno do loop. No segundo caso, a mesma função previamente declarada é usada como um manipulador de evento. Isso resulta em um consumo menor de memória. Além do mais, no primeiro caso, já que nenhuma referência à função anônima é mantida, não é possível chamar element.removeEventListener porque não há uma referência ao manipulador, enquanto no segundo caso é possível fazer myElement.removeEventListener("click", processEvent, false).

+ +

Compatiblidade de navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico1.0{{ CompatGeckoDesktop(1.0) }}9.071.0
useCapture é opcional1.06.09.011.60{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico1.0{{ CompatGeckoMobile(1.0) }}9.06.01.0
+
+ +

Notas Gecko

+ + + +

Notas Webkit

+ + + +

Veja também

+ + + +

Especificação

+ + diff --git a/files/pt-br/web/api/element/animate/index.html b/files/pt-br/web/api/element/animate/index.html new file mode 100644 index 0000000000..8c8d5e58c5 --- /dev/null +++ b/files/pt-br/web/api/element/animate/index.html @@ -0,0 +1,202 @@ +--- +title: Element.animate() +slug: Web/API/Element/animate +translation_of: Web/API/Element/animate +--- +
{{APIRef('Web Animations')}} {{SeeCompatTable}}
+ +

Um {{domxref("Element")}} de interface do método animate() é um método de atalho o qual cria uma nova {{domxref("Animation")}}, e a aplica ao elemento, então executa a animação. Retorna a instância do objeto {{domxref("Animation")}} criado.

+ +
+

Elementos podem ter múltiplas animações aplicadas a eles. Você pode obter uma lista de animações que afetam um elemento chamando {{domxref("Element.getAnimations()")}}.

+
+ +

Syntax

+ +
var animation = element.animate(keyframes, options); 
+ +

Paramêtros

+ +
+
keyframes
+
+

An Object formatted to represent a set of keyframes.

+
+
opções
+
Ou um inteiro representando a duração da animação (em milisegundos), ou um objeto contendo uma ou mais propriedades de tempo:
+
id {{optional_inline}}
+
+
+
Um propriedade única á animate(): uma DOMString com a qual a animação é referenciada. 
+
+ {{Page("/en-US/docs/Web/API/Web_Animations_API/Animation_timing_properties", "Properties")}}
+
+ +

Opções Futuras

+ +

As seguintes opções atualmente não são embarcadas em nenhum lugar, porém serão adicionadas num futuro próximo.

+ +
+
composite {{optional_inline}}
+
Determina como os valores são combinados entre animações diferentes, separa animações que não especificam suas próprias operações de composição. Padrão para subtitituir. +
    +
  • Adiciona efeito de imposição e aditivação, onde cada iteração sucessiva é executada sobre a última. Por exemplo, com transform translateX(-200px) não sobreescreveria um valor anterior de rotate(20deg) mas resultaria em translateX(-200px) rotate(20deg).
  • +
  • accumulate é similar porém um pouco mais inteligente: blur(2) e blur(5) se tornam blur(7), não blur(2) blur(5).
  • +
  • replace sobreescreve o valor anterior com um novo. 
  • +
+
+
iterationComposite {{optional_inline}}
+
Determines how values build from iteration to iteration in this animation. Can be set to accumulate or replace (see above). Defaults to replace.
+
spacing {{optional_inline}}
+
Determina como quadros-chaves sem deslocamento temporal devem ser distribuidos durante a duração da animação. Padrão para distribute. +
    +
  • distribuir quadro-chaves de posição de forma que a diferença de deslocamento entre quadros-chaves subsequentes seja igual, distribuirá igualmente os quadros-chaves no decorrer do tempo de execução.
  • +
  • paced positions keyframes so that the distance between subsequent values of a specified paced property are equal, that is to say, keyframes are spaced further apart the greater the difference in their property values.
  • +
+ +

 

+
+
+ +

Valor de retorno

+ +

Retorna uma {{domxref("Animation")}}.

+ +

Exemplo

+ +

Na demonstração Down the Rabbit Hole (with the Web Animation API), nós usamos o método conveniente animate() para imediamente criar e executar uma animação no elemento #tunnel para faze-lo fluir em direção superior, infinitamente.
+ Note o array de quadros-chave passado e também o bloco de opções de temporização.

+ +
document.getElementById("tunnel").animate([
+  // keyframes
+  { transform: 'translateY(0px)' },
+  { transform: 'translateY(-300px)' }
+], {
+  // timing options
+  duration: 1000,
+  iterations: Infinity
+});
+
+ +

Especificações

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Animations', '#the-animatable-interface', 'animate()' )}}{{Spec2('Web Animations')}}Initial definition
+ +

Compatibildade entre Navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome("36")}}{{CompatNo}}{{ CompatGeckoDesktop("48.0")}}{{CompatNo}}23{{CompatUnknown}}
id option{{CompatChrome(50.0)}}{{CompatNo}}{{ CompatGeckoDesktop("48.0")}}{{CompatNo}}37{{CompatUnknown}}
composite, iterationComposite, and spacing options{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatChrome(39.0)}}{{CompatChrome(39.0)}}{{ CompatGeckoMobile("48.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
id option{{CompatNo}}{{CompatChrome(50.0)}}{{CompatChrome(50.0)}}{{ CompatGeckoMobile("48.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
composite, iterationComposite, and spacing options{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

Veja Também

+ + diff --git a/files/pt-br/web/api/element/attributes/index.html b/files/pt-br/web/api/element/attributes/index.html new file mode 100644 index 0000000000..b5888e0f04 --- /dev/null +++ b/files/pt-br/web/api/element/attributes/index.html @@ -0,0 +1,166 @@ +--- +title: Element.attributes +slug: Web/API/Element/attributes +tags: + - API + - DOM + - Element + - Elemento + - Property + - Propriedade + - Reference + - Referencia +translation_of: Web/API/Element/attributes +--- +

{{ APIRef("DOM") }}

+ +

A propriedade Element.attributes retorna uma coleção de todos os atributos registrados para um nó especificado. É um {{domxref("NamedNodeMap")}}, e não um Array, então não há os métodos de um {{jsxref("Array")}} e os nós indexados {{domxref("Attr")}} podem ser diferentes entre os navegadores. Para ser mais específico, attributes é um par de chave/valor de strings que representa qualquer informação relacionada ao atributo.

+ +

Sintaxe

+ +
var attr = element.attributes;
+
+ +

Exemplo

+ +

Exemplos básicos

+ +
// Obtem o primeiro elemento <p> no documento
+var para = document.getElementsByTagName("p")[0];
+var atts = para.attributes;
+ +

Listando os atributos dos elementos

+ +

Indexadores numéricos são úteis para percorrer através de todos os atributos de um elemento.
+ O exemplo a seguir percorre através dos nós dos atributos do elemento no documento que tenha o id de "p1", e imprime o valor de cada atributo.

+ +
<!DOCTYPE html>
+
+<html>
+
+ <head>
+  <title>Exemplo com atributos</title>
+  <script type="text/javascript">
+   function listAttributes() {
+     var paragraph = document.getElementById("paragraph");
+     var result = document.getElementById("result");
+
+     // Antes, vamos verificar se o paragrafo tem algum atributo
+     if (paragraph.hasAttributes()) {
+       var attrs = paragraph.attributes;
+       var output = "";
+       for(var i = attrs.length - 1; i >= 0; i--) {
+         output += attrs[i].name + "->" + attrs[i].value;
+       }
+       result.value = output;
+     } else {
+       result.value = "Nenhum atributo para mostrar";
+     }
+   }
+  </script>
+ </head>
+
+<body>
+ <p id="paragraph" style="color: green;">Paragrafo de exemplo</p>
+ <form action="">
+  <p>
+    <input type="button" value="Mostra o nome e o valor do atributo"
+      onclick="listAttributes();">
+    <input id="result" type="text" value="">
+  </p>
+ </form>
+</body>
+</html>
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('DOM WHATWG', '#dom-element-attributes', 'Element.attributes')}}{{Spec2('DOM WHATWG')}}Da {{SpecName('DOM3 Core')}}, movido de {{domxref("Node")}} para {{domxref("Element")}}
{{SpecName('DOM3 Core', 'core.html#ID-84CF096', 'Element.attributes')}}{{Spec2('DOM3 Core')}}Nenhuma alteração a partir da {{SpecName('DOM2 Core')}}
{{SpecName('DOM2 Core', 'core.html#ID-84CF096', 'Element.attributes')}}{{Spec2('DOM2 Core')}}Nenhuma alteração a partir da {{SpecName('DOM1')}}
{{SpecName('DOM1', 'level-one-core.html#ID-84CF096', 'Element.attributes')}}{{Spec2('DOM1')}}Definição inicial.
+ +

Compatibilidade entre os navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }} [1]6.0 [2]{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FuncionalidadeAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }} [1]{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

[1] Antes do Firefox 22, este atributo foi implementado na interface {{domxref("Node")}} (herdada por {{domxref("Element")}}). foi movido para esta interface para obedecer a especificação e o uso em outros navegadores.

+ +

[2] Internet Explorer 5.5 retorna um map contendo os valores ao invés dos objetos do atributo.

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/element/classlist/index.html b/files/pt-br/web/api/element/classlist/index.html new file mode 100644 index 0000000000..03b79e63d5 --- /dev/null +++ b/files/pt-br/web/api/element/classlist/index.html @@ -0,0 +1,171 @@ +--- +title: Element.classList +slug: Web/API/Element/classList +translation_of: Web/API/Element/classList +--- +
{{APIRef("DOM")}}
+ +

O Element.classList é uma propriedade somente leitura que retorna uma coleção {{domxref ("DOMTokenList")}} ativa dos atributos de classe do elemento.

+ +

Usar classList é uma alternativa conveniente para acessar a lista de classes de um elemento como uma seqüência delimitada por espaço através de {{domxref ("element.className")}}.

+ +

Sintaxe

+ +
const elementClasses = elementNodeReference.classList;
+
+ +

elementClasses é um DOMTokenList que representa o atributo de classe de elementNodeReference. Se o atributo de classe não foi definido ou está vazio elementClasses.length retorna 0. element.classList propriamente dito é somente leitura, embora você possa modificá-lo usando os métodos add () e remove ().

+ +

Métodos

+ +
+
add( String [, String] )
+
Adicione valores de classe especificados. Se essas classes já existem no atributo do elemento, elas são ignoradas.
+
remove( String [,String] )
+
Remover valores de classe específicos.
+
item ( Number )
+
Retorna o valor da classe por índice na coleção.
+
toggle ( String [, force] )
+
Quando apenas um argumento está presente: Toggle class value; Ou seja, se a classe existir, em seguida, removê-lo e retornar false, se não, então adicioná-lo e retornar true.
+ Quando um segundo argumento está presente: Se o segundo argumento é avaliado como true, adicione o valor especificado da classe e, se ele for avaliado como false, remova-o.
+
contains( String )
+
Verifica se o valor da classe especificado existe no atributo de classe do elemento.
+
+ +

Exemplos

+ +
// div é uma referência de objeto para um elemento <div> com class = "foo bar"
+div.classList.remove("foo");
+div.classList.add("anotherclass");
+
+// Se estiver visível, remova-o, caso contrário, adicione-o
+div.classList.toggle("visible");
+
+// adicionar/remover, dependendo do teste condicional, i menos de 10
+div.classList.toggle("visible", i < 10 );
+
+alert(div.classList.contains("foo"));
+
+// adicionar ou remover várias classes
+div.classList.add("foo","bar");
+div.classList.remove("foo", "bar");
+ +
+

As versões do Firefox antes de 26 não implementam o uso de vários argumentos nos métodos add / remove / toggle. Veja https://bugzilla.mozilla.org/show_bug.cgi?id=814014

+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçõesStatusComentário
{{SpecName("HTML WHATWG", "dom.html#dom-classlist", "Element.classList")}}{{Spec2("HTML WHATWG")}}Observe dentro da especificação HTML relacionada ao {{htmlattrxref("class")}} attribute.
{{SpecName("DOM WHATWG", "#dom-element-classlist", "Element.classList")}}{{Spec2("DOM WHATWG")}}Definição inicial
{{SpecName("DOM4", "#dom-element-classlist", "Element.classList")}}{{Spec2("DOM4")}} 
+ +

Compatibilidade do navegador

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support8.0{{CompatVersionUnknown}}[3]{{CompatGeckoDesktop("1.9.2")}}10[1][3]11.505.1
toggle method's second argument24{{CompatVersionUnknown}}{{CompatGeckoDesktop("24")}}{{CompatNo}}[2]155.1
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support3.0{{CompatVersionUnknown}}{{CompatGeckoMobile("1.9.2")}}1011.105.0
toggle method's second argument{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("24")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Não suportado para elementos SVG. Veja a report at Microsoft about that.
+ [2] O Internet Explorer nunca implementou isso. Veja a report at Microsoft about that.
+ [3] Internet Explorer usa apenas o primeiro parâmetro em "add" e "remove".

+ +

 

+ +

 

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/element/classname/index.html b/files/pt-br/web/api/element/classname/index.html new file mode 100644 index 0000000000..1db2b4f71e --- /dev/null +++ b/files/pt-br/web/api/element/classname/index.html @@ -0,0 +1,123 @@ +--- +title: Element.className +slug: Web/API/Element/className +tags: + - API + - DOM + - Gecko + - Property + - Reference +translation_of: Web/API/Element/className +--- +
{{APIRef("DOM")}}
+ +

Sumário

+ +

className retorna e define o valor do atributo class do elemento especificado.

+ +

Syntax

+ +
var cName = elementNodeReference.className;
+elementNodeReference.className = cName;
+ + + +

Exemplo

+ +
var element = document.getElementById("div1");
+
+if (element.className === "fixed") {
+  // verifica a partir de uma classe específica do elemento
+  goNextElement();
+}
+ +

Notas

+ +

O nome className é utilizado para esta propriedade ao invés de class por conta de conflitos com a palavra-chave "class" em variáveis linguagens que são utilizadas para manipulação do DOM.

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("DOM WHATWG", "#dom-element-classname", "element.className")}}{{Spec2("DOM WHATWG")}} 
{{SpecName("DOM4", "#dom-element-classname", "element.className")}}{{Spec2("DOM4")}} 
{{SpecName("DOM2 HTML", "html.html#ID-95362176", "element.className")}}{{Spec2("DOM2 HTML")}}Definição inicial
+ +

Compatibilidade de Browser

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
RecursoChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte Básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
RecursoAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte Básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/element/click_event/index.html b/files/pt-br/web/api/element/click_event/index.html new file mode 100644 index 0000000000..1044c53281 --- /dev/null +++ b/files/pt-br/web/api/element/click_event/index.html @@ -0,0 +1,276 @@ +--- +title: click +slug: Web/API/Element/click_event +translation_of: Web/API/Element/click_event +--- +

O evento click event é disparado quando o botão de um dispositivo apontador (normalmente o botão de um mouse) é pressionado e solto logo em seguida em um mesmo elemento.

+ +

Informações gerais

+ +
+
Especificação
+
DOM L3
+
Interface
+
{{domxref("MouseEvent")}}
+
Bubbles
+
Sim
+
Cancelável
+
Sim
+
Target
+
Element
+
Ação padrão
+
Variável
+
+ +

Propriedades

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
target {{readonlyInline}}EventTargetO alvo do evento (o mais alto na arvore de DOM).
type {{readonlyInline}}DOMStringTipo do evento.
bubbles {{readonlyInline}}BooleanSe o evento "bubbles" naturalmente ou não.
cancelable {{readonlyInline}}BooleanSe o evento é cancelável ou não
view {{readonlyInline}}WindowProxydocument.defaultView (window do documento)
detail {{readonlyInline}}long (float) +

Um contador de cliques consecutivos que ocorrem em um curto espaço de tempo, incrementado em 1.

+
currentTarget {{readonlyInline}}EventTargetO node que contem o eventListener.
relatedTarget {{readonlyInline}}EventTargetPara eventos mouseover, mouseout, mouseentermouseleave: o alvo do evento complementar (o mouseleave no caso de um evento mouseenter ). null , se falso.
screenX {{readonlyInline}}longA coordenada X do ponteiro do mouse na tela.
screenY {{readonlyInline}}longA coordenada Y do ponteiro do mouse na tela.
clientX {{readonlyInline}}longA coordenada X do ponteiro do mouse no DOM atual.
clientY {{readonlyInline}}longA coordenada Y do ponteiro do mouse no DOM atual.
button {{readonlyInline}}unsigned shortThe button number that was pressed when the mouse event was fired: Left button=0, middle button=1 (if present), right button=2. For mice configured for left handed use in which the button actions are reversed the values are instead read from right to left.
buttons {{readonlyInline}}unsigned shortThe buttons being pressed when the mouse event was fired: Left button=1, Right button=2, Middle (wheel) button=4, 4th button (typically, "Browser Back" button)=8, 5th button (typically, "Browser Forward" button)=16. If two or more buttons are pressed, returns the logical sum of the values. E.g., if Left button and Right button are pressed, returns 3 (=1 | 2). More info.
mozPressure {{readonlyInline}}floatThe amount of pressure applied to a touch or tabdevice when generating the event; this value ranges between 0.0 (minimum pressure) and 1.0 (maximum pressure).
ctrlKey {{readonlyInline}}booleantrue if the control key was down when the event was fired. false otherwise.
shiftKey {{readonlyInline}}booleantrue if the shift key was down when the event was fired. false otherwise.
altKey {{readonlyInline}}booleantrue if the alt key was down when the event was fired. false otherwise.
metaKey {{readonlyInline}}booleantrue if the meta key was down when the event was fired. false otherwise.
+ +

Exemplo

+ +
<div id="test"></div>
+
+<script>
+  document.getElementById("test").addEventListener("click", function( event ) {
+    // mostra o contador de cliques dentro da div clicada
+    event.target.innerHTML = "Total de cliques: " + event.detail;
+  }, false);
+</script>
+
+ +

Compatibilidade nos Browsers

+ +

Internet Explorer

+ +

O Internet Explorer 8 e 9 apresentam um bug onde o elemento com a propriedade {{cssxref("background-color")}} é definida como transparent that are overlaid on top of other element(s) won't receive click events. Todos os eventos click serão disparados no elemento underlying instead. Veja uma demonstração neste exemplo.

+ +

Soluções de contorno para este bug:

+ + + +

Safari Mobile

+ +

Safari Mobile 7.0+ (and likely earlier versions too) suffers from a bug where click events aren't fired on elements that aren't typically interactive (e.g. {{HTMLElement("div")}}) and which also don't have event listeners directly attached to the elements themselves (i.e. event delegation is being used). See this live example for a demonstration. See also Safari's docs on making elements clickable and the definition of "clickable element".

+ +

Known workarounds for this bug:

+ + + +

Safari Mobile considers the following elements to be typically interactive (and thus they aren't affected by this bug):

+ + + +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerEdgeOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
On disabled form elements{{CompatVersionUnknown}}[1]{{CompatNo}}{{CompatVersionUnknown}}[2]{{CompatNo}}{{CompatVersionUnknown}}[1]{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
On disabled form elements{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Only works for {{HTMLElement("textarea")}} elements and some {{HTMLElement("input")}} element types.

+ +

[2] Internet Explorer only triggers the click event on {{HTMLElement("input")}} elements of type checkbox or radio when the element is double-clicked.

+ +

See also

+ + diff --git a/files/pt-br/web/api/element/closest/index.html b/files/pt-br/web/api/element/closest/index.html new file mode 100644 index 0000000000..cfae3b2c98 --- /dev/null +++ b/files/pt-br/web/api/element/closest/index.html @@ -0,0 +1,127 @@ +--- +title: Element.closest() +slug: Web/API/Element/closest +translation_of: Web/API/Element/closest +--- +
{{APIRef("DOM")}}{{SeeCompatTable}}
+ +

O método Element.closest() retorna o ancestral mais próximo, em relação ao elemento atual, que possui o seletor fornecido como parâmetro. No caso de o elemento atual possuir o seletor, o mesmo é retornado.  Caso não exista um ancestral o método retorna null.

+ +

Sintaxe

+ +
var elt = element.closest(selectors);
+
+ +

Parâmetros

+ + + +

Valor retornado

+ + + +

Exceções

+ + + +

Exemplo

+ +
<article>
+  <div id="div-01">Esta é a div-01
+    <div id="div-02">Esta é a div-02
+      <div id="div-03">Esta é a div-03</div>
+    </div>
+  </div>
+</article>
+ +
var el = document.getElementById('div-03');
+
+var r1 = el.closest("#div-02");
+// retorna o elemento com id=div-02
+
+var r2 = el.closest("div div");
+// retorna o ancestral mais próximo que é uma div dentro de uma div, nesse caso div-03 é retornada
+
+var r3 = el.closest("article > div");
+// retorna o ancestral mais próximo que é uma div e tem um article como elemento pai, nesse caso div-01 é retornada
+
+var r4 = el.closest(":not(div)");
+// retorna o ancestral mais próximo que não é uma div, neste caso article é retornado
+
+ +

Polyfill

+ +

Para navegadores que não suportam Element.closest(), mas possuem suporte para element.matches() (ou um prefixo equivalente, ou seja IE9+), o seguinte polyfill pode ser usado: 

+ +
if (!Element.prototype.matches)
+    Element.prototype.matches = Element.prototype.msMatchesSelector ||
+                                Element.prototype.webkitMatchesSelector;
+
+if (!Element.prototype.closest)
+    Element.prototype.closest = function(s) {
+        var el = this;
+        if (!document.documentElement.contains(el)) return null;
+        do {
+            if (el.matches(s)) return el;
+            el = el.parentElement;
+        } while (el !== null);
+        return null;
+    };
+
+ +

Contudo, se você de fato precisa dar suporte ao IE 8, você pode usar o polyfill abaixo, o qual é lento mas eficaz. Além disso, ele só garante suporte a seletores CSS 2.1 no IE 8 e ainda pode causar picos de lentidão em websites em produção.

+ +
if (window.Element && !Element.prototype.closest) {
+    Element.prototype.closest =
+    function(s) {
+        var matches = (this.document || this.ownerDocument).querySelectorAll(s),
+            i,
+            el = this;
+        do {
+            i = matches.length;
+            while (--i >= 0 && matches.item(i) !== el) {};
+        } while ((i < 0) && (el = el.parentElement));
+        return el;
+    };
+}
+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('DOM WHATWG', '#dom-element-closest', 'Element.closest()')}}{{Spec2('DOM WHATWG')}}Definição inicial.
+ +

Compatibilidade em navegadores

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

Veja também

+ + diff --git a/files/pt-br/web/api/element/getattribute/index.html b/files/pt-br/web/api/element/getattribute/index.html new file mode 100644 index 0000000000..c5d1a9475b --- /dev/null +++ b/files/pt-br/web/api/element/getattribute/index.html @@ -0,0 +1,76 @@ +--- +title: Element.getAttribute() +slug: Web/API/Element/getAttribute +tags: + - API + - DOM + - Referencia + - metodo +translation_of: Web/API/Element/getAttribute +--- +
{{APIRef("DOM")}}
+ +

Resumo

+ +

getAttribute() retorna o valor de um argumento específico do elemento. Se o atributo não existir, o valor retornado será null ou "" (string vazia). Veja {{Anch("Notas")}} para mais detalhes.

+ +

Sintaxe

+ +
var atributo = element.getAttribute(nomeDoAtributo);
+
+ +

onde

+ + + +

Exemplo

+ +
var div1 = document.getElementById("div1");
+var align = div1.getAttribute("align");
+
+alert(align); // mostra o valor do atributo "align" do elemento com id="div1"
+ +

Notas

+ +

Quando for utilizado para um elemento HTML num DOM sinalizado como documento HTML,  getAttribute() troca de caixa alta para caixa baixa (maiúscula para minúscula) seu argumento antes de prosseguir.

+ +

Essencialmente todos navegadores (Firefox, Internet Explorer, versões recentes do Opera, Safari, Konqueror, e iCab, por exemplo) retornam null quando o atributo especificado não existe no elemento em questão, seguindo que o esboço atual de especificações DOM diz. A velha especificação do DOM 3 Core, por sua vez, diz que correto é retornar uma string vazia e algumas implementações de DOM se comportam dessa forma. Por exemplo, a implementação do getAttribute no XUL (Gecko) segue as especificações do DOM 3 Core e retorna uma string vazia. Consequentemente, deve-se usar {{domxref("Element.hasAttribute()")}} para checar a existência do atributo antes de utilizar o getAttribute()caso exista a possibilidade do argumento inexistir.

+ +
+

Compatibilidade entre browsers

+ +

{{CompatibilityTable}}

+ + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte Básico2923{{CompatVersionUnknown}}{{CompatVersionUnknown}}6
+ +

{{DOMAttributeMethods}}

+
+ +

Especificação

+ + diff --git a/files/pt-br/web/api/element/getboundingclientrect/index.html b/files/pt-br/web/api/element/getboundingclientrect/index.html new file mode 100644 index 0000000000..5f32a3512a --- /dev/null +++ b/files/pt-br/web/api/element/getboundingclientrect/index.html @@ -0,0 +1,84 @@ +--- +title: Element.getBoundingClientRect() +slug: Web/API/Element/getBoundingClientRect +tags: + - API + - CSSOM View + - Método(2) + - Referência(2) +translation_of: Web/API/Element/getBoundingClientRect +--- +
{{APIRef("DOM")}}
+ +

O método Element.getBoundingClientRect() retorna o tamanho de um elemento e sua posição relativa ao viewport.

+ +

Sintaxe

+ +
rectObject = object.getBoundingClientRect();
+
+ +

Valor de retorno

+ +

O valor de retorno é o objeto DOMRect que é a uniāo dos retângulos retornados por getClientRects() para o elemento, ou seja, os atributos border-boxes do CSS associados ao elemento.

+ +

O valor retornado é um objeto DOMRect, que contém as propriedades apenas-leitura left, top, right e bottom que descrevem o border-box em pixels. top e left são relativos às propriedades top-left do viewport.

+ +
+

Nota: {{Gecko("1.9.1")}} adiciona as propriedades width e height ao objeto DOMRect.

+
+ +

Border-boxes vazias são completamente ignoradas. Se todos os border-boxes do elemento são vazias, então é retornado o retângulo com width e height como zero, e no lugar de top e left determina-se o top-left do border-box relacionado ao primeiro box CSS (determinado pela ordem do conteúdo) em relaçāo ao elemento.

+ +

A quantidade de scrolling que foi feita na área do viewport (ou qualquer outra área de qualquer outro elemento scrollable) é tomada com medida ao computar o delimitador do retângulo. Isso significa que as propriedades top e left mudam seus valores tão logo a posiçāo do scroll for alterada (assim seus valores sāo relativos ao viewport e não são absolutos). Se esse não for o comportamento esperado basta adicionar a posição atual do scroll para as propriedades top e left (via window.scrollX e window.scrollY) para pegar os valores constantes independentemente da posiçāo atual do scroll.

+ +

Scripts que requerem uma alta compatibilidade cross-browser podem usar window.pageXOffset e window.pageYOffset ao invés de window.scrollX e window.scrollY. Scripts sem acesso ao window.pageXOffset, window.pageYOffset, window.scrollX e window.scrollY podem usar:

+ +
// Para o scrollX
+(((t = document.documentElement) || (t = document.body.parentNode))
+  && typeof t.ScrollLeft == 'number' ? t : document.body).ScrollLeft
+// Para o scrollY
+(((t = document.documentElement) || (t = document.body.parentNode))
+  && typeof t.ScrollTop == 'number' ? t : document.body).ScrollTop
+
+ +

Exemplo

+ +
// rect é um objeto DOMRect com seis propriedades: left, top, right, bottom, width, height
+var rect = obj.getBoundingClientRect();
+
+ +

Especificaçōes

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName("CSSOM View", "#dom-element-getboundingclientrect", "Element.getBoundingClientRect()")}}{{Spec2("CSSOM View")}}Definiçāo Inicial
+ +

Notas

+ +

getBoundingClientRect() foi primeiramente introduzida no modelo de objeto MS IE DHTML.

+ +

O valor de retorno de getBoundingClientRect() é frozen.

+ +

Compatibilidade

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

Veja também

+ + diff --git a/files/pt-br/web/api/element/getelementsbyclassname/index.html b/files/pt-br/web/api/element/getelementsbyclassname/index.html new file mode 100644 index 0000000000..2660d0009b --- /dev/null +++ b/files/pt-br/web/api/element/getelementsbyclassname/index.html @@ -0,0 +1,108 @@ +--- +title: Element.getElementsByClassName() +slug: Web/API/Element/getElementsByClassName +translation_of: Web/API/Element/getElementsByClassName +--- +
{{APIRef("DOM")}}
+ +

O método getElementsByClassName() da interface {{domxref("Element")}} retorna um {{domxref("HTMLCollection")}} atualizado simultaneamente que contém todos os elementos descendentes da classe ou das classes especificadas.

+ +

O método {{domxref("Document.getElementsByClassName", "getElementsByClassName()")}} da interface {{domxref("Document")}} funciona da mesma forma, exceto que atua em todo o documento, começando da raíz.

+ +

Sintaxe

+ +
var elements = element.getElementsByClassName(names);
+ +

Parâmetros

+ +
+
names
+
Uma {{domxref("DOMString")}} contendo um ou mais nomes de classes separados por espaço em branco.
+
+ +

Valor de retorno

+ +

Um {{domxref("HTMLCollection")}} que contém uma lista de elementos atualizada em tempo real com todos os elementos que são membros das classes especificadas em names.

+ +

Notas de uso

+ +

Habitualmente, o conjunto de elementos retornado será atualizado simultaneamente com as mudanças feitas, refletindo no estado atual da árvore DOM, no elemento em que a função foi chamada. Assim que novos elementos que satisfazem as classes contidas em names são adicionados na subárvore, eles imediatamente aparecem no conjunto de elementos. Em um exemplo similar, se um elemento existente que não satisfaz nenhuma classe contida em names tem as suas classes ajustadas para que satisfaça, ele irá instantaneamente ser adicionado ao conjunto de elementos.

+ +

O oposto disso também acontece; os elementos que não satisfazerem mais as classes contidas em name serão removidos instantaneamente do conjunto.

+ +
+

No modo quirks, o nome das classes são comparadas da forma case-insensitive. Caso contrário, considere case sensitive.

+
+ +

Exemplos

+ +

Usando uma única classe

+ +

Para procurarmos elementos que incluem uma classe específica, nós apenas informamos o nome da classe ao chamar getElementsByClassName():

+ +
element.getElementsByClassName('test');
+ +

Esse exemplo retorna todos os elementos que possuem a classe test, e que também são filhos do elemento que possui o id com valor main:

+ +
document.getElementById('main').getElementsByClassName('test');
+ +

Usando várias classes

+ +

Para retornar elementos que incluem as classes red and test:

+ +
element.getElementsByClassName('red test');
+ +

Examinando os resultados

+ +

You can use either the {{domxref("HTMLCollection.item", "item()")}} method on the returned HTMLCollection or standard array syntax to examine individual elements in the collection. However the following code will not work as one might expect because "matches" will change as soon as any "colorbox" class is removed.

+ +
var matches = element.getElementsByClassName('colorbox');
+
+for (var i=0; i<matches.length; i++) {
+  matches[i].classList.remove('colorbox');
+  matches.item(i).classList.add('hueframe');
+}
+
+ +

Instead, use another method, such as:

+ +
var matches = element.getElementsByClassName('colorbox');
+
+while (matches.length > 0) {
+  matches.item(0).classList.add('hueframe');
+  matches[0].classList.remove('colorbox');
+}
+ +

This code finds descendant elements with the "colorbox" class, adds the class "hueframe", by calling item(0), then removes "colorbox" (using array notation). Another element (if any are left) will then become item(0).

+ +

Filtering the results using array methods

+ +

We can also use methods of {{jsxref("Array.prototype")}} on any {{ domxref("HTMLCollection") }} by passing the {{domxref("HTMLCollection")}} as the method's this value. Here we'll find all {{HTMLElement("div")}} elements that have a class of test:

+ +
var testElements = document.getElementsByClassName('test');
+var testDivs = Array.prototype.filter.call(testElements, function(testElement) {
+  return testElement.nodeName === 'DIV';
+});
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-element-getelementsbyclassname', 'Element.getElementsByClassName()')}}{{Spec2('DOM WHATWG')}}Initial definition
+ +

Browser compatibility

+ + + +

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

diff --git a/files/pt-br/web/api/element/id/index.html b/files/pt-br/web/api/element/id/index.html new file mode 100644 index 0000000000..864b1fe8b3 --- /dev/null +++ b/files/pt-br/web/api/element/id/index.html @@ -0,0 +1,119 @@ +--- +title: Element.id +slug: Web/API/Element/id +tags: + - API + - DOM + - Gecko + - Property + - Reference +translation_of: Web/API/Element/id +--- +
{{ApiRef("DOM")}}
+ +
 
+ +

A propriedade Element.id representa o identificador do elemento, refletindo no atributo global id.

+ +

O ID precisa ser único no documento, e geralmente é utilizado para obter o elemento usando {{domxref("document.getElementById", "getElementById")}}.. Outro uso comum de id é utilizar o ID como um seletor ao estilizar o documento com CSS.

+ +
+

Nota: IDs são case-sensitive, mas você não deve criar IDs cuja única diferença nos nomes sejam letras maiúsculas/minúsculas (veja Case sensitivity in class and id names).

+
+ +

Sintaxe

+ +
var idStr = element.id; // Retorna o id.
+element.id = idStr; // Insere o id
+
+ + + +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('DOM WHATWG', '#dom-element-id', 'id')}}{{Spec2('DOM WHATWG')}}Sem alteração desde {{SpecName('DOM2 HTML')}}.
{{SpecName('DOM2 HTML', 'html.html#ID-63534901', 'id')}}{{Spec2('DOM2 HTML')}}Sem alteração desde {{SpecName('DOM1')}}.
{{SpecName('DOM1', 'level-one-html.html#ID-63534901', 'id')}}{{Spec2('DOM1')}}Definição inicial.
+ +

Compatibilidade com os browsers

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome para AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/element/index.html b/files/pt-br/web/api/element/index.html new file mode 100644 index 0000000000..b3779720d9 --- /dev/null +++ b/files/pt-br/web/api/element/index.html @@ -0,0 +1,529 @@ +--- +title: Element +slug: Web/API/Element +tags: + - API + - DOM + - DOM Reference + - Element + - Interface + - Reference + - Web API +translation_of: Web/API/Element +--- +

{{ APIRef("DOM") }}

+ +

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

+ +

Linguagens fora do domínio da plataforma da Web, como XUL através da interface XULElement, também implementa Element.

+ +

Propriedades

+ +

Herda propriedades de seus parentes {{domxref("Node")}}, e seu próprio parente, {{domxref("EventTarget")}}, e implementa aqueles de {{domxref("ParentNode")}}, {{domxref("ChildNode")}}, {{domxref("NonDocumentTypeChildNode")}}, e {{domxref("Animatable")}}.

+ +
+
{{ domxref("Element.attributes") }}  {{readOnlyInline}}
+
Retorna um {{ domxref("NamedNodeMap") }} que lista todos os atributos associados ao elemento.
+
{{ domxref("ParentNode.childElementCount") }}
+
É um {{jsxref("Number")}} representando o número de nós filhos que são elementos.
+
{{ domxref("ParentNode.children") }}
+
É um {{ domxref("HTMLCollection") }} ao vivo contendo todos os elementos filhos do elemento, como uma coleção.
+
{{ domxref("Element.classList") }} {{readOnlyInline}}
+
Retorna um {{ domxref("DOMTokenList") }} contendo a lista de atributos de classe.
+
{{ domxref("Element.className") }}
+
É um {{domxref("DOMString")}} representando a classe do elemento.
+
{{ domxref("Element.clientHeight") }} {{experimental_inline}} {{readOnlyInline}}
+
Retorna um {{jsxref("Number")}} representando a altura interna do elemento.
+
{{ domxref("Element.clientLeft") }} {{experimental_inline}} {{readOnlyInline}}
+
Retorna um {{jsxref("Number")}} representando a largura da borda do elemento..
+
{{ domxref("Element.clientTop") }} {{experimental_inline}} {{readOnlyInline}}
+
Retorna um {{jsxref("Number")}} representando a largura da borda do topo do elemento.
+
{{ domxref("Element.clientWidth") }} {{experimental_inline}} {{readOnlyInline}}
+
Retorna um {{jsxref("Number")}} representando a largura interna do elemento.
+
{{ domxref("ParentNode.firstElementChild") }}
+
+

É um {{ domxref("Element") }}, o primeiro elemento filho direto de um elemento, ou null se o elemento não tem elementos filho.

+
+
{{ domxref("Element.id") }}
+
É um {{domxref("DOMString")}} representando o id do elemento.
+
{{ domxref("Element.innerHTML") }} {{experimental_inline}}
+
É um {{domxref("DOMString")}} representando a marcação do conteúdo do elemento.
+
{{ domxref("ParentNode.lastElementChild") }}
+
É um {{ domxref("Element") }}, o último elemento filho direto de um elemento, ou null se o elemento não tem elementos filho.
+
{{ domxref("NonDocumentTypeChildNode.nextElementSibling") }}
+
É um {{ domxref("Element") }}, o elemento seguido imediatamente do dito na árvore, ou null se não há nó irmão.
+
{{ domxref("Element.outerHTML") }} {{experimental_inline}}
+
É um {{domxref("DOMString")}} representando a marcação do elemento incluindo seu conteúdo. Quando usado como um setter, substitui o elemento com nós analisados a partir de uma determinada string.
+
{{ domxref("NonDocumentTypeChildNode.previousElementSibling") }}
+
É um {{ domxref("Element") }}, o elemento precedido imediatamente do dito na árvore, ou nulo se não há elemento irmão.
+
{{ domxref("Element.scrollHeight") }} {{experimental_inline}} {{readOnlyInline}}
+
Retorna um {{jsxref("Number")}} representando a altura da vista de rolagem de um elemento.
+
{{ domxref("Element.scrollLeft") }} {{experimental_inline}}
+
É um {{jsxref("Number")}} representando o deslocamento de rolagem esquerdo do elemento.
+
{{ domxref("Element.scrollLeftMax") }} {{non-standard_inline}} {{readOnlyInline}}
+
Retorna um {{jsxref("Number")}} representando o deslocamento de rolagem esquerdo máximo possível para o elemento.
+
{{ domxref("Element.scrollTop") }} {{experimental_inline}}
+
É um {{jsxref("Number")}} representando o deslocamento de rolagem superior de um elemento.
+
{{ domxref("Element.scrollTopMax") }} {{non-standard_inline}} {{readOnlyInline}}
+
Retorna um {{jsxref("Number")}} representando o deslocamento de rolagem máximo superior possível para o elemento.
+
{{ domxref("Element.scrollWidth") }} {{experimental_inline}} {{readOnlyInline}}
+
Retorna um {{jsxref("Number")}} representando a largura de exibição de rolagem do elemento.
+
{{domxref("Element.shadowRoot") }} {{experimental_inline}} {{readOnlyInline}}
+
...
+
{{ domxref("Element.tagName") }} {{readOnlyInline}}
+
Retorna um {{domxref("String")}} com o nome da tag para o elemento em questão.
+
{{ domxref("Element.undoManager")}} {{experimental_inline}} {{readOnlyInline}}
+
Retorna o {{domxref("UndoManager")}} associado com o elemento.
+
{{ domxref("Element.undoScope")}} {{experimental_inline}}
+
É a {{jsxref("Boolean")}} indicando se o elemento é um anular hospedagem de escopo, ou não.
+
+ +

Manipuladores de Eventos

+ +
+
{{ domxref("Element.ongotpointercapture") }}
+
+
{{ domxref("Element.onlostpointercapture") }}
+
+
{{ domxref("Element.onwheel") }} {{ non-standard_inline() }}
+
Retorna o código de manipulação de evento para o evento wheel.
+
+ +

Métodos

+ +

Herda métodos de seus parentes {{domxref("Node")}}, e seu proprío parente, {{domxref("EventTarget")}}, e implementa aqueles de  {{domxref("ParentNode")}}, {{domxref("ChildNode")}}, {{domxref("NonDocumentTypeChildNode")}}, e {{domxref("Animatable")}}.

+ +
+
{{ domxref("EventTarget.addEventListener()") }}
+
Registra um manipulador de evento para um tipo específico de evento no elemento.
+
{{ domxref("Element.closest()")}} {{experimental_inline}}
+
Retorna o {{domxref("Element")}}, descendente deste elemento(ou este elemento em si), que é o ancestral mais próximo dos elementos selecionados pelos seletores dados no parâmetro.
+
{{ domxref("Element.createShadowRoot()")}} {{experimental_inline}}
+
+
{{ domxref("EventTarget.dispatchEvent()") }}
+
Despacha um evento para este nó no DOM e retorna um {{jsxref("Boolean")}} que indica que pelo menos um manipulador não o cancelou.
+
{{domxref("Element.find()")}}{{experimental_inline}}
+
...
+
{{domxref("Element.findAll()")}}{{experimental_inline}}
+
...
+
{{domxref("Animatable.getAnimationPlayers()")}} {{experimental_inline}}
+
+
{{ domxref("Element.getAttribute()") }}
+
Recupera o valor do atributo nomeado do nó atual e o retorna como um {{jsxref("Object")}}.
+
{{ domxref("Element.getAttributeNS()") }}
+
Recupera o valor do atributo com o nome especificado e namespace, do nó atual e o retorna como um {{jsxref("Object")}}.
+
{{ domxref("Element.getAttributeNode()") }} {{obsolete_inline}}
+
Recupera a representação do nó de um atributo nomeado do nó atual e o retorna como um {{ domxref("Attr") }}.
+
{{ domxref("Element.getAttributeNodeNS()") }} {{obsolete_inline}}
+
Recupera a representação de nó do atributo com o nome especificado e namespace, do nó atual e o retorna como um {{ domxref("Attr") }}.
+
{{ domxref("Element.getBoundingClientRect()") }} {{experimental_inline}}
+
...
+
{{ domxref("Element.getClientRects()") }} {{experimental_inline}} TYPE of returnvalue????
+
Retorna uma coleção de retângulos que indicam os retângulos delimitadores para cada linha de texto em um cliente.
+
{{domxref("Element.getDestinationInsertionPoints()")}} {{experimental_inline}}
+
+
{{ domxref("Element.getElementsByClassName()") }}
+
Retorna um {{ domxref("HTMLCollection") }} vivo que contêm todos os descendentes do elemento atual que possui a lista de classes dadas no parâmetro.
+
{{ domxref("Element.getElementsByTagName()") }}
+
Retorna um {{ domxref("HTMLCollection") }} vivo contendo todos os elementos descendentes, de uma etiqueta de nome particular, do elemento atual.
+
{{ domxref("Element.getElementsByTagNameNS()") }}
+
Retorna um {{ domxref("HTMLCollection") }} vivo contendo todos os elementos descendentes, de uma etiqueta de nome particular e namespace, do elemento atual.
+
{{ domxref("Element.hasAttribute()") }}
+
Retorna um {{jsxref("Boolean")}} indicando se o elemento tem o atributo especificado ou não.
+
{{ domxref("Element.hasAttributeNS()") }}
+
Retorna um {{jsxref("Boolean")}} indicando se o elemento tem um atributo especificado, no namespace especificado, ou não.
+
{{ domxref("Element.insertAdjacentHTML") }} {{experimental_inline}}
+
Analisa o texto como HTML ou XML e insere os nós resultantes na árvore em dada posição.
+
{{ domxref("Element.matches()") }} {{experimental_inline}}
+
Retorna um {{jsxref("Boolean")}} indicando se o elemento seria ou não selecionado pelo seletor de string specificada.
+
{{ domxref("Element.querySelector()") }}
+
Retorna {{ domxref("Node") }}...
+
{{ domxref("Element.querySelectorAll") }}
+
Retorna um {{ domxref("NodeList") }}...
+
{{ domxref("Element.releasePointerCapture")}} {{experimental_inline}}
+
+
{{domxref("ChildNode.remove()")}}
+
Remove o elemento da lista de filhos de seu parente.
+
{{ domxref("Element.removeAttribute()") }}
+
Remove um atributo nomeado do nó atual.
+
{{ domxref("Element.removeAttributeNS()") }}
+
Remove o atributo com o nome especificado ou namespace, do nó atual.
+
{{ domxref("Element.removeAttributeNode()") }} {{obsolete_inline}}
+
Remove a representação do nó do atributo nomeado do nó atual.
+
{{ domxref("EventTarget.removeEventListener()") }}
+
Remove um ouvinte de eventos do elemento.
+
{{ domxref("Element.requestFullscreen()") }} {{experimental_inline}}
+
Assíncronamente pede o navegador para fazer o elemento tela cheia.
+
{{ domxref("Element.requestPointerLock()")}} {{experimental_inline}}
+
Permite assíncronamente pedir pelo apontador para ser bloqueado em um dado elemento.
+
+ +
+
{{ domxref("Element.scrollIntoView()") }} {{experimental_inline}}
+
Rola a página até que o elemento apareça na visão.
+
{{ domxref("Element.setAttribute()") }}
+
Define o valor de um atributo nomeado do nó atual.
+
{{ domxref("Element.setAttributeNS()") }}
+
Define o valor do atributo com o nome especificado e namespace, do nó atual.
+
{{ domxref("Element.setAttributeNode()") }} {{obsolete_inline}}
+
Define a representação do nó de um atributo nomeado do nó atual.
+
{{ domxref("Element.setAttributeNodeNS()") }} {{obsolete_inline}}
+
Define a representação do nó do atributo com o nome especificado e namespace, do nó atual.
+
{{ domxref("Element.setCapture()") }} {{non-standard_inline}}
+
Define a captura de evento do mouse, redirecionando todos os eventos de mouse para este elemento.
+
{{domxref("Element.setPointerCapture()")}}
+
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Web Animations", '', '')}}{{Spec2("Web Animations")}}Adicionado o método getAnimationPlayers().
{{SpecName('Undo Manager', '', 'Element')}}{{Spec2('Undo Manager')}}Adicionadas as propriedades undoScopeundoManager.
{{SpecName('Pointer Events', '#extensions-to-the-element-interface', 'Element')}}{{Spec2('Pointer Events')}}Adicionados os seguintes manipuladores de evento: ongotpointercaptureonlostpointercapture.
+ Adicionados os seguintes métodos: setPointerCapture()releasePointerCapture().
{{SpecName('Selectors API Level 2', '#interface-definitions', 'Element')}}{{Spec2('Selectors API Level 2')}}Adicionados os seguintes métodos: matches() (implementado como mozMatchesSelector()), find(), findAll().
{{SpecName('Selectors API Level 1', '#interface-definitions', 'Element')}}{{Spec2('Selectors API Level 1')}}Adicionados os seguintes métodos: querySelector()querySelectorAll().
{{SpecName('Pointer Lock', 'index.html#element-interface', 'Element')}}{{Spec2('Pointer Lock')}}Adicionado o método requestPointerLock().
{{SpecName('Fullscreen', '#api', 'Element')}}{{Spec2('Fullscreen')}}Adicionado o método requestFullscreen().
{{SpecName('DOM Parsing', '#extensions-to-the-element-interface', 'Element')}}{{Spec2('DOM Parsing')}}Adicionadas as seguintes propriedades: innerHTML, e outerHTML.
+ Adicionado o seguinte método: insertAdjacentHTML().
{{SpecName('CSSOM View', '#extensions-to-the-element-interface', 'Element')}}{{Spec2('CSSOM View')}}Adicionadas as seguintes propriedades: scrollTop, scrollLeft, scrollWidth, scrollHeight, clientTop, clientLeft, clientWidth, e clientHeight.
+ Adicionados os seguintes métodos: getClientRects(), getBoundingClientRect(), e scrollIntoView().
{{SpecName('Element Traversal', '#ecmascript-bindings', 'Element')}}{{Spec2('Element Traversal')}}Adicionada herança da interface {{domxref("ElementTraversal")}}.
{{SpecName('DOM WHATWG', '#interface-element', 'Element')}}{{Spec2('DOM WHATWG')}}Removidos os seguintes métodos: closest(), setIdAttribute(), setIdAttributeNS(), e setIdAttributeNode().
+ Removida a propriedade schemaTypeInfo.
+ Modificado o valor de retorno de getElementsByTag()getElementsByTagNS().
+ Movida hasAttributes() da interface Node para esta.
{{SpecName('DOM3 Core', 'core.html#ID-745549614', 'Element')}}{{Spec2('DOM3 Core')}}Adicionados os seguintes métodos: setIdAttribute(), setIdAttributeNS(), e setIdAttributeNode(). Estes métodos nunca foram implementados e foram removidos em especificações posteriores.
+ Adicionada a propriedade schemaTypeInfo. Esta propriedade nunca foi implementada e foi removida em especificações posteriores.
{{SpecName('DOM2 Core', 'core.html#ID-745549614', 'Element')}}{{Spec2('DOM2 Core')}}O método normalize() foi movido para {{domxref("Node")}}.
{{SpecName('DOM1', 'level-one-core.html#ID-745549614', 'Element')}}{{Spec2('DOM1')}}Definição inicial.
+ +

Compatibilidade de Navegador

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico1.0{{CompatGeckoDesktop("1")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}1.0
children{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9")}}7.0 com um bug significativo[1]
+ 9.0 de acordo com as especificações
{{CompatVersionUnknown}}{{CompatNo}}
childElementCount, nextElementSibling, previousElementSibling{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.1")}}9.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}
firstElementChild, lastElementChild{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9")}}9.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}
classList{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.2")}} {{CompatVersionUnknown}}{{CompatVersionUnknown}}
outerHTML {{experimental_inline}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("11")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
clientLeft, clientTop {{experimental_inline}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.1")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
getBoundingClientRect(), getClientRects() {{experimental_inline}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
querySelector(), querySelectorAll()1.0{{CompatGeckoDesktop("1.9.1")}}8.010.03.2 (525.3)
insertAdjacentHTML() {{experimental_inline}}1.0{{CompatGeckoDesktop("8")}}4.07.04.0 (527)
setCapture() {{non-standard_inline}}{{CompatNo}}{{CompatGeckoDesktop("2")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
oncopy, oncut, onpaste {{non-standard_inline}}{{CompatNo}}{{CompatGeckoDesktop("1.9")}}{{CompatVersionUnknown}} {{CompatNo}}
onwheel {{non-standard_inline}}{{CompatNo}}{{CompatGeckoDesktop("17")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
ongotpointercapture, onlostpointercapture, setPointerCapture(), e releasePointerCapture(){{CompatNo}}{{CompatNo}}10.0 {{property_prefix("MS")}}{{CompatNo}}{{CompatNo}}
matches() {{experimental_inline}}{{CompatVersionUnknown}} com o nome não padrão webkitMatchesSelector{{CompatGeckoDesktop("1.9.2")}} com o nome não padrão mozMatchesSelector
+ {{CompatGeckoDesktop("34")}} com o nome padrão
9.0 com o nome não padrão msMatchesSelector11.5 com o nome não padrão oMatchesSelector
+ 15.0 com o nome não padrão webkitMatchesSelector
5.0 com o nome não padrão webkitMatchesSelector
find()findAll(){{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
requestPointerLock()16.0  {{property_prefix("webkit")}}, atrás de um about:flags
+ 22.0 {{property_prefix("webkit")}} (com casos especiais, levantados progressivamente, veja [2])
{{CompatGeckoDesktop("14")}}{{property_prefix("moz")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
requestFullscreen()14.0 {{property_prefix("webkit")}}{{CompatGeckoDesktop("10")}} {{property_prefix("moz")}}11.0 {{property_prefix("ms")}}12.10
+ 15.0 {{property_prefix("webkit")}}
5.1 {{property_prefix("webkit")}}
undoManagerundoScope{{CompatNo}}{{CompatVersionUnknown}} (atrás do pref dom.undo_manager.enabled){{CompatNo}}{{CompatNo}}{{CompatNo}}
attributes{{CompatUnknown}}{{CompatGeckoDesktop("22")}}
+ Antes era disponível via interface {{domxref("Node")}} que qualquer element herda.
{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
scrollTopMax()scrollLeftMax(){{CompatNo}}{{CompatGeckoDesktop("16")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
closest(){{CompatUnknown}}{{CompatGeckoDesktop("35")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
hasAttributes(){{CompatVersionUnknown}}{{CompatGeckoDesktop("1.0")}} (na interface {{domxref("Node")}})
+ {{CompatGeckoDesktop("35")}} (nesta interface)
{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Suporte básico1.0{{CompatGeckoMobile("1")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}1.0
scrollTopMax() and scrollLeftMax(){{CompatNo}}{{CompatGeckoMobile("16")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
closest(){{CompatUnknown}}{{CompatGeckoMobile("35")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
hasAttributes(){{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}} (na interface {{domxref("Node")}})
+ {{CompatGeckoMobile("35")}} (nesta interface)
{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

[1] Internet Explorer 7 e 8 incorretamente retorna os comentários como parte do filho de um Element. Isto está fixado no Internet Explorer 9 e posterior.

+ +

[2] Chrome 16 permitiu webkitRequestPointerLock() somente em tela cheia; Chrome 21 para website confiável(com permissão do usuário);  Chrome 22 permitiu por padrão para todos documentos de mesma origem; Chrome 23 permitiu em testes em ambientes locais {{HTMLElement("iframe")}} se o valor não padrão webkit-allow-pointer-lock é definido para o atributo {{htmlattrxref("sandbox", "iframe")}}.

diff --git a/files/pt-br/web/api/element/innerhtml/index.html b/files/pt-br/web/api/element/innerhtml/index.html new file mode 100644 index 0000000000..f9ba30f9cf --- /dev/null +++ b/files/pt-br/web/api/element/innerhtml/index.html @@ -0,0 +1,148 @@ +--- +title: Element.innerHTML +slug: Web/API/Element/innerHTML +tags: + - API + - DOM + - Gecko + - NeedsBrowserCompatibility + - Propriedade + - Referência(2) +translation_of: Web/API/Element/innerHTML +--- +

{{APIRef("DOM")}}

+ +

A propriedade Element.innerHTML define ou obtém a sintaxe HTML ou XML descrevendo os elementos descendentes.

+ +
Nota: Se um nó {{HTMLElement("div")}}, {{HTMLElement("span")}}, ou {{HTMLElement("noembed")}} tem um nó filho que inclui os caracteres (&), (<), ou (>), o innerHTML retornará esses caracteres como &amp, &lt e &gt respectivamente. Utilize {{domxref("Node.textContent")}} para recuperar uma cópia correta do conteúdo desses nós de texto.
+ +

Sintaxe

+ +
var content = element.innerHTML;
+ +

No retorno, content contém o código HTML serializado descrevendo todos os descendentes dos elementos.

+ +
 element.innerHTML = content;
+ +

Remove todos os elementos filhos, analisa o conteúdo da string e atribui os nós resultantes como filhos do elemento.

+ +

Exceptions

+ +
+
SyntaxError
+
Foi feita uma tentativa de definir o valor de um innerHTML usando uma string que não é HTML.
+
NoModificationAllowedError
+
Foi feita uma tentativa de inserir HTML dentro de um nó no qual o pai é um {{domxref("Document")}}.
+
+ +

Exemplo

+ +
<html>
+<head></head>
+<body>
+
+<div id="txt">
+  <script     id="txt0"> x=0 </script>
+    <noembed    id="txt1"> 1   </noembed>
+    <noframes   id="txt2"> 2   </noframes>
+    <noscript   id="txt3"> 3   </noscript>
+    <div        id="txt4"> 4   </div>
+    <div>
+      <noscript id="txt5"> 5   </noscript>
+    </div>
+    <span       id="txt6"> 6   </span>
+  </div>
+
+  <div id="innerHTMLtxt"></div>
+<div id="textContenttxt"><div>
+
+<script>
+for (i = 0; i < 7; i++) {
+    x = "txt" + i;
+    document.getElementById(x).firstChild.nodeValue = '&<>';
+}
+
+document.getElementById("innerHTMLtxt").textContent = document.getElementById("txt").innerHTML
+document.getElementById("textContenttxt").textContent = document.getElementById("txt").textContent
+</script>
+
+<body>
+</html>
+ +
// HTML:
+// <div id="d"><p>Content</p>
+// <p>Further Elaborated</p>
+// </div>
+
+const d = document.getElementById("d");
+dump(d.innerHTML);
+
+//  a string "<p>Content</p><p>Further Elaborated</p>"
+// é exibida na janela do console
+
+ +

Notas

+ +

Essa propriedade fornece uma forma simples de trocar completamente o conteúdo de um elemento. Por exemplo, o conteúdo inteiro do elemento body pode ser excluído ao fazer:

+ +
// Troca o conteúdo de body por uma string vazia.
+document.body.innerHTML = "";  
+ +

A propriedade innerHTML de vários tipos de elementos — incluindo {{HTMLElement("body")}} ou {{HTMLElement("html")}} — pode ser retornada ou trocada. Essa também pode ser usada para ver o código fonte de uma página que foi modificada dinamicamente:

+ +
// Copie e cole este código, em uma única linha, na barra de endereços
+javascript:"<pre>"+document.documentElement.innerHTML.replace(/</g,"&lt;") + "</pre>";
+
+ +

Essa propriedade foi implementada inicialmente pelos navegadores web, e então especificada pela WHATWG e W3C no HTML5. Implementações antigas talvez não tenham implementado-a exatamente da mesma forma. Por exemplo, quando um texto é inserido em uma caixa de texto, o Internet Explorer muda o valor do atributo innerHTML dessa entrada, mas os navegadores Gecko não.

+ +

Considerações de segurança

+ +

Não é incomum ver a propriedade innerHTML usada para inserir texto em uma página web. Isso vem com um risco de segurança.

+ +
var name = "John";
+
+// presumindo que el é um elemento DOM HTML
+el.innerHTML = name; // inofensivo, nesse caso
+
+// ...
+
+name = "<script>alert('I am John in an annoying alert!')</script>";
+el.innerHTML = name; // inofensivo, nesse caso
+ +

Embora isso talvez se pareça como um ataque  {{interwiki("wikipedia", "cross-site scripting")}}, o resultado é inofensivo. O HTML5 especifica que uma tag {{HTMLElement("script")}}, inserida via innerHTML, não deve ser executada.

+ +

No entanto, há formas de se executar JavaScript sem usar elementos {{HTMLElement("script")}}, por isso ainda há um risco de segurança sempre que você usa innerHTML para definir uma string sobre a qual você não tem controle. Por exemplo:

+ +
const name = "<img src='x' onerror='alert(1)'>";
+el.innerHTML = name; // exibe uma caixa de alerta
+ +

Por essa razão, recomenda-se que você não use o innerHTML quando estiver inserindo texto puro; como alternativa, utilize {{domxref("node.textContent")}}. Isso não interpreta o conteúdo passado como HTML, mas em vez disso, insere-o como texto puro.

+ +

Especificação

+ + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('DOM Parsing', '#widl-Element-innerHTML', 'Element.innerHTML')}}{{ Spec2('DOM Parsing') }}Definição inicial
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/element/insertadjacenthtml/index.html b/files/pt-br/web/api/element/insertadjacenthtml/index.html new file mode 100644 index 0000000000..89a0bbdfcc --- /dev/null +++ b/files/pt-br/web/api/element/insertadjacenthtml/index.html @@ -0,0 +1,138 @@ +--- +title: Element.insertAdjacentHTML() +slug: Web/API/Element/insertAdjacentHTML +translation_of: Web/API/Element/insertAdjacentHTML +--- +
{{APIRef("DOM")}}
+ +

Resumo

+ +

insertAdjacentHTML analisa o texto especificado como HTML ou XML e insere os nós que resultam na árvore DOM em uma posição especificada. Não reanalisa o elemento que está a ser utilizado e, portanto, não corrompe os elementos existentes dentro do elemento. Esta, e evitando a etapa extra de serialização, torna-o muito mais rápido do que a manipulação direta innerHTML.

+ +

Sintaxe

+ +
element.insertAdjacentHTML(posição, texto);
+ +

Posição é a posição em relação ao elemento, e deve ser um dos seguintes tipos:

+ +
+
'beforebegin'
+
Antes do elemento.
+
'afterbegin'
+
Dentro do elemento, antes de seu primeiro filho (childNode).
+
'beforeend'
+
Dentro do elemento, após seu último filho (childNode) .
+
'afterend'
+
Após o elemento.
+
+ +

texto é a string a ser analisada como HTML ou XML e inserido na árvore.

+ +

Visualização da posição de nomes

+ +
<!-- beforebegin -->
+<p>
+<!-- afterbegin -->
+foo
+<!-- beforeend -->
+</p>
+<!-- afterend -->
+ +
Nota:  As posições beforeBegin e afterEnd funcionam apenas se o nó está em uma árvore DOM e tem um elemento pai.
+ +

Exemplo

+ +
// Estrutura inicial:
+// <div id="one">one</div>
+
+var d1 = document.getElementById('one');
+d1.insertAdjacentHTML('afterend', '<div id="two">two</div>');
+
+// Neste ponto, a nova estrutura é:
+// <div id="one">one</div>
+// <div id="two">two</div>
+ +

Especificação

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM Parsing', '#insertadjacenthtml()', 'Element.insertAdjacentHTML()')}}{{ Spec2('DOM Parsing') }} 
+ +

Compatibilidade de Navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico1.0{{ CompatGeckoDesktop("8.0") }}4.0*7.04.0 (527)
+
+ +
+ + + + + + + + + + + + + + + + + + + +
 CaracterísticaAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Suporte básico{{ CompatUnknown() }}{{ CompatGeckoMobile("8.0") }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+ +

 

+ +

Questão no IE:

+ + +
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/element/matches/index.html b/files/pt-br/web/api/element/matches/index.html new file mode 100644 index 0000000000..06ce8b5c31 --- /dev/null +++ b/files/pt-br/web/api/element/matches/index.html @@ -0,0 +1,165 @@ +--- +title: Element.matches() +slug: Web/API/Element/matches +translation_of: Web/API/Element/matches +--- +
{{APIRef("DOM")}}
+ +

O método Element.matches() retorna verdadeiro se o elemento puder ser selecionado pela sequência de caracteres específica; caso contrário retorna falso.

+ +
+

Diversos navegadores implementam isto, prefixado, sob nome não padronizado matchesSelector().

+
+ +

Sintaxe

+ +
var result = element.matches(selectorString);
+
+ + + +

Exemplo

+ +
<ul id="birds">
+  <li>Orange-winged parrot</li>
+  <li class="endangered">Philippine eagle</li>
+  <li>Great white pelican</li>
+</ul>
+
+<script type="text/javascript">
+  var birds = document.getElementsByTagName('li');
+
+  for (var i = 0; i < birds.length; i++) {
+    if (birds[i].matches('.endangered')) {
+      console.log('The ' + birds[i].textContent + ' is endangered!');
+    }
+  }
+</script>
+
+ +

Isto irá logar "The Philippine eagle is endangered!" para o console, desde que o elemento tenha de fato um atributo de classe com o valor endangered.

+ +

Exceções

+ +
+
SYNTAX_ERR
+
O seletor de string específico é inválido.
+
+ +

Polyfill

+ +

Para navegadores que não suportam Element.matches() ou Element.matchesSelector(),  mass possuem suporte para document.querySelectorAll(), existe um polyfill:

+ +
if (!Element.prototype.matches) {
+    Element.prototype.matches =
+        Element.prototype.matchesSelector ||
+        Element.prototype.mozMatchesSelector ||
+        Element.prototype.msMatchesSelector ||
+        Element.prototype.oMatchesSelector ||
+        Element.prototype.webkitMatchesSelector ||
+        function(s) {
+            var matches = (this.document || this.ownerDocument).querySelectorAll(s),
+                i = matches.length;
+            while (--i >= 0 && matches.item(i) !== this) {}
+            return i > -1;
+        };
+}
+ +

Especificação

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('DOM WHATWG', '#dom-element-matches', 'Element.prototype.matches')}}{{Spec2('DOM WHATWG')}}Initial definition
+ +

Compatibilidade de navegador

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Original support with a non-standard name +

{{CompatVersionUnknown}}[1]

+
{{CompatGeckoDesktop("1.9.2")}}[2]9.0[3]11.5[4]
+ 15.0[1]
5.0[1]
Specified version{{CompatChrome("34")}}{{CompatGeckoDesktop("34")}}{{CompatUnknown}}21.07.1
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Original support with a non-standard name{{CompatUnknown}}{{CompatGeckoMobile("1.9.2")}}[2]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Specified version{{CompatUnknown}}{{CompatGeckoMobile("34")}}{{CompatUnknown}}{{CompatUnknown}}8
+
+ +

[1] Esta feature foi implementada com o nome não padronizado webkitMatchesSelector.

+ +

[2] Esta feature foi implementada com o nome não padronizado mozMatchesSelector. Anteriormente para o Gecko 2.0, seletores de string inválido faziam com que retornasse false ao invés de empurrar uma exceção.

+ +

[3] Esta feature foi implementada com o nome não padronizado msMatchesSelector.

+ +

[4] Esta feature foi implementada com o nome não padronizado oMatchesSelector.

diff --git a/files/pt-br/web/api/element/mousedown_event/index.html b/files/pt-br/web/api/element/mousedown_event/index.html new file mode 100644 index 0000000000..bbddbff605 --- /dev/null +++ b/files/pt-br/web/api/element/mousedown_event/index.html @@ -0,0 +1,235 @@ +--- +title: mousedown +slug: Web/API/Element/mousedown_event +tags: + - API + - DOM + - Interface + - NeedsSpecTable + - Reference + - events +translation_of: Web/API/Element/mousedown_event +--- +
{{APIRef}}
+ +

O evento mousedown é ativado quando um botão de um dispositivo apontador é pressionado sobre um elemento.

+ +

Informação geral

+ +
+
Especificação
+
DOM L3
+
Interface
+
{{domxref("MouseEvent")}}
+
Bubbles
+
Sim
+
Cancelável
+
Sim
+
Alvo
+
Elemento
+
Ação Padrão
+
Varia: Inicia um operação de arrastar/soltar; inicia a seleção de texto; inicia a interação de rolagem/arrastar (junto do botão do meio do mouse, se suportado)
+
+ +

Propriedades

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
target {{readonlyInline}}{{domxref("EventTarget")}} +

O alvo do evento (o alvo mais alto na árvore do DOM).

+
type {{readonlyInline}}{{domxref("DOMString")}}O tipo de evento
bubbles {{readonlyInline}}BooleanWhether the event normally bubbles or not
cancelable {{readonlyInline}}BooleanO evento é cancelável ou não?
view {{readonlyInline}}{{domxref("WindowProxy")}}{{domxref("document.defaultView")}} (window do documento)
detail {{readonlyInline}}long (float) +

Um número de cliques consecutivos que aconteceu num pequeno espaço de tempo, acrescido em um.

+
currentTarget {{readonlyInline}}{{domxref("EventTarget")}}O nó que teve o listener do evento anexado.
relatedTarget {{readonlyInline}}{{domxref("EventTarget")}}Para os eventos mouseovermouseoutmouseenter e mouseleave: o alvo do evento complementar (o alvo do mouseleave no caso de um evento mouseenter). Caso contrário, null.
screenX {{readonlyInline}}longA coordenada X do mouse baseada nas coordenadas globais (tela).
screenY {{readonlyInline}}longA coordenada Y do mouse baseada nas coordenadas globais (tela).
clientX {{readonlyInline}}longA coordenada X do ponteiro do mouse baseada nas coordenadas locais (conteúdo do DOM).
clientY {{readonlyInline}}longA coordenada Y do ponteiro do mouse baseada nas coordenadas locais (conteúdo do DOM).
button {{readonlyInline}}unsigned shortO número do botão que foi pressionado quando o evento mouse foi ativado: Botão esquerdo = 0, botão do meio = 1 (se presente), botão direito = 2. Para os mouses configurados para uso por canhotos onde as ações do mouse são invertidas, os valores são lidos da direita para a esquerda.
buttons {{readonlyInline}}unsigned short +

Os botões pressionados que foram pressionados quando o evento do mouse foi ativado: Botão esquerdo = 1, botão direito = 2, botão do meio (roda) = 4, 4º botão (geralmente, o "botão de voltar") = 8, 5º botão (geralmente, o "botão de avançar") = 16. Se dois ou mais botões são pressionados, retorna a soma lógica dos valores. Exemplo: se o Botão esquerdo e o Botão direito são pressionados, retorna 3 (=1 | 2). Mais informações.

+
mozPressure {{readonlyInline}}floatA quantidade de pressão aplicada a um dispositivo touch ou tablet quando o evento estava sendo gerado; este valor varia entre 0.0 (pressão mínima) e 1.0 (pressão máxima).
ctrlKey {{readonlyInline}}booleantrue se a tecla control estava pressionada quando o evento foi ativado. Caso contrário, false.
shiftKey {{readonlyInline}}booleantrue se a tecla shift estava pressionada quando o evento foi ativado. Caso contrário, false.
altKey {{readonlyInline}}booleantrue se a tecla alt estava pressionada quando o evento foi ativado. Caso contrário, false.
metaKey {{readonlyInline}}booleantrue se a tecla meta estava pressionada quando o evento foi ativado. Caso contrário, false.
+ +

Compatibilidade entre navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
RecursoChromeFirefox (Gecko)Internet ExplorerEdgeOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Em elementos desativados{{CompatVersionUnknown}}[1]{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown}}[1]{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
RecursoAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Em elementos desativados{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Só funciona em elementos {{HTMLElement("textarea")}} e alguns tipos do elemento {{HTMLElement("input")}}.

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/element/mouseenter_event/index.html b/files/pt-br/web/api/element/mouseenter_event/index.html new file mode 100644 index 0000000000..881958914b --- /dev/null +++ b/files/pt-br/web/api/element/mouseenter_event/index.html @@ -0,0 +1,314 @@ +--- +title: mouseenter +slug: Web/API/Element/mouseenter_event +translation_of: Web/API/Element/mouseenter_event +--- +
{{APIRef}}
+ +

O evento mouseenter é disparado quando um dispositivo de apontamento (geralmente um mouse) se move sobre um elemento (para dentro do mesmo).

+ +

Similar ao {{event('mouseover')}}, ele se diferencia no fato de que não ocorre a fase bubble e não é disparado quando o cursor / apontador mover-se do espaço físico de um de seus descendentes para o seu próprio espaço físico.

+ +
+
mouseenter.png
+Um evento mouseenter é enviado para cada elemento da hierarquia ao entrar neles. Aqui 4 eventos são enviados aos quatro elementos da hierarquia quando o cursor / apontador chega no Text. + +
mouseover.png
+Um único evento mouseover é enviado ao elemento de maior profundidade na árvore DOM, a partir do qual ocorre a fase bubble e o mesmo percorre subindo na hierarquia dos elementos  até que seja cancelado por um handler ou alcance a raíz da árvore.
+ +

De acordo com a profundidade da hierarquia, a quantidade de eventos mouseenter disparados pode se tornar muito grande e causar problemas de performance significativos. Nestes casos é melhor escutar por eventos mouseover.

+ +

Combinado ao comportamento do seu evento simétrico, mouseleave, o evento DOM mouseenter age de modo bastante similar à pseudo-classe CSS {{cssxref(':hover')}}.

+ +

Informações Gerais

+ +
+
Especificação
+
DOM L3
+
Interface
+
{{domxref('MouseEvent')}}
+
Sincronismo
+
Síncrono
+
Fase Bubble
+
Não
+
Cancelável
+
Não
+
Target
+
Element
+
Ação Padrão
+
Nenhuma
+
+ +

Propriedades

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
target {{readonlyInline}}{{domxref("EventTarget")}}The event target (the topmost target in the DOM tree).
type {{readonlyInline}}{{domxref("DOMString")}}The type of event.
bubbles {{readonlyInline}}BooleanWhether the event normally bubbles or not
cancelable {{readonlyInline}}BooleanWhether the event is cancellable or not?
view {{readonlyInline}}{{domxref("WindowProxy")}}{{domxref("document.defaultView")}} (window of the document)
detail {{readonlyInline}}long (float)0.
currentTarget {{readonlyInline}}{{domxref("EventTarget")}}The node that had the event listener attached.
relatedTarget {{readonlyInline}}{{domxref("EventTarget")}}For mouseover, mouseout, mouseenter and mouseleave events: the target of the complementary event (the mouseleave target in the case of a mouseenter event). null otherwise.
screenX {{readonlyInline}}longThe X coordinate of the mouse pointer in global (screen) coordinates.
screenY {{readonlyInline}}longThe Y coordinate of the mouse pointer in global (screen) coordinates.
clientX {{readonlyInline}}longThe X coordinate of the mouse pointer in local (DOM content) coordinates.
clientY {{readonlyInline}}longThe Y coordinate of the mouse pointer in local (DOM content) coordinates.
button {{readonlyInline}}unsigned shortThe button number that was pressed when the mouse event was fired: Left button=0, middle button=1 (if present), right button=2. For mice configured for left handed use in which the button actions are reversed the values are instead read from right to left.
buttons {{readonlyInline}}unsigned shortThe buttons being pressed when the mouse event was fired: Left button=1, Right button=2, Middle (wheel) button=4, 4th button (typically, "Browser Back" button)=8, 5th button (typically, "Browser Forward" button)=16. If two or more buttons are pressed, returns the logical sum of the values. E.g., if Left button and Right button are pressed, returns 3 (=1 | 2). More info.
mozPressure {{readonlyInline}}floatThe amount of pressure applied to a touch or tabdevice when generating the event; this value ranges between 0.0 (minimum pressure) and 1.0 (maximum pressure).
ctrlKey {{readonlyInline}}booleantrue if the control key was down when the event was fired. false otherwise.
shiftKey {{readonlyInline}}booleantrue if the shift key was down when the event was fired. false otherwise.
altKey {{readonlyInline}}booleantrue if the alt key was down when the event was fired. false otherwise.
metaKey {{readonlyInline}}booleantrue if the meta key was down when the event was fired. false otherwise.
+ +

Examples

+ +

The mouseover documentation has an example illustrating the difference between mouseover and mouseenter.

+ +

The following example illustrates how to use mouseover to simulate the principle of event delegation for the mouseenter event.

+ +
<ul id="test">
+  <li>
+    <ul class="enter-sensitive">
+      <li>item 1-1</li>
+      <li>item 1-2</li>
+    </ul>
+  </li>
+  <li>
+    <ul class="enter-sensitive">
+      <li>item 2-1</li>
+      <li>item 2-2</li>
+    </ul>
+  </li>
+</ul>
+
+<script>
+  var delegationSelector = ".enter-sensitive";
+
+  document.getElementById("test").addEventListener("mouseover", function( event ) {
+    var target = event.target,
+        related = event.relatedTarget,
+        match;
+
+    // search for a parent node matching the delegation selector
+    while ( target && target != document && !( match = matches( target, delegationSelector ) ) ) {
+        target = target.parentNode;
+    }
+
+    // exit if no matching node has been found
+    if ( !match ) { return; }
+
+    // loop through the parent of the related target to make sure that it's not a child of the target
+    while ( related && related != target && related != document ) {
+        related = related.parentNode;
+    }
+
+    // exit if this is the case
+    if ( related == target ) { return; }
+
+    // the "delegated mouseenter" handler can now be executed
+    // change the color of the text
+    target.style.color = "orange";
+    // reset the color after a small amount of time
+    setTimeout(function() {
+        target.style.color = "";
+    }, 500);
+
+
+  }, false);
+
+
+  // function used to check if a DOM element matches a given selector
+  // the following code can be replaced by this IE8 compatible function: https://gist.github.com/2851541
+  function matches( elem, selector ){
+    // the matchesSelector is prefixed in most (if not all) browsers
+    return elem.matchesSelector( selector );
+  };
+</script>
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support30[1]{{CompatVersionUnknown}}10[2]5.5{{CompatVersionUnknown}}
+ {{CompatNo}} 15.0
+ 17.0
7[3]
On disabled form elements{{CompatNo}}{{CompatNo}}{{CompatGeckoDesktop("44.0")}}[4]{{CompatNo}}{{CompatNo}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
On disabled form elements{{CompatUnknown}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Implemented in bug 236215.

+ +

[2] Implemented in {{bug("432698")}}.

+ +

[3] Safari 7 fires the event in many situations where it's not allowed to, making the whole event useless. See bug 470258 for the description of the bug (it existed in old Chrome versions as well). Safari 8 has correct behavior

+ +

[4] Implemented in {{bug("218093")}}.

+ +

See also

+ + diff --git a/files/pt-br/web/api/element/mouseover_event/index.html b/files/pt-br/web/api/element/mouseover_event/index.html new file mode 100644 index 0000000000..f4a5c56a9e --- /dev/null +++ b/files/pt-br/web/api/element/mouseover_event/index.html @@ -0,0 +1,262 @@ +--- +title: mouseover +slug: Web/API/Element/mouseover_event +translation_of: Web/API/Element/mouseover_event +--- +

O evento mouseover é acionado quando um dispositivo ponteiro é movido para o elemento que esteja escutando ou para um de seus filhos.

+ +

Informações Gerais

+ +
+
Especificação
+
DOM L3
+
Interface
+
{{domxref("MouseEvent")}}
+
Bubbles
+
Sim
+
Cancelable
+
Sim
+
Alvo
+
Element
+
Ação Padrão
+
None
+
+ +

Propriedades

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
target {{readonlyInline}}{{domxref("EventTarget")}}O evento alvo(o mais alto alvo na arvore do DOM).
type {{readonlyInline}}{{domxref("DOMString")}}The type of event.
bubbles {{readonlyInline}}BooleanWhether the event normally bubbles or not
cancelable {{readonlyInline}}BooleanWhether the event is cancellable or not
view {{readonlyInline}}{{domxref("WindowProxy")}}{{domxref("document.defaultView")}} (window of the document)
detail {{readonlyInline}}long (float)0.
currentTarget {{readonlyInline}}{{domxref("EventTarget")}}The node that had the event listener attached.
relatedTarget {{readonlyInline}}{{domxref("EventTarget")}}For mouseover, mouseout, mouseenter and mouseleave events: the target of the complementary event (the mouseleave target in the case of a mouseenter event). null otherwise.
screenX {{readonlyInline}}longThe X coordinate of the mouse pointer in global (screen) coordinates.
screenY {{readonlyInline}}longThe Y coordinate of the mouse pointer in global (screen) coordinates.
clientX {{readonlyInline}}longThe X coordinate of the mouse pointer in local (DOM content) coordinates.
clientY {{readonlyInline}}longThe Y coordinate of the mouse pointer in local (DOM content) coordinates.
button {{readonlyInline}}unsigned shortThis is always 0 as no button presses trigger this event (mouse movement does).
buttons {{readonlyInline}}unsigned shortThe buttons depressed when the mouse event was fired: Left button=1, Right button=2, Middle (wheel) button=4, 4th button (typically, "Browser Back" button)=8, 5th button (typically, "Browser Forward" button)=16. If two or more buttons are depressed, returns the logical sum of the values. E.g., if Left button and Right button are depressed, returns 3 (=1 | 2). More info.
mozPressure {{readonlyInline}}floatThe amount of pressure applied to a touch or tabdevice when generating the event; this value ranges between 0.0 (minimum pressure) and 1.0 (maximum pressure).
ctrlKey {{readonlyInline}}booleantrue if the control key was down when the event was fired. false otherwise.
shiftKey {{readonlyInline}}booleantrue if the shift key was down when the event was fired. false otherwise.
altKey {{readonlyInline}}booleantrue if the alt key was down when the event was fired. false otherwise.
metaKey {{readonlyInline}}booleantrue if the meta key was down when the event was fired. false otherwise.
+ +

Example

+ +

The following example illustrates the difference between mouseover and mouseenter events.

+ +
<ul id="test">
+  <li>item 1</li>
+  <li>item 2</li>
+  <li>item 3</li>
+</ul>
+
+<script>
+  var test = document.getElementById("test");
+
+
+  // this handler will be executed only once when the cursor moves over the unordered list
+  test.addEventListener("mouseenter", function( event ) {
+    // highlight the mouseenter target
+    event.target.style.color = "purple";
+
+    // reset the color after a short delay
+    setTimeout(function() {
+      event.target.style.color = "";
+    }, 500);
+  }, false);
+
+
+  // this handler will be executed every time the cursor is moved over a different list item
+  test.addEventListener("mouseover", function( event ) {
+    // highlight the mouseover target
+    event.target.style.color = "orange";
+
+    // reset the color after a short delay
+    setTimeout(function() {
+      event.target.style.color = "";
+    }, 500);
+  }, false);
+</script>
+
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerEdgeOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
On disabled form elements{{CompatVersionUnknown}}[1]{{CompatGeckoDesktop("44.0")}}[2]{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown}}[1]{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
On disabled form elements{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Only works for {{HTMLElement("textarea")}} elements and some {{HTMLElement("input")}} element types.

+ +

[2] Implemented in {{bug("218093")}}.

+ +

See also

+ + diff --git a/files/pt-br/web/api/element/name/index.html b/files/pt-br/web/api/element/name/index.html new file mode 100644 index 0000000000..d91ce0aa28 --- /dev/null +++ b/files/pt-br/web/api/element/name/index.html @@ -0,0 +1,79 @@ +--- +title: Element.name +slug: Web/API/Element/name +tags: + - API + - DOM + - Element + - NeedsBrowserCompatibility + - NeedsUpdate + - Property + - Reference + - Web +translation_of: Web/API +--- +

{{ APIRef("DOM") }}

+ +

Summary

+ +

name recebe ou ajusta uma propriedade name de um objeto do DOM; ele se aplica somente aos seguintes elementos: {{ HTMLelement("a") }}, {{ HTMLelement("applet") }}, {{ HTMLelement("button") }}, {{ HTMLelement("form") }}, {{ HTMLelement("frame") }}, {{ HTMLelement("iframe") }}, {{ HTMLelement("img") }}, {{ HTMLelement("input") }}, {{ HTMLelement("map") }}, {{ HTMLelement("meta") }}, {{ HTMLelement("object") }}, {{ HTMLelement("param") }}, {{ HTMLelement("select") }} e {{ HTMLelement("textarea") }}.

+ +
+

Nota: A propriedade name não existe para outros elementos; diferente de tagName e nodeName, ela não é uma propriedade das interfaces {{domxref("Node")}}, {{domxref("Element")}} ou {{domxref("HTMLElement")}}.

+
+ +

name pode ser usada no método {{ domxref("document.getElementsByName()") }}, em um form ou com uma coleção de elementos de formulário. Ela pode retornar um único elemento ou uma coleção quando usada com um formulário ou elementos de coleção.

+ +

Sintaxe

+ +
HTMLElement.name = string;
+var elName = HTMLElement.name;
+
+var fControl = HTMLFormElement.elementName;
+var controlCollection = HTMLFormElement.elements.elementName;
+
+ +

Exemplo

+ +
<form action="" name="formA">
+  <input type="text" value="foo">
+</form>
+
+<script type="text/javascript">
+
+  // Recebe uma referência ao primeiro elemento no formulário
+  var formElement = document.forms['formA'].elements[0];
+
+  // Fornece um name a ele
+  formElement.name = 'inputA';
+
+  // Exibe o valor do input
+  alert(document.forms['formA'].elements['inputA'].value);
+
+</script>
+
+ +

Notas

+ +

No Internet Explorer (IE), não é possível ajustar ou modificar a propriedade name de objetos do DOM criados com {{ domxref("document.createElement()") }}.

+ +

Especificação

+ +

Especificação W3C DOM 2 HTML:

+ + diff --git a/files/pt-br/web/api/element/outerhtml/index.html b/files/pt-br/web/api/element/outerhtml/index.html new file mode 100644 index 0000000000..1cdfa0826d --- /dev/null +++ b/files/pt-br/web/api/element/outerhtml/index.html @@ -0,0 +1,144 @@ +--- +title: Element.outerHTML +slug: Web/API/Element/outerHTML +translation_of: Web/API/Element/outerHTML +--- +

{{APIRef("DOM")}}

+ +

Sumário

+ +

O atributo outerHTML da estrutura DOM(Document object model) obtem  um fragmento serializado de código HTML descrevendo o elemento incluindo seus descendentes. É possível substituir o elemento em questão com nós obtidos através da análise de uma string.

+ +

Sintaxe

+ +

var conteudo = elemento.outerHTML;

+ +

Na atribuição, conteudo armazena o fragmento de código HTML que descreve o elemento e seus descentes.

+ +
elemento.outerHTML = conteudo;
+
+ +

Atribui a elemento  os nós obtidos pela análise da  string conteudo, tendo nó pai de elemento como nó de contexto o para o algoritmo de análise do fragmento de código HTML.

+ +

Exemplos

+ +

Obtendo o valor da propriedade outerHtml de um elemento :

+ +
// HTML:
+// <div id="d"><p>Conteúdo</p><p>Parágrafo</p></div>
+
+d = document.getElementById("d");
+dump(d.outerHTML);
+
+// A string '<div id="d"><p>Conteúdo</p><p>Parágrafo</p></div>'
+// é mostrada na janela do console.
+
+ +

Substituindo um nó atribuindo- lhe a propriedade outerHTML

+ +
// HTML:
+// <div id="container"><div id="d">Isto é uma div.</div></div>
+
+container = document.getElementById("container");
+d = document.getElementById("d");
+console.log(container.firstChild.nodeName); // mostra "DIV"
+
+d.outerHTML = "<p>Este parágrafo substitui a div original</p>";
+console.log(container.firstChild.nodeName); // mostra "P"
+
+// A div #d não faz mais parte da estrutura do documento,
+// O novo parágrafo a substituiu.
+
+ +

Notas

+ +

Se o elemento não tiver um nó pai, ou seja se o nó é a raiz do documento, tentar alterar sua propriedade outerHTML irá lançar um  DOMException com o código de erro NO_MODIFICATION_ALLOWED_ERR. Por exemplo:

+ +
document.documentElement.outerHTML = "test";  // Irá lançar uma DOMException
+
+ +

inclusive, quando o elemento for substituído na estrutura do documento, a variável a qual a propriedade outerHTML foi atribuída ainda irá conter uma referência para o elemento original.

+ +
var p = document.getElementsByTagName("p")[0];
+console.log(p.nodeName); // mostra: "P"
+p.outerHTML = "<div>Esta div substituiu o parágrafo.</div>";
+console.log(p.nodeName); // ainda contém "P";
+
+ +

Especificação

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM Parsing', '#outerhtml', 'Element.outerHTML')}}{{ Spec2('DOM Parsing') }} 
+ +

Compatibilidade com os navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Suporte básico{{ CompatGeckoDesktop("11") }}0.24.071.3
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
+

Suporte básico

+
{{ CompatVersionUnknown() }}{{ CompatGeckoMobile("11") }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/element/queryselector/index.html b/files/pt-br/web/api/element/queryselector/index.html new file mode 100644 index 0000000000..cbd41e09ff --- /dev/null +++ b/files/pt-br/web/api/element/queryselector/index.html @@ -0,0 +1,94 @@ +--- +title: Element.querySelector() +slug: Web/API/Element/querySelector +tags: + - API + - DOM + - Elemento + - Referencia +translation_of: Web/API/Element/querySelector +--- +
{{APIRef("DOM")}}
+ +

Retorna o primeiro elemento descendente do elemento em que a função foi invocada e que corresponde aos seletores especificado. 

+ +

Sintaxe

+ +
elemento = elementoBase.querySelector(seletores);
+
+ + + +

Exemplo

+ +

Neste exemplo é retornado o primeiro elemento style que, ou não tem nenhum atributo type, ou tem o atributo type igual a  text/css:

+ +
var el = document.body.querySelector("style[type='text/css'], style:not([type])");
+
+ +

Notas

+ +

Retorna null se nenhum elemento for encontrado; caso contrário retorna o primeiro elemento; 

+ +

Lança uma exceção SYNTAX_ERR se o grupo de seletores é inválido.

+ +

querySelector() foi introduzido em WebApps API.

+ +

O argumento de string do querySelector deve seguir a sintaxe CSS. Veja exemplos concretos em {{domxref("document.querySelector")}}

+ +

Compatibilidade de Browsers

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
BrowserSuporteNotas
Internet Explorer8(IE8) apenas selectores CSS 2.1
Firefox (Gecko)3.5 (1.9.1) 
Opera10 
Chrome1 
Safari (webkit)3.2 (525.3)webk.it/16587
+ +

Especificação

+ + + +

Veja Também

+ + diff --git a/files/pt-br/web/api/element/queryselectorall/index.html b/files/pt-br/web/api/element/queryselectorall/index.html new file mode 100644 index 0000000000..92f6e93506 --- /dev/null +++ b/files/pt-br/web/api/element/queryselectorall/index.html @@ -0,0 +1,118 @@ +--- +title: Element.querySelectorAll() +slug: Web/API/Element/querySelectorAll +translation_of: Web/API/Element/querySelectorAll +--- +
{{APIRef("DOM")}}
+ +

Sumário

+ +

Retorna uma  NodeList de todos os elementos descendentes do elemento que foi invocado que sejam compatíveis com o grupo de seletores CSS especificados.

+ +

Sintaxe

+ +
elementList = baseElement.querySelectorAll(selectors);
+
+ +

Onde

+ + + +

Exemplos

+ +

Este exemplo retorna uma lista de todos os elementos p no corpo do HTML:

+ +
var matches = document.body.querySelectorAll('p');
+
+ +

Este exemplo retorna uma lista de elementos p que estejam contidos em outro elemento, o qual é uma div que tem a classe 'highlighted':

+ +

 

+ +
var el = document.querySelector('#test');
+var matches = el.querySelectorAll('div.highlighted > p'); 
+ +

Este exemplo retorna uma lista de elementos iframe que contenham um atributo data 'src':

+ +
var matches = el.querySelectorAll('iframe[data-src]');
+
+ +

Notas

+ +

Joga uma excessão SYNTAX_ERR se o grupo especificado de seletores for inválido.

+ +

querySelectorAll() foi introduzida na WebApps API.

+ +

A string passada como argumento para querySelectorAll deve seguir a sintaxe do CSS. veja {{domxref("document.querySelector")}} para um exemplo concreto.

+ +

Lembre-se que o valor retornado é uma NodeList, então não é recomendado o uso de recursões for...in, nem de nenhum método de array. Se realmente houver a necessidade de usar métodos de uma array, então o NodeList deve ser convertido em uma array antes de ser usado.

+ +

Compatibilidade com Browsers

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico1{{CompatGeckoDesktop("1.9.1")}}8103.2 (525.3)
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatGeckoMobile("1.9.1")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
+
+ +

 

+ +

Especificações

+ + + +

Veja também

+ + diff --git a/files/pt-br/web/api/element/removeattribute/index.html b/files/pt-br/web/api/element/removeattribute/index.html new file mode 100644 index 0000000000..c160dee957 --- /dev/null +++ b/files/pt-br/web/api/element/removeattribute/index.html @@ -0,0 +1,36 @@ +--- +title: Element.removeAttribute() +slug: Web/API/Element/removeAttribute +translation_of: Web/API/Element/removeAttribute +--- +

{{ APIRef("DOM") }}

+ +

removeAttribute remove um atributo de um elemento específico.

+ +

Sintaxe

+ +
element.removeAttribute(attrName);
+
+ + + +

Exemplo

+ +
// <div id="div1" align="left" width="200px">
+document.getElementById("div1").removeAttribute("align");
+// agora: <div id="div1" width="200px">
+
+ +

Observação

+ +

Você deve usar removeAttribute ao invés de atribuir null ao atributo usando setAttribute.

+ +

Tentar remover um atributo que não existe no elemento não fará que uma exceção seja lançada.

+ +

{{ DOMAttributeMethods() }}

+ +

Especificação

+ +

DOM Level 2 Core: removeAttribute (introduzido no DOM Level 1 Core)

diff --git a/files/pt-br/web/api/element/scrollintoview/index.html b/files/pt-br/web/api/element/scrollintoview/index.html new file mode 100644 index 0000000000..28714a4b1e --- /dev/null +++ b/files/pt-br/web/api/element/scrollintoview/index.html @@ -0,0 +1,89 @@ +--- +title: Element.scrollIntoView() +slug: Web/API/Element/scrollIntoView +tags: + - API + - CSSOM Views + - DOM + - Elemento + - Experimental + - Referencia + - Rolagem + - View + - metodo + - scrollIntoView +translation_of: Web/API/Element/scrollIntoView +--- +
{{ APIRef("DOM")}}{{SeeCompatTable}}
+ +

O método Element.scrollIntoView() move o elemento ao qual é aplicado para a área visível da janela do navegador.

+ +

Sintaxe

+ +
element.scrollIntoView(); // Equivalente a element.scrollIntoView(true)
+element.scrollIntoView(alignToTop); // Argumentos booleanos
+element.scrollIntoView(scrollIntoViewOptions); // argumento Objeto
+
+ +

Parâmetros

+ +
+
alignToTop {{optional_inline}}
+
É um valor {{jsxref("Boolean")}}: +
    +
  • Se true, a parte superior do elemento ficará alinhada com o topo da área visível do elemento-pai. Correponde a scrollIntoViewOptions: {block: "start", inline: "nearest"}. Este é o valor default.
  • +
  • Se false, a parte inferior do elemento ficará alinhada com o fundo da área visível do elemento-pai. Corresponde a scrollIntoViewOptions: {block: "end", inline: "nearest"}
  • +
+
+
scrollIntoViewOptions {{optional_inline}}
+
Um booleano ou um objeto com as seguintes opções:
+
+
{
+  behavior: "auto"  | "instant" | "smooth",
+  block:    "start" | "center" | "end" | "nearest",
+  inline:   "start" | "center" | "end" | "nearest"
+}
+
+
Caso seja um valor booleano, true corresponde a {block: "start"} e false a {block: "end"}.
+
+ +

Exemplo

+ +
var element = document.getElementById("box");
+
+element.scrollIntoView();
+element.scrollIntoView(false);
+element.scrollIntoView({block: "end"});
+element.scrollIntoView({block: "end", behavior: "smooth"});
+
+ +

Observações

+ +

O elemento poderá não ser movido completamento ao topo ou ao fundo dependendo de sua composição com outros elementos.

+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName("CSSOM View", "#dom-element-scrollintoview", "Element.scrollIntoView()")}}{{Spec2("CSSOM View")}}Definição inicial
+ +

Compatibilidade com navegadores

+ +

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

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/element/scrollleft/index.html b/files/pt-br/web/api/element/scrollleft/index.html new file mode 100644 index 0000000000..30df424288 --- /dev/null +++ b/files/pt-br/web/api/element/scrollleft/index.html @@ -0,0 +1,83 @@ +--- +title: Element.scrollLeft +slug: Web/API/Element/scrollLeft +translation_of: Web/API/Element/scrollLeft +--- +

{{ APIRef("DOM") }}

+ +

A propriedade Element.scrollLeft obtem, ou define o número de pixels do contéudo de um elemento que é rolado para a esquerda.

+ +

Note que se os {{cssxref("direction")}} do elemento do elemento é rtl (direita-para-esquerda) então scrollLeft é 0 quando a barra de rolagem está na posição mais à direita (o início do conteúdo rolado) e então, fica cada vez mais negativa à medida que se desloca em direção ao fim do conteúdo.

+ +

Sintaxe

+ +
// Obtem o número de pixels rolado
+var sLeft = element.scrollLeft;
+
+ +

sLeft é um inteiro representando o número de pixels do elemento que foi movido para a esquerda.

+ +
// Define o número de pixels rolado
+element.scrollLeft = 10;
+
+ +

scrollLeft pode ser definido para qualquer valor inteiro, entretanto:

+ + + +

Exemplo

+ +
<!DOCTYPE html>
+<html>
+<head>
+    <meta charset="utf-8">
+    <style>
+        #container {
+            border: 1px solid #ccc; height: 100px; overflow: scroll; width: 100px;
+        }
+        #content {
+            background-color: #ccc; width: 250px;
+        }
+    </style>
+    <script>
+        document.addEventListener('DOMContentLoaded', function () {
+            var button = document.getElementById('slide');
+            button.onclick = function () {
+                document.getElementById('container').scrollLeft += 20;
+            };
+        }, false);
+    </script>
+</head>
+<body>
+    <div id="container">
+        <div id="content">Lorem ipsum dolor sit amet.</div>
+    </div>
+    <button id="slide" type="button">Slide</button>
+</body>
+</html>
+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçõesStatusComentário
{{SpecName('CSSOM View', '#dom-element-scrollleft', 'scrollLeft')}}{{Spec2("CSSOM View")}} 
+ +

Referências

+ +

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

diff --git a/files/pt-br/web/api/element/scrolltop/index.html b/files/pt-br/web/api/element/scrolltop/index.html new file mode 100644 index 0000000000..f8f7dc4cd6 --- /dev/null +++ b/files/pt-br/web/api/element/scrolltop/index.html @@ -0,0 +1,69 @@ +--- +title: Element.scrollTop +slug: Web/API/Element/scrollTop +translation_of: Web/API/Element/scrollTop +--- +

{{ APIRef("DOM") }}

+ +

A propriedade Element.scrollTop obtém ou define o número de pixels quando o conteúdo de um elemento é rolado para baixo. O ScrollTop de um elemento é uma medida da distância do topo de um elemento para o seu conteúdo superior visível. Quando um conteúdo de elemento não gera uma barra de rolagem vertical, então o seu valor será padronizado scrollTop = 0.

+ +

Sintaxe

+ +
// Obtém o número de pixels rolados
+var intElemScrollTop = element.scrollTop;
+
+ +

Depois de executar este código, intElemScrollTop é um número inteiro correspondente ao número de pixels que o {{domxref ("elemento")}}  conteúdo foi rolado para cima.

+ +
// Define o número de pixels rolados
+element.scrollTop = intValue;
+
+ +

scrollTop pode ser definido como qualquer valor inteiro, com algumas ressalvas:

+ + + +

Exemplo

+ +
+
+

padding-top

+ +

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

+ +

Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

+ +

padding-bottom

+
+Left Top Right Bottom margin-top margin-bottom border-top border-bottom
+ +

Image:scrollTop.png

+ +

Especificações

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSSOM View', '#dom-element-scrolltop', 'scrollTop')}}{{Spec2("CSSOM View")}} 
+ +

Referências

+ + diff --git a/files/pt-br/web/api/element/scrollwidth/index.html b/files/pt-br/web/api/element/scrollwidth/index.html new file mode 100644 index 0000000000..9f0c3009b5 --- /dev/null +++ b/files/pt-br/web/api/element/scrollwidth/index.html @@ -0,0 +1,116 @@ +--- +title: Element.scrollWidth +slug: Web/API/Element/scrollWidth +translation_of: Web/API/Element/scrollWidth +--- +
{{ APIRef("DOM") }}
+ +

A propriedade de somente leitura Element.scrollWidth retorna a largura em pixels do conteúdo de um elemento ou a largura do elemento em si, o que for maior. Se o elemento for mais amplo do que a área de conteúdo (por exemplo, se houver barras de rolagem para percorrer o conteúdo), o scrollWidth é maior do que o clientWidth.

+ +
+

Esta propriedade irá arredondar o valor para um número inteiro. Se você precisar de um valor fracionário, use {{ domxref("element.getBoundingClientRect()") }}.

+
+ +

Syntaxe

+ +
var xScrollWidth = element.scrollWidth;
+ +

xScrollWidth é a largura do conteúdo do elemento em pixels.

+ +

Examplo

+ +
<!DOCTYPE html>
+<html>
+<head>
+    <title>Example</title>
+    <style>
+        div {
+            overflow: hidden;
+            white-space: nowrap;
+            text-overflow: ellipsis;
+        }
+
+        #aDiv {
+            width: 100px;
+        }
+
+        button {
+            margin-bottom: 2em;
+        }
+    </style>
+</head>
+
+<body>
+    <div id="aDiv">
+        FooBar-FooBar-FooBar-FooBar
+    </div>
+    <button id="aButton">
+        Check for overflow
+    </button>
+
+    <div id="anotherDiv">
+        FooBar-FooBar-FooBar-FooBar
+    </div>
+    <button id="anotherButton">
+        Check for overflow
+    </button>
+</body>
+<script>
+    var buttonOne = document.getElementById('aButton'),
+    buttonTwo = document.getElementById('anotherButton'),
+    divOne = document.getElementById('aDiv'),
+    divTwo = document.getElementById('anotherDiv');
+
+    //check to determine if an overflow is happening
+    function isOverflowing(element) {
+        return (element.scrollWidth > element.offsetWidth);
+    }
+
+    function alertOverflow(element) {
+        if (isOverflowing(element)) {
+            alert('Contents are overflowing the container.');
+        } else {
+            alert('No overflows!');
+        }
+    }
+
+    buttonOne.addEventListener('click', function() {
+        alertOverflow(divOne);
+    });
+
+    buttonTwo.addEventListener('click', function() {
+        alertOverflow(divTwo);
+    });
+</script>
+</html>
+
+
+ +

Especificação

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName("CSSOM View", "#dom-element-scrollwidth", "Element.scrollWidth")}}{{Spec2("CSSOM View")}}Definição inicial
+ +

Referências

+ +

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

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/element/setattribute/index.html b/files/pt-br/web/api/element/setattribute/index.html new file mode 100644 index 0000000000..0a3642be64 --- /dev/null +++ b/files/pt-br/web/api/element/setattribute/index.html @@ -0,0 +1,58 @@ +--- +title: Element.setAttribute() +slug: Web/API/Element/setAttribute +tags: + - Elemento + - IPA + - MOD + - Referencia + - metodo +translation_of: Web/API/Element/setAttribute +--- +

{{APIRef("DOM")}}

+ +

Adiciona um novo atributo ou modifica o valor de um atributo existente num elemento específico.

+ +

Sintaxe

+ +
element.setAttribute(name, value);
+
+ + + +

Exemplo

+ +

No seguinte exemplo, setAttribute() é usado para definir o atributo {{htmlattrxref("disabled")}} em {{htmlelement("button")}}, desabilitado-o.

+ +
<button>Hello World</button>
+ +
var b = document.querySelector("button");
+
+b.setAttribute("disabled", "disabled");
+
+ +

{{ EmbedLiveSample('Example', '300', '50', '', 'Web/API/Element/setAttribute') }}

+ +

Notas

+ +

Quando chamado em um documento HTML, setAttribute lower-cases its attribute name argument.

+ +

Se um atributo especificado já existe, então o valor do atributo é mudado para o valor passado para a função. Se não existe, então o atributo é criado.

+ +

Apesar de getAttribute() retornar null para atributos ausentes, você precisa usar removeAttribute() ao invés de elt.setAttribute(attr, null) para remover o atributo. Este último forçará o valor null para a string "null", o que não é provavelmente o que você quer.

+ +

Usar setAttribute() para modificar certos atributos, mais notavelmente valor em XUL, funciona inconsistentemente, como atributos específicos de valor padrão. Para acessar ou modificar os valores atuais, você deve usar as propriedades. Por exemplo, use elt.value ao invés de elt.setAttribute('value', val).

+ +

Para definir um atributo que não leva valor, assim como o atributo autoplay de um elemento {{HTMLElement("audio")}}, use null ou um valor vazio. Por exemplo: elt.setAttribute('autoplay', '')

+ +
{{DOMAttributeMethods}}
+ +

Especificação

+ + diff --git a/files/pt-br/web/api/element/setattributens/index.html b/files/pt-br/web/api/element/setattributens/index.html new file mode 100644 index 0000000000..d4837965a7 --- /dev/null +++ b/files/pt-br/web/api/element/setattributens/index.html @@ -0,0 +1,33 @@ +--- +title: Element.setAttributeNS() +slug: Web/API/Element/setAttributeNS +translation_of: Web/API/Element/setAttributeNS +--- +

{{ APIRef("DOM") }}

+ +

setAttributeNS adiciona um novo atributo ou modifica o valor de um atributo com um namespace e um nome.

+ +

Syntax

+ +
element.setAttributeNS(namespace,name,value)
+
+ + + +

Exemplo

+ +
var d = document.getElementById("d1");
+d.setAttributeNS("http://www.mozilla.org/ns/specialspace", "align", "center");
+
+ +

Notas

+ +

{{ DOMAttributeMethods() }}

+ +

Especificação

+ +

DOM Level 2 Core: setAttributeNS

diff --git a/files/pt-br/web/api/element/tagname/index.html b/files/pt-br/web/api/element/tagname/index.html new file mode 100644 index 0000000000..c0345f4763 --- /dev/null +++ b/files/pt-br/web/api/element/tagname/index.html @@ -0,0 +1,119 @@ +--- +title: Element.tagName +slug: Web/API/Element/tagName +tags: + - API + - DOM + - Gecko + - PrecisaCompatibilidadeBrowser + - Propriedade + - Referência DOM +translation_of: Web/API/Element/tagName +--- +

{{ApiRef("DOM")}}

+ +

Retorna o nome do elemento.

+ +

Sintaxe

+ +
nomeDoElemento = element.tagName;
+
+ + + +

Notas

+ +

Em XML (e linguagens baseadas, como XHTML), tagName conserva o case  (caixa alta/baixa) da tag. Nos elementos HTML da árvore do DOM marcados como documentos HTML, tagName retorna o nome do elemento em uppercase (caixa alta). O valor de tagName é o mesmo que o nodeName

+ +

Exemplo

+ +

conteúdo HTML

+ +
<span id="exemplo">Descrição do exemplo...</span>
+
+ +

conteúdo JavaScript

+ +
var span = document.getElementById("exemplo");
+console.log(span.tagName);
+
+ +

Em XHTML (ou qualquer outro formato XML), "span" será a saída. Em HTML, "SPAN" será a saída.

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName("DOM3 Core", "core.html#ID-104682815", "Element.tagName")}}{{Spec2("DOM3 Core")}}No change
{{SpecName("DOM2 Core", "core.html#ID-104682815", "Element.tagName")}}{{Spec2("DOM2 Core")}}Initial definition
+ +

Compatibilidade de browser

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
diff --git a/files/pt-br/web/api/element/touchstart_event/index.html b/files/pt-br/web/api/element/touchstart_event/index.html new file mode 100644 index 0000000000..ae2649f49c --- /dev/null +++ b/files/pt-br/web/api/element/touchstart_event/index.html @@ -0,0 +1,174 @@ +--- +title: touchstart +slug: Web/API/Element/touchstart_event +tags: + - Event + - Evento Toque + - Toque + - TouchEvent +translation_of: Web/API/Element/touchstart_event +--- +

O evento touchstart é acionado quando o ponteiro de toque(dedo ou caneta) é aplicado sobre à superfície de toque da tela(toque sobre a tela no elemento alvo).

+ +

Info Geral

+ +
+
Especificações
+
Touch Events
+
Interface
+
{{domxref("TouchEvent")}}
+
Bubbles
+
Sim
+
Cancelável
+
Sim
+
Alvo
+
Documento, Elemento
+
Ação Padrão
+
undefined (indefinido)
+
+ +

Propriedades

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
target {{readonlyInline}}EventTargetThe event target (the topmost target in the DOM tree).
type {{readonlyInline}}DOMStringThe type of event.
bubbles {{readonlyInline}}BooleanWhether the event normally bubbles or not.
cancelable {{readonlyInline}}BooleanWhether the event is cancellable or not.
view {{readonlyInline}}WindowProxydocument.defaultView (window of the document)
detail {{readonlyInline}}long (float)0.
touches {{readonlyInline}}TouchListA list of Touches for every point of contact currently touching the surface.
targetTouches {{readonlyInline}}TouchListA list of Touches for every point of contact that is touching the surface and started on the element that is the target of the current event.
changedTouches {{readonlyInline}}TouchListA list of Touches for every point of contact which contributed to the event.
+ For the touchstart event this must be a list of the touch points that just became active with the current event. For the touchmove event this must be a list of the touch points that have moved since the last event. For the touchend and touchcancel events this must be a list of the touch points that have just been removed from the surface.
ctrlKey {{readonlyInline}}booleantrue if the control key was down when the event was fired. false otherwise.
shiftKey {{readonlyInline}}booleantrue if the shift key was down when the event was fired. false otherwise.
altKey {{readonlyInline}}booleantrue if the alt key was down when the event was fired. false otherwise.
metaKey {{readonlyInline}}booleantrue if the meta key was down when the event was fired. false otherwise.
+ +

Exemplos

+ +

Os códigos de exemplos para este evento estão disponíveis nesta página dedicada: Touch events.

+ +

Compatibilidade de Navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico{{CompatChrome("22.0")}}{{CompatGeckoDesktop("18.0")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidAndroid WebviewChrome para AndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("6.0")}}{{CompatVersionUnknown}}11{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Eventos Relacionados

+ + diff --git a/files/pt-br/web/api/encoding_api/index.html b/files/pt-br/web/api/encoding_api/index.html new file mode 100644 index 0000000000..543a842cdc --- /dev/null +++ b/files/pt-br/web/api/encoding_api/index.html @@ -0,0 +1,55 @@ +--- +title: Encoding API +slug: Web/API/Encoding_API +translation_of: Web/API/Encoding_API +--- +

{{DefaultAPISidebar("Encoding API")}}{{SeeCompatTable}}

+ +

Encoding API providência uma mecânismo para tratar textos em vários tipos de {{Glossary("character encoding", "encode de caracteres")}}, incluindo encodes legados non-{{Glossary("UTF-8")}}

+ +

A API provém de quatro interfaces: {{domxref("TextDecoder")}}, {{domxref("TextEncoder")}}, {{domxref("TextDecoderStream")}} e {{domxref("TextEncoderStream")}}.

+ +

Interfaces

+ +
+ +
+ +

Tutoriais & ferramentas

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Encoding")}}{{Spec2("Encoding")}}Definição inicial.
+ +

Compatibilidade dos navegadores

+ + + +

TextDecoder

+ +

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

+ +

TextEncoder

+ +

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

diff --git a/files/pt-br/web/api/event/comparativo_entre_event_targets/index.html b/files/pt-br/web/api/event/comparativo_entre_event_targets/index.html new file mode 100644 index 0000000000..e9b2004719 --- /dev/null +++ b/files/pt-br/web/api/event/comparativo_entre_event_targets/index.html @@ -0,0 +1,167 @@ +--- +title: Comparativo entre Event Targets +slug: Web/API/Event/Comparativo_entre_Event_Targets +tags: + - DOM + - Event + - event target +translation_of: Web/API/Event/Comparison_of_Event_Targets +--- +
{{ ApiRef() }}
+ +

Event targets

+ +

É facil se confundir sobre o tipo de alvo (target) que deseja-se examinar ao criar um manipulador de eventos (event handler). Este artigo se propõe a esclarecer o uso da propriedade target.

+ +

Há 5 tipos de targets a se considerar:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropriedadeDefinido emObjetivo
event.targetDOM Event Interface +

O elemento do DOM à esquerda da chamada que disparou este evento, por exemplo:

+ +
+element.dispatchEvent(event)
+
+
event.currentTargetDOM Event InterfaceO EventTarget do qual o EventListeners está sendo atualmente processado. Logo que a captura e a subida do evento ocorre a mudança deste valor.
event.relatedTargetDOM MouseEvent InterfaceIdentifica um alvo secundário para o evento.
event.explicitOriginalTarget{{ Source("/dom/public/idl/events/nsIDOMNSEvent.idl", "nsIDOMNSEvent.idl") }}{{ Non-standard_inline() }} Se o evento foi redirecionado por alguma outra razão senão o cruzamento de uma fronteira anônima, este evento será colocado no alvo antes que o redirecionamento ocorra. por exemplo, eventos do mouse são redirecionados à seus elementos pais quando acontecem sobre nós de texto ({{ Bug("185889") }}), e neste caso .target mostrará o nó pai e .explicitOriginalTarget mostrará o nó texto. Diferente de .originalTarget, .explicitOriginalTarget nunca irá conter um conteúdo anônimo.
event.originalTarget{{ Source("/dom/public/idl/events/nsIDOMNSEvent.idl", "nsIDOMNSEvent.idl") }}{{ Non-standard_inline() }} O alvo original do evento, antes de qualquer redirecionamento. Veja Anonymous Content#Event_Flow_and_Targeting para mais detalhes.
+ +

Uso de explicitOriginalTarget e originalTarget

+ +

TODO: Disponível apensas em navegadores Mozilla-based?

+ +

TODO: Adequado apenas para desenvolvedores de extensões?

+ +

Exemplos

+ +
<!DOCTYPE html>
+<html>
+<head>
+    <meta charset="utf-8">
+    <meta http-equiv="X-UA-Compatible" content="IE=edge">
+    <title>Comparison of Event Targets</title>
+    <style>
+        table {
+            border-collapse: collapse;
+            height: 150px;
+            width: 100%;
+        }
+        td {
+            border: 1px solid #ccc;
+            font-weight: bold;
+            padding: 5px;
+            min-height: 30px;
+        }
+        .standard {
+            background-color: #99ff99;
+        }
+        .non-standard {
+            background-color: #902D37;
+        }
+    </style>
+</head>
+<body>
+    <table>
+    <thead>
+        <tr>
+            <td class="standard">Original target dispatching the event <small>event.target</small></td>
+            <td class="standard">Target who's event listener is being processed <small>event.currentTarget</small></td>
+            <td class="standard">Identify other element (if any) involved in the event <small>event.relatedTarget</small></td>
+            <td class="non-standard">If there was a retargetting of the event for some reason <small> event.explicitOriginalTarget</small> contains the target before retargetting (never contains anonymous targets)</td>
+            <td class="non-standard">If there was a retargetting of the event for some reason <small> event.originalTarget</small> contains the target before retargetting (may contain anonymous targets)</td>
+        </tr>
+    </thead>
+    <tr>
+        <td id="target"></td>
+        <td id="currentTarget"></td>
+        <td id="relatedTarget"></td>
+        <td id="explicitOriginalTarget"></td>
+        <td id="originalTarget"></td>
+    </tr>
+</table>
+<p>Clicking on the text will show the difference between explicitOriginalTarget, originalTarget and target</p>
+<script>
+    function handleClicks(e) {
+        document.getElementById('target').innerHTML = e.target;
+        document.getElementById('currentTarget').innerHTML = e.currentTarget;
+        document.getElementById('relatedTarget').innerHTML = e.relatedTarget;
+        document.getElementById('explicitOriginalTarget').innerHTML = e.explicitOriginalTarget;
+        document.getElementById('originalTarget').innerHTML = e.originalTarget;
+    }
+
+    function handleMouseover(e) {
+        document.getElementById('target').innerHTML = e.target;
+        document.getElementById('relatedTarget').innerHTML = e.relatedTarget;
+    }
+
+    document.addEventListener('click', handleClicks, false);
+    document.addEventListener('mouseover', handleMouseover, false);
+</script>
+</body>
+</html>
+ +

Uso de target e relatedTarget

+ +

A propriedade relatedTarget do evento de mouseover mantém o nó de onde o mouse estava sobre anteriormente. Para o evento de mouseout, mantém o nó para onde o mouse se moveu.

+ + + + + + + + + + + + + + + + + + + +
Tipo de Eventoevent.targetevent.relatedTarget
mouseoverO EventTarget do qual o dispositivo apontador entrou.O EventTarget do qual o dispositivo apontador saiu.
mouseoutO EventTarget do qual o dispositivo apontador saiu.O EventTarget do qual o dispositivo apontador entrou.
+ +

TODO: Necessário descrição complemento sobre eventos de dragenter e dragexit.

+ +

Exemplo

+ +
<hbox id="outer">
+  <hbox id="inner"
+        onmouseover="dump('mouseover ' + event.relatedTarget.id + ' > ' + event.target.id + '\n');"
+        onmouseout="dump('mouseout  ' + event.target.id + ' > ' + event.relatedTarget.id + '\n');"
+        style="margin: 100px; border: 10px solid black; width: 100px; height: 100px;" />
+</hbox>
+
diff --git a/files/pt-br/web/api/event/currenttarget/index.html b/files/pt-br/web/api/event/currenttarget/index.html new file mode 100644 index 0000000000..e74a58fb61 --- /dev/null +++ b/files/pt-br/web/api/event/currenttarget/index.html @@ -0,0 +1,129 @@ +--- +title: Event.currentTarget +slug: Web/API/Event/currentTarget +tags: + - API + - CompatibilidadeEntreNavegadores + - DOM + - Gecko + - Propriedade +translation_of: Web/API/Event/currentTarget +--- +

{{APIRef("DOM")}}

+ +

Identifica o alvo atual para o evento quando o event percorre o DOM. O currentTarget sempre se refere ao elemento associado ao event handler, ao invés do event.target que identifica o elemento ao qual o evento ocorreu.

+ +

Exemplo

+ +

event.currentTarget é bom para ser usado quando nós queremos associar o mesmo event handler para vários elementos.

+ +
function hide(e){
+  e.currentTarget.style.visibility = "hidden";
+  console.log(e.currentTarget);
+  // Quando essa função é usada como um event
+  // handler: this === e.currentTarget
+}
+
+var ps = document.getElementsByTagName('p');
+
+for(var i = 0; i < ps.length; i++){
+  // console: print the clicked <p> element
+  ps[i].addEventListener('click', hide, false);
+}
+// console: print <body>
+document.body.addEventListener('click', hide, false);
+
+// Clique e faça os parágrafos desaparecerem
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName("DOM WHATWG", "#dom-event-currenttarget", "Event.currentTarget")}}{{Spec2("DOM WHATWG")}} 
{{SpecName("DOM4", "#dom-event-currenttarget", "Event.currentTarget")}}{{Spec2("DOM4")}} 
{{SpecName("DOM3 Events", "#dfn-current-event-target", "current event target")}}{{Spec2("DOM3 Events")}} 
{{SpecName("DOM2 Events", "#Events-Event-currentTarget", "Event.currentTarget")}}{{Spec2("DOM2 Events")}}Definição incial
+ +

Compatibilidade  dos navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Supote básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}[1]{{CompatVersionUnknown}}10.0
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Supote básico{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}10.0
+
+ +

[1] Do Internet Explorer 6 até o 8, o modelo do event é diferente. Event listeners estão acoplados com o {{domxref("EventTarget.attachEvent")}} método não padronizado. Neste modelo não há um equivalente para event.currentTarget e this é um objeto global. Uma solução para simular o event.currentTarget é envolver seu handler em uma função e chamando-a usando o Function.prototype.call com o elemento sendo o primeiro argumento. Desta forma, this será o valor esperado.

+ +

Veja também

+ +

Comparativo dos Event Targets

diff --git a/files/pt-br/web/api/event/defaultprevented/index.html b/files/pt-br/web/api/event/defaultprevented/index.html new file mode 100644 index 0000000000..d0407443c7 --- /dev/null +++ b/files/pt-br/web/api/event/defaultprevented/index.html @@ -0,0 +1,79 @@ +--- +title: Event.defaultPrevented +slug: Web/API/Event/defaultPrevented +translation_of: Web/API/Event/defaultPrevented +--- +

{{ ApiRef("DOM") }}

+ +

Resumo

+ +

Retorna um booleano que indica se ou não {{ domxref("event.preventDefault()") }} foi chamado no evento.

+ +
Nota: Você deve usar isso em vez de a não-padrão, método desatualizado getPreventDefault()  (ver {{ bug(691151) }}).
+ +

Sintaxe

+ +
bool = event.defaultPrevented 
+ +

Exemplo

+ +
 if (e.defaultPrevented) {
+   /* o padrão foi impedido */
+ }
+
+ +

Compatibilidade do navegador

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
RecursoChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{ CompatChrome(18) }}{{ CompatGeckoDesktop("6.0") }}{{ CompatIE(9.0) }}{{ CompatOpera(11.0) }}{{ CompatSafari("5.0") }}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{ CompatUnknown() }}{{ CompatGeckoMobile("6.0") }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatSafari(5.0) }}
+
+ +

Especificação

+ + diff --git a/files/pt-br/web/api/event/event/index.html b/files/pt-br/web/api/event/event/index.html new file mode 100644 index 0000000000..40bc836e77 --- /dev/null +++ b/files/pt-br/web/api/event/event/index.html @@ -0,0 +1,69 @@ +--- +title: Event() +slug: Web/API/Event/Event +translation_of: Web/API/Event/Event +--- +

{{APIRef("DOM")}}

+ +

O Event() cria uma nova {{domxref("Event")}}.

+ +

Sintaxe

+ +
 event = new Event(typeArg, eventInit);
+ +

Valores

+ +
+
typeArg
+
É uma {{domxref("DOMString")}} representa o nome do evento.
+
eventInit{{optional_inline}}
+
+ +
+
É um dicionário EventInit, tendo os seguintes campos: + +
    +
  • "bubbles", opcional e false por default, do tipo {{jsxref("Boolean")}}, indica se o evento é bubbles ou não.
  • +
  • "cancelable", opcional e false por default, do tipo {{jsxref("Boolean")}}, indica se o evento pode ser cancelado ou não.
  • +
+
+
+ +

Exemplo

+ +
// criar um evento com bubbles true e que não pode ser cancelado
+
+var ev = new Event("look", {"bubbles":true, "cancelable":false});
+document.dispatchEvent(ev);
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('DOM WHATWG','#interface-event','Event()')}}{{Spec2('DOM WHATWG')}}Definição inicial.
+ +

Compatibilidade de browser

+ + + +

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

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/event/index.html b/files/pt-br/web/api/event/index.html new file mode 100644 index 0000000000..7fe5549c48 --- /dev/null +++ b/files/pt-br/web/api/event/index.html @@ -0,0 +1,146 @@ +--- +title: Event +slug: Web/API/Event +tags: + - API + - DOM + - Event + - Interface + - NeedsTranslation + - Reference + - Référence(2) + - TopicStub +translation_of: Web/API/Event +--- +

{{APIRef("DOM")}}

+ +

A interface de eventos representa qualquer evento de DOM. Ele contém propriedades comuns e métodos para qualquer evento.

+ +

Um monte de outras interfaces herdam, diretamente ou não, a partir desta interface base:

+ +
+ +
+ +

Construtor

+ +
+
{{domxref("Event.Event", "Event()")}}
+
Cria um objeto Event.
+
+ +

Propriedades

+ +

Esta interface não herda nenhuma propriedade.

+ +
+
{{domxref("Event.bubbles")}} {{readonlyinline}}
+
Um booleano que indica se o evento surge em bolha pela DOM ou não.
+
{{domxref("Event.cancelable")}} {{readonlyinline}}
+
Um booleano que indica se o evento é cancelado.
+
{{domxref("Event.currentTarget")}} {{readonlyinline}}
+
Uma referencia para o alvo registrado atualmente para o evento.
+
{{domxref("Event.defaultPrevented")}} {{readonlyinline}}
+
Indica se ou não {{domxref("event.preventDefault()")}} foi chamado no evento..
+
{{domxref("Event.eventPhase")}} {{readonlyinline}}
+
Indica que fase do fluxo de eventos está a ser processada.
+
{{domxref("Event.explicitOriginalTarget")}} {{non-standard_inline}} {{readonlyinline}}
+
O objetivo original explícito do evento (Mozilla-specific).
+
{{domxref("Event.originalTarget")}} {{non-standard_inline}} {{readonlyinline}}
+
O objectivo inicial do evento, antes de qualquer redirecionamento (Mozilla-specific).
+
{{domxref("Event.target")}} {{readonlyinline}}
+
A referência ao objectivo para o qual o evento foi originalmente despachado.
+
{{domxref("Event.timeStamp")}} {{readonlyinline}}
+
O tempo em que o evento foi criado.
+
{{domxref("Event.type")}} {{readonlyinline}}
+
O nome do evento (case-insensitive).
+
{{domxref("Event.isTrusted")}} {{readonlyinline}}
+
Indica se ou não o evento foi iniciado pelo navegador (depois de um clique do usuário, por exemplo) ou por um script (usando um método de criação de evento, como event.initEvent)
+
+ +

Metodos

+ +

Esta interface não herda nenhum método.

+ +
+
{{domxref("Event.initEvent()")}} {{deprecated_inline}}
+
Inicializa o valor de um evento criado. Se o evento já está sendo despachado, este método não faz nada.
+
{{domxref("Event.preventBubble()")}} {{non-standard_inline}} {{Obsolete_inline(24)}}
+
Impede o evento de borbulhar. Obsoleto, use {{domxref ("event.stopPropagation")}} em vez disso.
+
{{domxref("Event.preventCapture()")}} {{non-standard_inline}} {{Obsolete_inline(24)}}
+
Obsoleto, use {{domxref("event.stopPropagation")}} ao invés.
+
{{domxref("Event.preventDefault()")}}
+
Cancela o evento (caso seja cancelável).
+
{{domxref("Event.stopImmediatePropagation()")}}
+
Para este evento em particular, nenhum outro ouvinte será chamado. Ou aqueles ligados no mesmo elemento, nem aqueles associados em elementos que serão percorridos mais tarde
+ (em fase de captura, por exemplo)​.
+
{{domxref("Event.stopPropagation()")}}
+
Para a propagação de eventos mais adiante no DOM.
+
{{domxref("Event.getPreventDefault()")}} {{non-standard_inline}}
+
Obsoleto, use {{domxref("Event.defaultPrevented")}} ao invés.
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/event/initevent/index.html b/files/pt-br/web/api/event/initevent/index.html new file mode 100644 index 0000000000..6a26dcb3e8 --- /dev/null +++ b/files/pt-br/web/api/event/initevent/index.html @@ -0,0 +1,137 @@ +--- +title: Event.initEvent() +slug: Web/API/Event/initEvent +tags: + - API + - DOM + - Descontinuado + - Evento + - Referencia + - metodo +translation_of: Web/API/Event/initEvent +--- +
{{ ApiRef("DOM") }}{{deprecated_header}}
+ +

O método Event.initEvent() é usado para inicializar o valor de um {{ domxref("event") }} criado usando {{ domxref("Document.createEvent()") }}.

+ +

Eventos inicializados desta maneira precisam ter sido criados com o método {{ domxref("Document.createEvent()") }}. Este método precisar ser chamado para definir o evento antes de ser despachado, usando {{ domxref("EventTarget.dispatchEvent()") }}. Uma vez despachado, não faz mais nada.

+ +
+

Não use esse método mais, pois está depreciado.

+ +

Ao invés, use construtores de eventos específicos, como {{domxref("Event.Event", "Event()")}}. A página sobre Criando e disparando eventos detalha mais informações sobre o uso desses eventos.

+
+ +

Syntax

+ +
event.initEvent(tipo, bubbles, cancelable);
+ +
+
tipo
+
É um {{domxref("DOMString")}} definido o tipo do evento.
+
bolhas
+
É um {{jsxref("Boolean")}} decidindo se o evento precisa ser enviado para cima, na cadeia de eventos ou não. Uma vez definido, a propriedade read-only {{ domxref("Event.bubbles") }} irá informar o seu valor.
+
cancelable
+
É um {{jsxref("Boolean")}} definindo se o evento pode ser cancelado. Uma vez definido, a propriedade read-only {{ domxref("Event.cancelable") }} will irá informar o seu valor.
+
+ +

Exemplo

+ +
// Cria o evento.
+var event = document.createEvent('Event');
+
+// Cria um evento de clique que borbulha e
+// não pode ser cancelado
+event.initEvent('click', true, false);
+
+// Escuta este evento.
+elem.addEventListener('click', function (e) {
+  // e.target matches elem
+}, false);
+
+elem.dispatchEvent(event);
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('DOM WHATWG', '#dom-event-initevent','Event.initEvent()')}}{{Spec2("DOM WHATWG")}}From {{SpecName('DOM2 Events')}}, deprecated it, superseded by event constructors.
{{SpecName('DOM2 Events','##Events-Event-initEvent','Event.initEvent()')}}{{Spec2('DOM2 Events')}}Initial definition.
+ +

Compatibilidade com navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureFirefox (Gecko)ChromeEdgeInternet ExplorerOperaSafari
Basic support{{CompatVersionUnknown()}} [1]{{CompatVersionUnknown()}}{{CompatVersionUnknown}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureFirefox Mobile (Gecko)AndroidEdgeIE MobileOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }} [1]{{ CompatUnknown() }}{{CompatVersionUnknown}}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

[1] Antes do Firefox 17, uma chamada a este método depois de despachar o evento gerava uma exceção ao invés de não fazer nada.

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/event/istrusted/index.html b/files/pt-br/web/api/event/istrusted/index.html new file mode 100644 index 0000000000..711fcae44b --- /dev/null +++ b/files/pt-br/web/api/event/istrusted/index.html @@ -0,0 +1,57 @@ +--- +title: Event.isTrusted +slug: Web/API/Event/isTrusted +translation_of: Web/API/Event/isTrusted +--- +
{{APIRef("DOM")}}
+A propriedade  isTrusted da interface {{domxref("Event")}}, exclusiva para leitura, é uma booleana ({{domxref("Boolean")}}) de valor verdadeiro (true) se tal evento é disparado pela ação do usuário. Retorna falso (false) caso o acionamento do evento seja ocasionado pelo método {{domxref("EventTarget.dispatchEvent()")}} ou tenha sido criado ou modificado por um script.
+ +
 
+ +

Sintaxe

+ +
var eventIsTrusted = event.isTrusted;
+
+ +

Valor

+ +

{{domxref("Boolean")}}

+ +

Exemplo

+ +
if (e.isTrusted) {
+  /* The event is trusted */
+} else {
+  /* The event is not trusted */
+}
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + +
EspecifiaçãoStatusComentário
{{SpecName('DOM WHATWG', '#dom-event-istrusted', 'Event.isTrusted')}}{{ Spec2('DOM WHATWG') }} 
{{SpecName('DOM3 Events', '#trusted-events', 'Trusted events')}}{{Spec2('DOM3 Events')}}Amplia requisito para confiabilidade de um evento, embora isto não defina por si só a propriedade isTrusted.
+ + + +
+ + +

{{Compat("api.Event.isTrusted")}}

+
diff --git a/files/pt-br/web/api/event/preventdefault/index.html b/files/pt-br/web/api/event/preventdefault/index.html new file mode 100644 index 0000000000..cc39be846e --- /dev/null +++ b/files/pt-br/web/api/event/preventdefault/index.html @@ -0,0 +1,113 @@ +--- +title: Event.preventDefault() +slug: Web/API/Event/preventDefault +translation_of: Web/API/Event/preventDefault +--- +
{{ ApiRef("DOM") }}
+ +
 
+ +

Resumo

+ +

Cancela o evento se for cancelável, sem parar a propagação do mesmo.

+ +

Sintaxe

+ +
event.preventDefault();
+ +

Exemplo

+ +

Alternar é a ação padrão de clicar em uma caixa de seleção. Este exemplo demonstra como impedir que isso aconteça:

+ +
<!DOCTYPE html>
+<html>
+<head>
+<title>preventDefault example</title>
+
+<script>
+function stopDefAction(evt) {
+    evt.preventDefault();
+}
+
+document.getElementById('my-checkbox').addEventListener(
+    'click', stopDefAction, false
+);
+</script>
+</head>
+
+<body>
+
+<p>Please click on the checkbox control.</p>
+
+<form>
+    <input type="checkbox" id="my-checkbox" />
+    <label for="my-checkbox">Checkbox</label>
+</form>
+
+</body>
+</html>
+ +

Você pode ver o preventDefault em ação aqui.

+ +

O exemplo a seguir demonstra como um input com texto inválido pode ser parado ao chegar ao campo de entrada com o preventDefault().

+ +
+
<!DOCTYPE html>
+<html>
+<head>
+<title>preventDefault example</title>
+
+<script>
+
+ +
function Init () {
+    var myTextbox = document.getElementById('my-textbox');
+    myTextbox.addEventListener( 'keypress', checkName, false );
+}
+
+function checkName(evt) {
+    var charCode = evt.charCode;
+    if (charCode != 0) {
+        if (charCode < 97 || charCode > 122) {
+            evt.preventDefault();
+            alert(
+                "Please use lowercase letters only."
+                + "\n" + "charCode: " + charCode + "\n"
+            );
+        }
+    }
+}
+
+ +
</script>
+</head>
+<body onload="Init ()">
+    <p>Please enter your name using lowercase letters only.</p>
+    <form>
+        <input type="text" id="my-textbox" />
+    </form>
+</body>
+</html>
+
+ +

Aqui está o resultado do código anterior:

+ +

{{ EmbedLiveSample('preventDefault_invalid_text', '', '', '') }}

+ +

Notas

+ +

Chamar preventDefault durante qualquer fase do fluxo de eventos cancela o evento, o que significa que qualquer ação padrão normalmente feita pela aplicação como um resultado do evento não ocorrerá.

+ +
+

Nota: A partir do {{Gecko("6.0")}}, chamar o preventDefault() faz com que o {{ domxref("event.defaultPrevented") }} se torne true.

+
+ +

Você pode usar o event.cancelable para checar se o evento é cancelável. Chamar o preventDefault para um evento não cancelável não fará efeito.

+ +

Se o preventDefault não parar a propagação do evento através do DOM. event.stopPropagation deve ser usada para isso.

+ +

Especificação

+ + diff --git a/files/pt-br/web/api/event/srcelement/index.html b/files/pt-br/web/api/event/srcelement/index.html new file mode 100644 index 0000000000..c66dc744d4 --- /dev/null +++ b/files/pt-br/web/api/event/srcelement/index.html @@ -0,0 +1,74 @@ +--- +title: Event.srcElement +slug: Web/API/Event/srcElement +translation_of: Web/API/Event/srcElement +--- +

{{ApiRef("DOM")}}

+ +

{{ Non-standard_header() }}

+ +

Event.srcElement é uma propriedade alias para a propriedade padrão {{domxref("Event.target")}}. É específica para versões antigas do Microsoft Internet Explorer.

+ +

Especificações

+ +

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

+ +

Microsoft tem uma descrição na MSDN.

+ +

Compatibilidade de navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatNo}} [1]{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatUnknown}}{{CompatNo}} [1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1]: {{bug(453968)}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/event/stopimmediatepropagation/index.html b/files/pt-br/web/api/event/stopimmediatepropagation/index.html new file mode 100644 index 0000000000..a5de39c083 --- /dev/null +++ b/files/pt-br/web/api/event/stopimmediatepropagation/index.html @@ -0,0 +1,99 @@ +--- +title: Event.stopImmediatePropagation() +slug: Web/API/Event/stopImmediatePropagation +tags: + - API + - Method + - Referência(2) + - event.stopImmediatePropagation(); + - events + - pt-br + - stopImmediatePropagation +translation_of: Web/API/Event/stopImmediatePropagation +--- +
{{APIRef("DOM")}}
+ +

Evita que outros listeners escutem o evento.

+ +

Sintaxe

+ +
event.stopImmediatePropagation();
+
+ +

Notas

+ +

No caso de um evento onde vários listeners o estão escutando, os mesmos são disparados na ordem em que foram adicionados. Porém, se durante uma chamada (ou disparo), event.stopImmediatePropagation() for chamado, os demais listeners não serão disparados.

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentários
{{SpecName('DOM WHATWG', '#dom-event-stopimmediatepropagation', 'Event.stopImmediatePropagation()')}}{{Spec2('DOM WHATWG')}} 
{{SpecName('DOM4', '#dom-event-stopimmediatepropagation', 'Event.stopImmediatePropagation()')}}{{Spec2('DOM4')}}Initial definition
+ +

Compatibilidade

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatChrome("6.0")}}{{CompatGeckoDesktop("10.0")}}{{CompatIE(9.0)}}{{CompatOpera("15.0")}}{{CompatSafari("5.0")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
diff --git a/files/pt-br/web/api/event/stoppropagation/index.html b/files/pt-br/web/api/event/stoppropagation/index.html new file mode 100644 index 0000000000..54d0c9bd5f --- /dev/null +++ b/files/pt-br/web/api/event/stoppropagation/index.html @@ -0,0 +1,93 @@ +--- +title: Event.stopPropagation() +slug: Web/API/Event/stopPropagation +tags: + - API + - Evento + - Referencia + - Referência(2) + - metodo + - stopPropagation +translation_of: Web/API/Event/stopPropagation +--- +

{{APIRef("DOM")}}

+ +

Resumo

+ +

Impede a propagação do evento por seus respectivos listeners.

+ +

Sintaxe

+ +
event.stopPropagation();
+ +

Parametros

+ +

Nenhum

+ +

Valor retornado

+ +

undefined.

+ +

Exemplo

+ +

Veja o exemplo 5: Event Propagation no capítulo Eventos para um exemplo mais detalhado desse método e propagação de evento no DOM.

+ +

Notas

+ +

Veja DOM specification para a explicação do fluxo de eventos. (O DOM Level 3 Events draft possui uma ilustração.)

+ +

preventDefault é um método de complemento que pode ser usado para previnir a ação padrão do evento que estiver acontecendo.

+ +

Especificação

+ +

DOM Level 3 Events: stopPropagation

+ +

Compatibilidade do Browser

+ +

{{CompatibilityTable()}}

+ +
+ + + + + + + + + + + + + + + + + + + +
RecursoChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}9{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
RecursoAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}{{CompatUnknown()}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}
+
diff --git a/files/pt-br/web/api/event/target/index.html b/files/pt-br/web/api/event/target/index.html new file mode 100644 index 0000000000..8a3ab35191 --- /dev/null +++ b/files/pt-br/web/api/event/target/index.html @@ -0,0 +1,69 @@ +--- +title: Event.target +slug: Web/API/Event/target +tags: + - PortuguêsBrasil + - pt-br +translation_of: Web/API/Event/target +--- +
{{ApiRef("DOM")}}
+ +

Uma referência ao objeto que enviou o evento. É diferente de {{domxref ("event.currentTarget")}} quando o manipulador de eventos é chamado durante a fase de borbulhagem ou captura do evento.

+ +

Sintaxe

+ +
theTarget = event.target
+ +

Exemplo

+ +

A propriedade event.target pode ser usada para implementar a delegação de eventos.

+ +
// Assumindo que existe uma variável 'list' contendo uma instância de um elemento ul de HTML.
+function hide(e) {
+  // A menos que os itens da lista sejam separados por uma margem, e.target deve ser diferente de e.currentTarget
+  e.target.style.visibility = 'hidden';
+}
+
+list.addEventListener('click', hide, false);
+
+// Se algum elemento (elemento <li> ou um link dentro de um elemento <li> por exemplo) for clicado, ele desaparecerá.
+// Só requer um único listener para fazer isso.
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("DOM WHATWG", "#dom-event-target", "Event.target")}}{{Spec2("DOM WHATWG")}}
{{SpecName("DOM4", "#dom-event-target", "Event.target")}}{{Spec2("DOM4")}}
{{SpecName("DOM2 Events", "#Events-Event-target", "Event.target")}}{{Spec2("DOM2 Events")}}Initial definition
+ +

Compatibilidade do navegador

+ + +

{{Compat("api.Event.target")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/event/type/index.html b/files/pt-br/web/api/event/type/index.html new file mode 100644 index 0000000000..3ca34e79f3 --- /dev/null +++ b/files/pt-br/web/api/event/type/index.html @@ -0,0 +1,60 @@ +--- +title: Event.type +slug: Web/API/Event/type +translation_of: Web/API/Event/type +--- +

{{APIRef("DOM")}}

+ +

Sumário

+ +

Retorna uma string contendo o tipo de evento.

+ +

O argumento do evento {{ domxref("EventTarget.addEventListener()") }} e {{ domxref("EventTarget.removeEventListener()") }} é caso insensível(case insensitive).

+ +

Veja Mozilla event reference para obter a lista de tipos de evento disponíveis

+ +

Sintaxe

+ +
event.type
+
+ +

Exemplos

+ +
var string = event.type;
+
+ +
<!DOCTYPE html>
+<html lang="pt-br">
+<head>
+
+<title>exemplo de tipo</title>
+
+<script>
+var currEvent = null;
+
+function getEvtType(evt) {
+  currEvent = evt.type;
+  document.getElementById("Etype").firstChild.nodeValue = currEvent;
+}
+
+</script>
+</head>
+
+<body
+  onkeydown="getEvtType(event)"
+  onkeyup="getEvtType(event)"
+  onmousedown="getEvtType(event)"
+  onmouseup="getEvtType(event)">
+
+<p>Pressione uma tecla ou clique com o mouse para obter o tipo de evento.</p>
+<p>Tipo de evento: <span id="Etype">-</span></p>
+
+</body>
+</html>
+
+ +

Especificação

+ + diff --git a/files/pt-br/web/api/eventlistener/index.html b/files/pt-br/web/api/eventlistener/index.html new file mode 100644 index 0000000000..0e00e865a2 --- /dev/null +++ b/files/pt-br/web/api/eventlistener/index.html @@ -0,0 +1,48 @@ +--- +title: EventListener +slug: Web/API/EventListener +tags: + - API + - DOM + - Eventos DOM +translation_of: Web/API/EventListener +--- +

{{APIRef("DOM Events")}}

+ +

Visão Geral

+ + + + + + + +
void handleEvent(in Event event);
+ +

Métodos

+ +

handleEvent()

+ +

Este método é chamado sempre que ocorrer o evento para qual a interface do  EventListener for registrada.

+ +
void handleEvent(
+  in Event event
+);
+
+ +
Parâmetros
+ +
+
event
+
O {{ domxref("Evento") }} DOM que foi acionado.
+
+ +

Observaçōes

+ +

Conforme a interface for marcada com a flag [function], todos os objetos Function automaticamente implementtam essa interface. Chamar o método {{ manch("handleEvent") }} em uma dessas implementaçōes automaticamente invoca a função.

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/eventsource/eventsource/index.html b/files/pt-br/web/api/eventsource/eventsource/index.html new file mode 100644 index 0000000000..30db3e3761 --- /dev/null +++ b/files/pt-br/web/api/eventsource/eventsource/index.html @@ -0,0 +1,157 @@ +--- +title: EventSource() +slug: Web/API/EventSource/EventSource +tags: + - API + - Construtor + - EventSource + - Eventos enviados pelo servidor + - Referencia +translation_of: Web/API/EventSource/EventSource +--- +
{{APIRef('WebSockets API')}}
+ +

O construtor EventSource() retorna uma nova {{domxref("EventSource")}}, que representa um recurso remoto.

+ +

Sintaxe

+ +
eventSource = new EventSource(url, configuration);
+ +

Parâmetros

+ +
+
url
+
Uma {{domxref("USVString")}} que representa a localização de um recurso remoto servindo os eventos/mensagens.
+
configuration {{optional_inline}}
+
Fornece opções para configurar a nova conexão. Os atributos possíveis são: +
    +
  • withCredentials, valor padrão false, indicando se o CORS deve ser instruído a incluir credenciais.
  • +
+
+
+ +

Exemplos

+ +
var evtSource = new EventSource('sse.php');
+var eventList = document.querySelector('ul');
+
+evtSource.onmessage = function(e) {
+  var newElement = document.createElement("li");
+
+  newElement.textContent = "message: " + e.data;
+  eventList.appendChild(newElement);
+}
+ +
+

Nota: Você pode encontrar um exemplo completo no GitHub — veja Simple SSE demo using PHP.

+
+ +

Especificações

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "comms.html#dom-eventsource", "EventSource()")}}{{Spec2('HTML WHATWG')}}Definição inicial
+ + + +

Compatibilidade de navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico9{{ CompatGeckoDesktop("6.0") }}{{CompatUnknown}}115
Suporte a CORS (withCredentials)26{{ CompatGeckoDesktop("11.0") }}{{CompatUnknown}}12{{CompatUnknown}}
Disponível em workers compartilhados e dedicados[1]{{CompatVersionUnknown}}{{CompatGeckoDesktop("53.0")}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{ CompatAndroid("4.4") }}{{ CompatGeckoMobile("6.0") }}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Suporte a CORS (withCredentials){{CompatUnknown}}{{ CompatGeckoMobile("11.0") }}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Disponível em workers compartilhados e dedicados[1]{{CompatUnknown}}{{CompatGeckoMobile("53.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Masin ainda não em service workers.

+ +

See also

+ + diff --git a/files/pt-br/web/api/eventsource/index.html b/files/pt-br/web/api/eventsource/index.html new file mode 100644 index 0000000000..9b9efaaf46 --- /dev/null +++ b/files/pt-br/web/api/eventsource/index.html @@ -0,0 +1,175 @@ +--- +title: EventSource +slug: Web/API/EventSource +tags: + - API + - Interface + - eventos +translation_of: Web/API/EventSource +--- +

{{APIRef("Websockets API")}}

+ +

A interface EventSource é usada para receber eventos enviados pelo servidor (server-sent events). Ele se conecta via HTTP em um servidor e recebe eventos com o formato text/event-stream. A conexão permanece aberta até ser fechada chamando {{domxref("EventSource.close()")}}.

+ +

Assim que a conexão estiver aberta, mensagens recebidas do servidor são entregues para o seu código na forma de eventos {{event("message")}}.

+ +

Ao contrário dos WebSockets, server-sent events são unidirecionais; ou seja, mensagens são entregues em uma direção, do servidor para o cliente (por exemplo, um navegador web). Isso torna-os uma excelente escolha quando não há necessidade de enviar mensagens do cliente para o servidor. Por exemplo, EventSource é uma abordagem útil para lidar com atualizações de status de mídias sociais, feeds de notícias, or entregar dados para um mecanismo de armazenamento do lado cliente como o IndexedDB ou o web storage.

+ +

Construtor

+ +
+
{{domxref("EventSource.EventSource", "EventSource()")}}
+
Cria um novo EventSource para receber enventos enviados pelo servidor de uma URL específica, opcionalmente no modo de credenciais.
+
+ +

Propriedades

+ +

 

+ +

Essa interface também herda propriedades do seu pai, {{domxref("EventTarget")}}.

+ +
+
{{domxref("EventSource.readyState")}} {{readonlyinline}}
+
Um número representando o estado da conexão. Valores possíveis são CONNECTING (0), OPEN (1), ou CLOSED (2).
+
{{domxref("EventSource.url")}} {{readonlyinline}}
+
Uma {{domxref("DOMString")}} representando a URL da origem.
+
{{domxref("EventSource.withCredentials")}} {{readonlyinline}}
+
Um {{domxref("Boolean")}} indicando se a EventSource foi instanciada com credenciais cross-origin (CORS) definidas (true) ou não (false, o padrão).
+
+

Eventos

+
+
{{domxref("EventSource.onerror")}}
+
É um {{domxref("EventHandler")}} chamado quando um erro ocorre e o evento {{event("error")}} é despachado para o objeto EventSource.
+
{{domxref("EventSource.onmessage")}}
+
É um {{domxref("EventHandler")}} chamado quando um evento {{event("message")}} é recebido, ou seja, quando uma mensagem está sendo recebida da origem.
+
{{domxref("EventSource.onopen")}}
+
É um {{domxref("EventHandler")}} chamado quando um evento {{event("open")}} é recebido, ou seja, logo após a abertura da conexão.
+
+ +

Métodos

+ +

Essa interface herda métodos de seu pai, {{domxref("EventTarget")}}.

+ +
+
{{domxref("EventSource.close()")}}
+
Fecha a conexão, se houver, e define o atributo readyState como CLOSED. Se a conexão já estiver fechada, esse método não faz nada.
+
+ +

Exemplos

+ +

Nesse exemplo básico, um EventSource é criado para receber eventos do servidor; a página com o nome "sse.php" é responsável por gerar os eventos.

+ +
var evtSource = new EventSource('sse.php');
+var eventList = document.querySelector('ul');
+
+evtSource.onmessage = function(e) {
+  var newElement = document.createElement("li");
+
+  newElement.textContent = "message: " + e.data;
+  eventList.appendChild(newElement);
+}
+ +

Cada evento recebido faz com que o handler do evento onmessage no objeto EventSource seja executado. Ele, em contrapartida, cria um novo elemento {{HTMLElement("li")}} e escreve os dados da mensagem nele, e em seguida concatena o novo elemento na lista já presente no documento.

+ +
+

Nota: Você pode encontrar um exemplo completo no GitHub — veja Simple SSE demo using PHP.

+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG', "comms.html#the-eventsource-interface", "EventSource")}}{{Spec2('HTML WHATWG')}} 
+ +

Compatibilidade de Navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte a EventSource6{{CompatNo}}{{CompatGeckoDesktop("6.0")}}{{CompatNo}}{{CompatVersionUnknown}}5
Disponível em workers compartilhados e dedicados[1]{{CompatVersionUnknown}}{{CompatNo}}{{CompatGeckoDesktop("53.0")}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte a EventSource4.445{{CompatNo}}124.1
Disponível em workers compartilhados e dedicados[1]{{CompatVersionUnknown}}{{CompatGeckoMobile("53.0")}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

[1] Mas ainda não em service workers.

+ +

 

+ +

Veja também

+ + + +

 

diff --git a/files/pt-br/web/api/eventsource/onerror/index.html b/files/pt-br/web/api/eventsource/onerror/index.html new file mode 100644 index 0000000000..09b996e967 --- /dev/null +++ b/files/pt-br/web/api/eventsource/onerror/index.html @@ -0,0 +1,121 @@ +--- +title: EventSource.onerror +slug: Web/API/EventSource/onerror +translation_of: Web/API/EventSource/onerror +--- +
{{APIRef('WebSockets API')}}
+ +
 
+ +

A propriedade onerror da interface {{domxref("EventSource")}} é um {{domxref("EventHandler")}} chamado quando um erro ocorre e um evento {{event("error")}} é despachado para o objeto EventSource.

+ +

Sintaxe

+ +
eventSource.onerror = function
+ +

Exemplos

+ +
evtSource.onerror = function() {
+  console.log("EventSource failed.");
+};
+ +
+

Nota: Você pode encontrar um exemplo completo no GitHub — veja Simple SSE demo using PHP.

+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG', "comms.html#handler-eventsource-onerror", "onerror")}}{{Spec2('HTML WHATWG')}}Definição inicial
+ + + +

Compatibilidade de navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte a EventSource6{{CompatNo}}{{CompatGeckoDesktop("6.0")}}{{CompatNo}}{{CompatVersionUnknown}}5
Disponibilidade em workers compartilhados e dedicados[1]{{CompatVersionUnknown}}{{CompatNo}}{{CompatGeckoDesktop("53.0")}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte a EventSource4.445{{CompatNo}}124.1
Disponibilidade em workers compartilhados e dedicados[1]{{CompatVersionUnknown}}{{CompatGeckoMobile("53.0")}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

[1] Mas ainda não em service workers.

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/eventtarget/dispatchevent/index.html b/files/pt-br/web/api/eventtarget/dispatchevent/index.html new file mode 100644 index 0000000000..75b633642b --- /dev/null +++ b/files/pt-br/web/api/eventtarget/dispatchevent/index.html @@ -0,0 +1,43 @@ +--- +title: EventTarget.dispatchEvent() +slug: Web/API/EventTarget/dispatchEvent +tags: + - API + - DOM + - Gecko + - Method + - events +translation_of: Web/API/EventTarget/dispatchEvent +--- +

{{APIRef("DOM Events")}}

+ +

Dispara um {{domxref("Event")}} para o {{domxref("EventTarget")}} especificado, invocando os {{domxref("EventListener")}}s especificados, em uma ordem apropriada. O processamento normal das regras (including the capturing and optional bubbling phase) aplica-se a eventos disparados manualmente com dispatchEvent().

+ +

Sintaxe

+ +
cancelled = !target.dispatchEvent(event)
+
+ + + +

O método dispatchEvent joga UNSPECIFIED_EVENT_TYPE_ERR se o tipo do evento não foi especificado pela inicialização do evento antes do método ser chamado, ou se o tipo do evento for is null ou uma string vazia. Exceções jogadas por event handlers são reportadas  como exceções não-capturáveis; os event handlers são executados em uma callstack aninhada; eles bloqueiam o chamador até que a rotina tenha sido totalmente executada, mas as execeções não se propagam para o chamador.

+ +

Notas

+ +

dispatchEvent é a última fase do processo create-init-dispatch, a qual é usada para disparar eventos na implementação do event model. O evento pode ser criado utilizando o método document.createEvent e pode ser inicializado com initEvent ou outro método de inicialização mais específico, como initMouseEvent ou initUIEvent.

+ +

Veja também a referência Event object.

+ +

Exemplo

+ +

Veja Creating and triggering events.

+ +

Especificações

+ + diff --git a/files/pt-br/web/api/eventtarget/eventtarget/index.html b/files/pt-br/web/api/eventtarget/eventtarget/index.html new file mode 100644 index 0000000000..0ce5aa4363 --- /dev/null +++ b/files/pt-br/web/api/eventtarget/eventtarget/index.html @@ -0,0 +1,70 @@ +--- +title: EventTarget() +slug: Web/API/EventTarget/EventTarget +translation_of: Web/API/EventTarget/EventTarget +--- +
{{APIRef("DOM Events")}}
+ +

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

+ +

Sintaxe

+ +
var myEventTarget = new EventTarget();
+ +

Parâmetros

+ +

Nenhum.

+ +

Retorno de valor

+ +

Uma instância do objeto {{domxref("EventTarget")}}.

+ +

Exemplos

+ +
class MyEventTarget extends EventTarget {
+  constructor(mySecret) {
+    super();
+    this._secret = mySecret;
+  }
+
+  get secret() { return this._secret; }
+};
+
+let myEventTarget = new MyEventTarget(5);
+let value = myEventTarget.secret;  // == 5
+myEventTarget.addEventListener("foo", function(e) {
+  this._secret = e.detail;
+});
+
+let event = new CustomEvent("foo", { detail: 7 });
+myEventTarget.dispatchEvent(event);
+let newValue = myEventTarget.secret; // == 7
+ +

Specificações

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-eventtarget-eventtarget', 'EventTarget() constructor')}}{{Spec2('DOM WHATWG')}}
+ +

Compatibilidade de navegadores

+ + + +

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

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/eventtarget/index.html b/files/pt-br/web/api/eventtarget/index.html new file mode 100644 index 0000000000..c1eb84c9f0 --- /dev/null +++ b/files/pt-br/web/api/eventtarget/index.html @@ -0,0 +1,124 @@ +--- +title: EventTarget +slug: Web/API/EventTarget +tags: + - API + - DOM + - DOM Events + - Interface +translation_of: Web/API/EventTarget +--- +

{{ ApiRef("DOM Events") }}

+ +

Resumo

+ +

EventTarget é uma interface DOM implementada por objetos que podem receber eventos DOM e tem que ouvir estes.

+ +

{{domxref("Element")}}, {{domxref("document")}}, e {{domxref("window")}} são os mais comuns disparadores de eventos, mas outros objetos podem disparar eventos também, por exemplo {{domxref("XMLHttpRequest")}}, {{domxref("AudioNode")}}, {{domxref("AudioContext")}} e outros.

+ +

Muitos disparadores de eventos (incluindo elements, documents,  e windows) também suportam definir event handlers através on... propriedades e atributos.

+ +

Métodos

+ +
+
{{domxref("EventTarget.addEventListener()")}}
+
Registra um tratamento para um tipo específico de evento sobre o EventTarget.
+
{{domxref("EventTarget.removeEventListener()")}}
+
Remove um event listener do EventTarget.
+
{{domxref("EventTarget.dispatchEvent()")}}
+
Dispatch an event to this EventTarget.
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('DOM WHATWG', '#interface-eventtarget', 'EventTarget')}}{{Spec2('DOM WHATWG')}}Sem mundanças.
{{SpecName('DOM3 Events', 'DOM3-Events.html#interface-EventTarget', 'EventTarget')}}{{Spec2('DOM3 Events')}}Alguns parâmetros agora são opcionais (listener), ou aceitam o valor null (useCapture).
{{SpecName('DOM2 Events', 'events.html#Events-EventTarget', 'EventTarget')}}{{Spec2('DOM2 Events')}}Definição inicial.
+ +

Compatibilidade entre navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte Básico1.0{{ CompatGeckoDesktop("1") }}9.071.0
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FuncionalidadeAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte Básico1.0{{ CompatGeckoMobile("1") }}9.06.01.0
+
+ +

Additional methods for Mozilla chrome code

+ +

Mozilla extensions for use by JS-implemented event targets to implement on* properties. See also WebIDL bindings.

+ + + +

Veja também

+ + diff --git a/files/pt-br/web/api/eventtarget/removeeventlistener/index.html b/files/pt-br/web/api/eventtarget/removeeventlistener/index.html new file mode 100644 index 0000000000..dc558d006f --- /dev/null +++ b/files/pt-br/web/api/eventtarget/removeeventlistener/index.html @@ -0,0 +1,138 @@ +--- +title: EventTarget.removeEventListener() +slug: Web/API/EventTarget/removeEventListener +tags: + - API + - DOM + - Gecko + - JavaScript + - Method + - events +translation_of: Web/API/EventTarget/removeEventListener +--- +

{{APIRef("DOM Events")}}

+ +

Remove o event listener anteriormente registrado com {{domxref("EventTarget.addEventListener()")}}.

+ +

Sintaxe

+ +
target.removeEventListener(type, listener[, useCapture])
+ +
+
type
+
Uma string indicando o tipo de evento a ser removido.
+
listener
+
A função {{ domxref("EventListener") }}  a ser removida do event target.
+
useCapture {{ optional_inline() }}
+
Indica quando o {{ domxref("EventListener") }} a ser removido foi registrado ou não como capturing listener. Caso este parâmetro seja omitido, o valor false será assumido por padrão.
+
Se um listener foi registrado duas vezes, uma com o parâmetro capture especificado e outra sem, cada um deve ser removido separadamente. A remoção de um capturing listener não afeta a versão non-capturing do mesmo listener, e vice versa.
+
+ +
Nota: useCapture era obrigatório em versões mais antigas dos navegadores. Para ampla compatibilidade, sempre informe o parâmetro useCapture.
+ +

Notas

+ +

Se um {{ domxref("EventListener") }} é removido de um {{ domxref("EventTarget") }} enquanto este está processando um evento, esse não será disparado pelas current actions. Um {{ domxref("EventListener") }} não será invocado para o evento o qual foi registrado depois de ter sido removido, porém pode ser registrado novamente.

+ +

Chamar removeEventListener() com argumentos que não identifiquem nenhum {{ domxref("EventListener") }} registrado no EventTarget não tem qualquer efeito.

+ +

Exemplo

+ +

Este é um exemplo de como associar e remover um event listener.

+ +
var div = document.getElementById('div');
+var listener = function (event) {
+  /* faça alguma coisa... */
+};
+div.addEventListener('click', listener, false);
+div.removeEventListener('click', listener, false);
+
+ +

Compatibilidade entre navegadores

+ +

{{Compat("api.EventTarget.removeEventListener", 3)}}

+ + + +

Notas para Gecko

+ + + +

Notas para Opera

+ + + +

Notas para WebKit

+ + + +

Veja também

+ +

{{ domxref("EventTarget.addEventListener()") }}.

+ +

Especificação

+ + + +

Polyfill para oferecer suporte aos navegadores antigos

+ +

addEventListener() e removeEventListener() não estão presentes em navegadores antigos. Isto pode ser contornado se você inserir o código abaixo no início dos seus scripts, permitindo o uso de addEventListener() e removeEventListener()  em implementações as quais não oferecem suporte nativo. Entretanto, este método não funciona para o Internet Explorer 7 ou versões anteriores, uma vez que não era possível extender o Element.prototype até o Internet Explorer 8.

+ +
if (!Element.prototype.addEventListener) {
+  var oListeners = {};
+  function runListeners(oEvent) {
+    if (!oEvent) { oEvent = window.event; }
+    for (var iLstId = 0, iElId = 0, oEvtListeners = oListeners[oEvent.type]; iElId < oEvtListeners.aEls.length; iElId++) {
+      if (oEvtListeners.aEls[iElId] === this) {
+        for (iLstId; iLstId < oEvtListeners.aEvts[iElId].length; iLstId++) { oEvtListeners.aEvts[iElId][iLstId].call(this, oEvent); }
+        break;
+      }
+    }
+  }
+  Element.prototype.addEventListener = function (sEventType, fListener /*, useCapture (will be ignored!) */) {
+    if (oListeners.hasOwnProperty(sEventType)) {
+      var oEvtListeners = oListeners[sEventType];
+      for (var nElIdx = -1, iElId = 0; iElId < oEvtListeners.aEls.length; iElId++) {
+        if (oEvtListeners.aEls[iElId] === this) { nElIdx = iElId; break; }
+      }
+      if (nElIdx === -1) {
+        oEvtListeners.aEls.push(this);
+        oEvtListeners.aEvts.push([fListener]);
+        this["on" + sEventType] = runListeners;
+      } else {
+        var aElListeners = oEvtListeners.aEvts[nElIdx];
+        if (this["on" + sEventType] !== runListeners) {
+          aElListeners.splice(0);
+          this["on" + sEventType] = runListeners;
+        }
+        for (var iLstId = 0; iLstId < aElListeners.length; iLstId++) {
+          if (aElListeners[iLstId] === fListener) { return; }
+        }
+        aElListeners.push(fListener);
+      }
+    } else {
+      oListeners[sEventType] = { aEls: [this], aEvts: [ [fListener] ] };
+      this["on" + sEventType] = runListeners;
+    }
+  };
+  Element.prototype.removeEventListener = function (sEventType, fListener /*, useCapture (will be ignored!) */) {
+    if (!oListeners.hasOwnProperty(sEventType)) { return; }
+    var oEvtListeners = oListeners[sEventType];
+    for (var nElIdx = -1, iElId = 0; iElId < oEvtListeners.aEls.length; iElId++) {
+      if (oEvtListeners.aEls[iElId] === this) { nElIdx = iElId; break; }
+    }
+    if (nElIdx === -1) { return; }
+    for (var iLstId = 0, aElListeners = oEvtListeners.aEvts[nElIdx]; iLstId < aElListeners.length; iLstId++) {
+      if (aElListeners[iLstId] === fListener) { aElListeners.splice(iLstId, 1); }
+    }
+  };
+}
+
diff --git a/files/pt-br/web/api/fetch_api/basic_concepts/index.html b/files/pt-br/web/api/fetch_api/basic_concepts/index.html new file mode 100644 index 0000000000..c9845e75aa --- /dev/null +++ b/files/pt-br/web/api/fetch_api/basic_concepts/index.html @@ -0,0 +1,66 @@ +--- +title: Conceitos básicos de Fetch +slug: Web/API/Fetch_API/Basic_concepts +translation_of: Web/API/Fetch_API/Basic_concepts +--- +

{{DefaultAPISidebar("Fetch API")}}{{draft}}

+ +
+

Fetch API fornece uma interface para buscar recursos (inclusive pela rede). Parecerá familiar para alguém que já tenha usado {{domxref("XMLHttpRequest")}}, mas ela fornece um conjunto de recursos mais poderoso e flexível . Este artigo expõe alguns conceitos básicos da API Fetch.

+
+ +
+

Este artigo será incrementado ao longo do tempo. Se você achar um conceito em Fetch que parece precisar de uma explicação melhor, informe alguém em fórum de discussãMDN, or Mozilla IRC (#mdn room.)

+
+ +

Em poucas palavras

+ +

O coração do Fetch são as abstrações da Interface do HTTP {{domxref("Request")}}, {{domxref("Response")}}, {{domxref("Headers")}}, e {{domxref("Body")}} payloads, juntamente com {{domxref("GlobalFetch.fetch","global fetch")}} método para iniciar requisições de recursos assíncronos. Como os componentes principais do HTTP são abstraidos como objetos de JavaScript, torna-se fácil APIs fazer uso das funcionalidades.

+ +

Service Workers é um exemplo de uma API que faz um grande uso de Fecth.

+ +

Fetch leva a assincronicidade um passo além. A API é completamente baseada em {{jsxref("Promise")}}.

+ +

Guard

+ +

Guard é uma novidade de objetos {{domxref("Headers")}}, podendo assumir os valores de immutable, request, request-no-cors, response, ou none, dependendo de onde o cabeçalho é utilizado.

+ +

Quando um novo objeto {{domxref("Headers")}} é criado usando o {{domxref("Headers.Headers","Headers()")}} {{glossary("constructor")}}, seu guard é configurado como none (o padrão). Quando um objeto {{domxref("Request")}} ou {{domxref("Response")}} é criado, tem um objeto {{domxref("Headers")}}  associado cujo guard é resumido a seguir:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Novo tipo de objetoConstrutor criadoConfiguração guard associada ao objeto {{domxref("Headers")}}
{{domxref("Request")}}{{domxref("Request.Request","Request()")}}request
{{domxref("Request.Request","Request()")}} com {{domxref("Request.mode","mode")}} de no-corsrequest-no-cors
{{domxref("Response")}}{{domxref("Response.Response","Response()")}}response
Métodos {{domxref("Response.error","error()")}} ou {{domxref("Response.redirect","redirect()")}}immutable
+ +

Um cabeçalho guard afeta os métodos {{domxref("Headers.set","set()")}}, {{domxref("Headers.delete","delete()")}}, e {{domxref("Headers.append","append()")}} os quais mudam o conteúdo do cabeçalho. UmTypeError é lançado se você tentar modificar um objeto {{domxref("Headers")}} objeto cujo "guard" é immutable. De qualquer maneira, a operação vai funcionar se

+ + diff --git a/files/pt-br/web/api/fetch_api/index.html b/files/pt-br/web/api/fetch_api/index.html new file mode 100644 index 0000000000..6409994ae7 --- /dev/null +++ b/files/pt-br/web/api/fetch_api/index.html @@ -0,0 +1,85 @@ +--- +title: Fetch API +slug: Web/API/Fetch_API +tags: + - API + - Experimental + - Fetch + - Referência(2) + - XMLHttpRequest + - request +translation_of: Web/API/Fetch_API +--- +

{{DefaultAPISidebar("Fetch API")}}{{ SeeCompatTable() }}

+ +

A Fetch API fornece uma interface para buscar recursos (por exemplo, em toda a rede). Parecerá familiar para qualquer pessoa que tenha usado XMLHttpRequest, porém a nova API oferece um conjunto de recursos mais poderoso e flexível.

+ +

Conceitos e uso

+ +

O Fetch fornece uma definição genérica de objetos de {{domxref("Request")}} e {{domxref("Response")}}  (e outras coisas envolvidas com solicitações de rede). Isso permitirá que eles sejam usados onde quer que sejam necessários no futuro, seja para service workers, Cache API e outras coisas similares que manipulam ou modifiquem pedidos e respostas ou qualquer tipo de caso de uso que possa exigir que você gere suas próprias responses programaticamente.

+ +

Ele também fornece uma definição para conceitos relacionados como CORS e a semântica de cabeçalho de origem HTTP, suplantando suas definições separadas em outro lugar.

+ +

Para fazer uma solicitação e buscar um recurso, use o método {{domxref("GlobalFetch.fetch")}} . Ele é implementado em várias interfaces, especificamente {{domxref("Window")}} e {{domxref("WorkerGlobalScope")}}. Isso torna disponível em praticamente qualquer contexto em que você possa querer obter recursos.

+ +

O método fetch () tem um argumento obrigatório, o caminho para o recurso que deseja obter. Ele retorna uma promessa que resolve a {{domxref("Response")}} para esta requisição, seja ele bem-sucedido ou não. Você também pode, opcionalmente, passar um objeto de opções de inicialização como o segundo argumento (consulte {{domxref("Request")}}).

+ +

Uma vez que uma {{domxref("Response")}} é recuperada, há uma série de métodos disponíveis para definir o conteúdo do corpo e como ele deve ser tratado (veja {{domxref("Body")}}.)

+ +


+ Você pode criar um pedido e uma resposta diretamente usando os construtores {{domxref("Request.Request","Request()")}} e {{domxref("Response.Response","Response()")}}, mas é improvável que você faça isso diretamente. Em vez disso, é mais provável que sejam criados como resultados de outras ações da API (por exemplo,  {{domxref("FetchEvent.respondWith")}} de service workers).

+ +
+

Note: Encontre mais informações sobre os recursos do Fetch API em Using Fetch,  e conceitos para estudos em Fetch basic concepts.

+
+ +

Fetch Interfaces

+ +
+
{{domxref("GlobalFetch")}}
+
Contém o método fetch() usado para buscar um recurso.
+
{{domxref("Headers")}}
+
Representa cabeçalhos response/request, permitindo que você os consulte e faça diferentes ações dependendo dos resultados.
+
{{domxref("Request")}}
+
Representa um pedido de recursos.
+
{{domxref("Response")}}
+
Representa a resposta de uma requisição.
+
+ +

Fetch mixin

+ +
+
{{domxref("Body")}}
+
Providencia métodos relacionados ao corpo da resposta/requisição, permitindo que você declare qual seu tipo de conteúdo e como ele deve ser tratado.
+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentários
{{SpecName('Fetch')}}{{Spec2('Fetch')}}Definição inicial
+ + + +

{{Compat("api.WindowOrWorkerGlobalScope.fetch")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/fetch_api/using_fetch/index.html b/files/pt-br/web/api/fetch_api/using_fetch/index.html new file mode 100644 index 0000000000..0b951f7461 --- /dev/null +++ b/files/pt-br/web/api/fetch_api/using_fetch/index.html @@ -0,0 +1,311 @@ +--- +title: Usando Fetch +slug: Web/API/Fetch_API/Using_Fetch +translation_of: Web/API/Fetch_API/Using_Fetch +--- +
+

A API Fetch fornece uma interface JavaScript para acessar e manipular partes do pipeline HTTP, tais como os pedidos e respostas. Ela também fornece o método global {{domxref("GlobalFetch.fetch","fetch()")}} que fornece uma maneira fácil e lógica para buscar recursos de forma assíncrona através da rede.

+
+ +

Este tipo de funcionalidade era obtida anteriormente utilizando {{domxref("XMLHttpRequest")}}. Fetch fornece uma alternativa melhor que pode ser facilmente utilizada por outras tecnologias como {{domxref("ServiceWorker_API", "Service Workers")}}. Fetch também provê um lugar lógico único para definir outros conceitos relacionados ao protocolo HTTP como CORS e extensões ao HTTP.

+ +

Note que a especificação fetch() difere de jQuery.ajax(), principalmente, de três formas:

+ + + +

Situação do suporte por navegadores

+ +

Os suportes para Fetch ainda estão em uma fase bastante precoce, mas começa a ter progresso. Se tornou um padrão no Firefox 39 e Chrome 42 até as versões mais atuais.

+ +

Caso tenha interesse no uso da ferramenta, há também uma Fetch Polyfill disponivel que recria as funcionalidade para outros navegadores que ainda não o suporta. Fique ciente que está em estado experimental e ainda não há uma versão completa.

+ +
+

Nota: There have been some concerns raised that the Fetch spec is at odds with the Streams spec; however, future plans show an intention to integrate Streams with Fetch: read Fetch API integrated with Streams for more information.

+
+ +

Detecção de Recursos

+ +

Fetch API support pode ser detectada na existência do escopo {{domxref("Headers")}}, {{domxref("Request")}}, {{domxref("Response")}} ou {{domxref("GlobalFetch.fetch","fetch()")}} no {{domxref("Window")}} ou {{domxref("Worker")}} . Por exemplo, faça o seguinte teste no seu código:

+ +
if(self.fetch) {
+    // execute minha solicitação do fetch aqui
+} else {
+    // faça alguma coisa com XMLHttpRequest?
+}
+ +

Fazendo as requisições Fetch

+ +

Uma requisição fetch é realizada para configuração. Temos um exemplo no seguinte código:

+ +
var myImage = document.querySelector('img');
+
+fetch('flowers.jpg')
+.then(function(response) {
+  return response.blob();
+})
+.then(function(myBlob) {
+  var objectURL = URL.createObjectURL(myBlob);
+  myImage.src = objectURL;
+});
+
+
+ +

Aqui estamos procurando uma imagem e inserindo em um elemento {{htmlelement("img")}}. O uso mais básico dofetch() acarreta em um argumento — a pasta do recurso que você deseja buscar — e retorna uma promessa contendo a resposta (a {{domxref("Response")}} object).

+ +

Esta é apenas uma resposta HTTP, não a imagem em sí. Para extrairmos a imagem da resposta, nós usamos o método {{domxref("Body.blob","blob()")}} (definido no mixin do {{domxref("Body")}}, que são implementados por ambos os objetos {{domxref("Request")}} e {{domxref("Response")}}.)

+ +
+

Nota: O Body mixin além disso possui métodos similares para extrair outros tipos de conteúdo do body; Veja a sessão {{anch("Body")}} para mais detalhes.

+
+ +

Um objectURL é criado na extração de {{domxref("Blob")}}, que então é inserido no {{domxref("img")}}.

+ +

Requisições Fetch são controladas pela directiva connect-src do Content Security Policy ao invés da directiva do recurso retornado.

+ +

Fornecendo opções de request

+ +

O método fetch() pode receber um segundo parametro opcional, que consiste em um objeto init que permite setar várias configurações:

+ +
var myHeaders = new Headers();
+
+var myInit = { method: 'GET',
+               headers: myHeaders,
+               mode: 'cors',
+               cache: 'default' };
+
+fetch('flowers.jpg',myInit)
+.then(function(response) {
+  return response.blob();
+})
+.then(function(myBlob) {
+  var objectURL = URL.createObjectURL(myBlob);
+  myImage.src = objectURL;
+});
+
+
+ +

See {{domxref("GlobalFetch.fetch","fetch()")}} for the full options available, and more descriptions.

+ +

Verificando se o fetch foi bem sucedido

+ +

Uma promise {{domxref("GlobalFetch.fetch","fetch()")}} será rejeitada com um {{jsxref("TypeError")}} quando um erro de rede é encontrado, embora isso geralmente signifique problemas de permissão ou similar — um 404 não constitui um erro de rede, por exemplo. Uma verificação precisa de um fetch()  bem-sucedido incluiria a verificação de que a promessa foi resolvida e, em seguida, a verificação de que a propriedade {{domxref("Response.ok")}} tem o valor de true. O código seria parecido com o abaixo:

+ +
fetch('flowers.jpg').then(function(response) {
+  if(response.ok) {
+    response.blob().then(function(myBlob) {
+      var objectURL = URL.createObjectURL(myBlob);
+      myImage.src = objectURL;
+    });
+  } else {
+    console.log('Network response was not ok.');
+  }
+})
+.catch(function(error) {
+  console.log('There has been a problem with your fetch operation: ' + error.message);
+});
+ +

Fornecendo seu próprio objeto de solicitação

+ +

Em vez de passar um caminho, para o recurso que você deseja solicitar, dentro da rquisição fetch(), você pode criar um objeto de solicitação usando o construtor {{domxref("Request.Request","Request()")}}, e então passar a solicitação como um argumento do método fetch() :

+ +
var myHeaders = new Headers();
+
+var myInit = { method: 'GET',
+               headers: myHeaders,
+               mode: 'cors',
+               cache: 'default' };
+
+var myRequest = new Request('flowers.jpg', myInit);
+
+fetch(myRequest)
+.then(function(response) {
+  return response.blob();
+})
+.then(function(myBlob) {
+  var objectURL = URL.createObjectURL(myBlob);
+  myImage.src = objectURL;
+});
+ +

Request() aceita exatamente os mesmos parâmetros do método fetch(). Você pode até mesmo passar um objeto de solicitação existente para criar uma cópia dele:​​​​​​

+ +
var anotherRequest = new Request(myRequest,myInit);
+ +

Isso é muito útil, pois os conteúdos de cada solicitação e resposta tem apenas um uso. Fazer uma cópia como essa permite que você use a solicitação / resposta novamente, variando as opções de inicialização, se desejar.

+ +
+

Nota: Também existe um método que cria uma cópia: {{domxref ("Request.clone", "clone ()")}}. Isso tem uma semântica ligeiramente diferente do outro método de cópia: o primeiro dirá se o conteúdo, da solicitação anterior, já tiver sido lido (ou copiado), enquanto o segundo, clone() não.

+
+ +

Headers

+ +

A interface {{domxref("Headers")}} permite que você crie seus proprios objetos headers por meio do construtor {{domxref("Headers.Headers","Headers()")}}. Um objeto headers é um  mapa multidimensional simples de nomes para o valor? 

+ +
var content = "Hello World";
+var myHeaders = new Headers();
+myHeaders.append("Content-Type", "text/plain");
+myHeaders.append("Content-Length", content.length.toString());
+myHeaders.append("X-Custom-Header", "ProcessThisImmediately");
+ +

O mesmo pode ser feito passando um array de arrays ou um objeto literal para o construtor:

+ +
myHeaders = new Headers({
+  "Content-Type": "text/plain",
+  "Content-Length": content.length.toString(),
+  "X-Custom-Header": "ProcessThisImmediately",
+});
+ +

O conteúdo pode ser consultado e recuperado:

+ +
console.log(myHeaders.has("Content-Type")); // true
+console.log(myHeaders.has("Set-Cookie")); // false
+myHeaders.set("Content-Type", "text/html");
+myHeaders.append("X-Custom-Header", "AnotherValue");
+
+console.log(myHeaders.get("Content-Length")); // 11
+console.log(myHeaders.getAll("X-Custom-Header")); // ["ProcessThisImmediately", "AnotherValue"]
+
+myHeaders.delete("X-Custom-Header");
+console.log(myHeaders.getAll("X-Custom-Header")); // [ ]
+ +

Some of these operations are only useful in {{domxref("ServiceWorker_API","ServiceWorkers")}}, but they provide a much nicer API for manipulating headers.

+ +

All of the Headers methods throw a TypeError if a header name is used that is not a valid HTTP Header name. The mutation operations will throw a TypeError if there is an immutable guard (see below). Otherwise they fail silently. For example:

+ +
var myResponse = Response.error();
+try {
+  myResponse.headers.set("Origin", "http://mybank.com");
+} catch(e) {
+  console.log("Cannot pretend to be a bank!");
+}
+ +

A good use case for headers is checking whether the content type is correct before you process it further. For example:

+ +
fetch(myRequest).then(function(response) {
+  var contentType = response.headers.get("content-type");
+  if(contentType && contentType.indexOf("application/json") !== -1) {
+    return response.json().then(function(json) {
+      // process your JSON further
+    });
+  } else {
+    console.log("Oops, we haven't got JSON!");
+  }
+});
+ +

Guard

+ +

Since headers can be sent in requests and received in responses, and have various limitations about what information can and should be mutable, headers objects have a guard property. This is not exposed to the Web, but it affects which mutation operations are allowed on the headers object.

+ +

Possible guard values are:

+ + + +
+

Note: You may not append or set a request guarded Headers’ Content-Length header. Similarly, inserting Set-Cookie into a response header is not allowed: ServiceWorkers are not allowed to set cookies via synthesized responses.

+
+ +

Response objects

+ +

As you have seen above, {{domxref("Response")}} instances are returned when fetch() promises are resolved.

+ +

They can also be created programmatically via JavaScript, but this is only really useful in {{domxref("ServiceWorker_API", "ServiceWorkers")}}, when you are providing a custom response to a received request using a {{domxref("FetchEvent.respondWith","respondWith()")}} method:

+ +
var myBody = new Blob();
+
+addEventListener('fetch', function(event) {
+  event.respondWith(
+    new Response(myBody, {
+      headers: { "Content-Type" : "text/plain" }
+    })
+  );
+});
+ +

The {{domxref("Response.Response","Response()")}} constructor takes two optional arguments — a body for the response, and an init object (similar to the one that {{domxref("Request.Request","Request()")}} accepts.)

+ +

The most common response properties you'll use are:

+ + + +
+

Note: The static method {{domxref("Response.error","error()")}} simply returns an error response. Similarly, {{domxref("Response.redirect","redirect()")}} returns a response resulting in
+ a redirect to a specified URL. These are also only relevant to Service Workers.

+
+ +

Body

+ +

Both requests and responses may contain body data. A body is an instance of any of the following types.

+ + + +

The {{domxref("Body")}} mixin defines the following methods to extract a body (implemented by both {{domxref("Request")}} and {{domxref("Response")}}). These all return a promise that is eventually resolved with the actual content.

+ + + +

This makes usage of non-textual data much easier than it was with XHR.

+ +

Request bodies can be set by passing body parameters:

+ +
var form = new FormData(document.getElementById('login-form'));
+fetch("/login", {
+  method: "POST",
+  body: form
+});
+ +

Both request and response (and by extension the fetch() function), will try to intelligently determine the content type. A request will also automatically set a Content-Type header if none is set in the dictionary.

+ +

Especificações

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fetch')}}{{Spec2('Fetch')}}Initial definition
+ +

Compatibilidade com os browsers

+ +

{{Compat("api.WindowOrWorkerGlobalScope.fetch")}}

+ +
+ + diff --git a/files/pt-br/web/api/fetch_api/uso_de_busca_cross-global/index.html b/files/pt-br/web/api/fetch_api/uso_de_busca_cross-global/index.html new file mode 100644 index 0000000000..c569966b5a --- /dev/null +++ b/files/pt-br/web/api/fetch_api/uso_de_busca_cross-global/index.html @@ -0,0 +1,35 @@ +--- +title: Uso de busca Cross-global +slug: Web/API/Fetch_API/Uso_de_busca_Cross-global +translation_of: Web/API/Fetch_API/Cross-global_fetch_usage +--- +

 

+ +

Este artigo explica um "edge case" (um problema ou situação que ocorre apenas em um parâmetro operacional extremo) que ocorre ao utilizar fetch (e potencialmente outras APIs que exibem o mesmo tipo de comportamento de recuperação de recurso). Quando uma busca de cross-origin envolvendo uma URL relativa é iniciada a partir de um {{htmlelement ("iframe")}}, a URL relativa costumava ser resolvida na localização global atual, em vez da localização do iframe.

+ +

O "edge case"

+ +

Muitos sites nunca se deparam com este caso extremo. Para que isso aconteça:

+ + + +

O problema

+ +

No passado, resolveríamos o URL relativo contra o global atual, por exemplo:

+ +
let absolute = new URL(relative, window.location.href)
+ +

Isto não é um problema como tal. É que diferentes APIs que exibem esse tipo de comportamento estavam fazendo isso de maneira inconsistente com o comportamento definido na especificação, o que poderia levar a problemas mais adiante.

+ +

A solução

+ +

No Firefox 60 em diante, o Mozilla resolve a URL relativa contra o global que possui a função fetch() que está sendo usada (veja {{bug (1432272)}}). Portanto, no caso descrito acima, ele é resolvido em relação à localização do iframe:

+ +
let absolute = new URL(relative, frame.contentWindow.location.href)
+ +

Há muita discussão em andamento sobre a obtenção de novas especificações para se alinhar a essa mudança de comportamento, a fim de mitigar possíveis problemas no futuro.

diff --git a/files/pt-br/web/api/file/index.html b/files/pt-br/web/api/file/index.html new file mode 100644 index 0000000000..471cf7bbda --- /dev/null +++ b/files/pt-br/web/api/file/index.html @@ -0,0 +1,146 @@ +--- +title: File +slug: Web/API/File +tags: + - API + - Arquivos + - DOM + - Files + - Referencia +translation_of: Web/API/File +--- +
{{gecko_minversion_header("1.9")}}
+ +
{{APIRef("File API")}}
+ +

Sumário

+ +

A interface File provê informações sobre arquivos e permite ao JavaScript  a acessar seu conteúdo.

+ +

São geralmente recuperados a partir de um objeto {{domxref("FileList")}} que é retornado como resultado da seleção, pelo usuário, de arquivos através do elemento {{ HTMLElement("input") }}, a partir do objeto {{domxref("DataTransfer")}} utilizado em operações de arrastar e soltar, ou a partir da API mozGetAsFile() em um {{ domxref("HTMLCanvasElement") }}. Em Gecko, códigos com privilégiios podem criar objetos File representando qualquer arquivo local sem a intereção do usuário (veja {{anch("Implementation notes")}} para mais informações.)

+ +

Um objeto File é um tipo específico de  {{domxref("Blob")}}, e podem ser utilizados em qualquer contexto que um Blob pode. Em particular, {{domxref("FileReader")}}, {{domxref("URL.createObjectURL()")}}, {{domxref("ImageBitmapFactories.createImageBitmap()", "createImageBitmap()")}}, e {{domxref("XMLHttpRequest", "", "send()")}} aceitam ambos, Blobs e Files.

+ +

Veja Using files from web applications (usando arquivos através de uma aplicação web) para mais informações e exemplos.

+ +

A referência ao arquivo pode ser salva quando o formulário é submetido enquanto o usuário está offline, de forma que os dados possam ser recuperados e enviados quando a conexão com a internet for reestabelecida,

+ +

Propriedades

+ +
+
{{domxref("File.lastModifiedDate")}} {{readonlyinline}} {{gecko_minversion_inline("15.0")}}
+
A Data da última modificação do arquivo referenciado pelo objeto File.
+
{{domxref("File.name")}} {{readonlyinline}} {{gecko_minversion_inline("1.9.2")}}
+
O nome do arquivo referenciado pelo objeto File.
+
{{domxref("File.fileName")}} {{non-standard_inline}} {{readonlyinline}} {{obsolete_inline("7.0")}}
+
O nome do arquivo referenciado pelo objeto File.
+
{{domxref("File.fileSize")}} {{non-standard_inline}} {{readonlyinline}} {{obsolete_inline("7.0")}}
+
O tamanho do arquivo referenciado, em bytes.
+
+ +

A interface File herda as propriedades da interface {{domxref("Blob")}}.

+ +

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

+ +

Métodos

+ +
+
{{domxref("File.getAsBinary()")}} {{non-standard_inline}} {{obsolete_inline("7.0")}}
+
Retorna uma string contendo os dados do arquivo em formato binário.
+
{{domxref("File.getAsDataURL()")}} {{non-standard_inline}} {{obsolete_inline("7.0")}}
+
Uma string contendo os dados do arquivo codificados como data: URL.
+
{{domxref("File.getAsText()","File.getAsText(string encoding)")}} {{non-standard_inline}} {{obsolete_inline("7.0")}}
+
Retorna o conteúdo do arquivo como uma string em que os dados do arquivo são interpretados como texto, usando a codificação passada por parâmetro.
+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentários
{{SpecName('File API')}}{{Spec2('File API')}}Definição Inicial.
+ +

Compatibilidade com os Navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico13{{CompatGeckoDesktop("1.9")}} (non standard)
+ {{CompatGeckoDesktop("7")}} (standard)
10.016.06.0
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Suporte básico{{CompatNo}}25{{CompatNo}}11.16.0
+
+ +

Notas de Implementação

+ +

Notas no Gecko

+ + + +

Veja também

+ + diff --git a/files/pt-br/web/api/file/using_files_from_web_applications/index.html b/files/pt-br/web/api/file/using_files_from_web_applications/index.html new file mode 100644 index 0000000000..cba8315001 --- /dev/null +++ b/files/pt-br/web/api/file/using_files_from_web_applications/index.html @@ -0,0 +1,351 @@ +--- +title: Using files from web applications +slug: Web/API/File/Using_files_from_web_applications +translation_of: Web/API/File/Using_files_from_web_applications +--- +

Usando a File API adicionada ao DOM em HTML5, agora é possível para conteúdo web solicitar ao usuário para selecionar arquivos locais, e então ler o conteúdo desses arquivos. Essa seleção pode ser feita usando um elemento HTML {{HTMLElement("input") }} ou por arrastar e soltar.  

+

Se você quiser usar a DOM File API através de extensões ou outro código chrome, você pode; Na verdade, há algumas funcionalidades adicionais para se estar ciente. Veja Usando a DOM File API em código chrome para detalhes.

+

Selecionando arquivos usando HTML

+

Selecionar um único arquivo para uso com a File API é simples:

+
<input type="file" id="input" onchange="handleFiles(this.files)">
+

Quando um usuário seleciona um arquivo, a função handleFiles() é chamada com um objeto {{ domxref("FileList") }} contendo o objeto {{ domxref("File") }} representando o arquivo selecionado pelo usuário.

+

If you want to let the user select multiple files, simply use the multiple attribute on the input element:

+
<input type="file" id="input" multiple onchange="handleFiles(this.files)">
+

In this case, the file list passed to the handleFiles() function contains one {{ domxref("File") }} object for each file the user selected.

+

Using hidden file input elements using the click() method

+

Starting in Gecko 2.0 {{ geckoRelease("2.0") }}, you can hide the admittedly ugly file {{ HTMLElement("input") }} element and present your own interface for opening the file picker and displaying which file or files the user has selected. You can do this by styling the input element with display:none and calling the {{ domxref("element.click","click()") }} method on the {{ HTMLElement("input") }} element.

+

Consider this HTML:

+
<input type="file" id="fileElem" multiple accept="image/*" style="display:none" onchange="handleFiles(this.files)">
+<a href="#" id="fileSelect">Select some files</a>
+

The code that handles the click event can look like this:

+
var fileSelect = document.getElementById("fileSelect"),
+  fileElem = document.getElementById("fileElem");
+
+fileSelect.addEventListener("click", function (e) {
+  if (fileElem) {
+    fileElem.click();
+  }
+  e.preventDefault(); // prevent navigation to "#"
+}, false);
+
+

Obviously you can style the new button for opening the file picker as you wish.

+

Dynamically adding a change listener

+

If your input field was created using a JavaScript library such as jQuery, you'll need to use {{ domxref("element.addEventListener()") }} to add the change event listener, like this:

+
var inputElement = document.getElementById("inputField");
+inputElement.addEventListener("change", handleFiles, false);
+
+function handleFiles() {
+  var fileList = this.files;
+
+  /* now you can work with the file list */
+}
+
+

Note that in this case, the handleFiles() function looks up the file list instead of accepting a parameter, since event listeners added in this way can't accept an input parameter.

+

Using object URLs

+

Gecko 2.0 {{ geckoRelease("2.0") }} introduces support for the DOM {{ domxref("window.URL.createObjectURL()") }} and {{ domxref("window.URL.revokeObjectURL()") }} methods. These let you create simple URL strings that can be used to reference any data that can be referred to using a DOM {{ domxref("File") }} object, including local files on the user's computer.

+

When you have a {{ domxref("File") }} object you'd like to reference by URL from HTML, you can create an object URL for it like this:

+
var objectURL = window.URL.createObjectURL(fileObj);
+

The object URL is a string identifying the {{ domxref("File") }} object. Each time you call {{ domxref("window.URL.createObjectURL()") }}, a unique object URL is created, even if you've created an object URL for that file already. Each of these must be released. While they are released automatically when the document is unloaded, if your page uses them dynamically, you should release them explicitly by calling {{ domxref("window.URL.revokeObjectURL()") }}:

+
window.URL.revokeObjectURL(objectURL);
+

Selecting files using drag and drop

+

You can also let the user drag and drop files into your web application.

+

The first step is to establish a drop zone. Exactly what part of your content will accept drops may vary depending on the design of your application, but making an element receive drop events is easy:

+
var dropbox;
+
+dropbox = document.getElementById("dropbox");
+dropbox.addEventListener("dragenter", dragenter, false);
+dropbox.addEventListener("dragover", dragover, false);
+dropbox.addEventListener("drop", drop, false);
+
+

In this example, we're turning the element with the ID dropbox into our drop zone. This is done by adding listeners for the dragenter, dragover, and drop events.

+

We don't actually need to do anything with the dragenter and dragover events in our case, so these functions are both simple. They just stop propagation of the event and prevent the default action from occurring:

+
function dragenter(e) {
+  e.stopPropagation();
+  e.preventDefault();
+}
+
+function dragover(e) {
+  e.stopPropagation();
+  e.preventDefault();
+}
+
+

The real magic happens in the drop() function:

+
function drop(e) {
+  e.stopPropagation();
+  e.preventDefault();
+
+  var dt = e.dataTransfer;
+  var files = dt.files;
+
+  handleFiles(files);
+}
+
+

Here, we retrieve the dataTransfer field from the event, then pull the file list out of it, passing that to handleFiles(). From this point on, handling the files is the same whether the user used the input element or drag and drop.

+

Getting information about selected files

+

The {{ domxref("FileList") }} object provided by the DOM lists all the files selected by the user, each specified as a {{ domxref("File") }} object. You can determine how many files the user selected by checking the value of the file list's length attribute:

+
var numFiles = files.length;
+

Individual {{ domxref("File") }} objects can be retrieved by simply accessing the list as an array:

+
for (var i = 0, numFiles = files.length; i < numFiles; i++) {
+  var file = files[i];
+  ..
+}
+
+

This loop iterates over all the files in the file list.

+

There are three attributes provided by the {{ domxref("File") }} object that contain useful information about the file.

+
+
+ name
+
+ The file's name as a read-only string. This is just the file name, and does not include any path information.
+
+ size
+
+ The size of the file in bytes as a read-only 64-bit integer.
+
+ type
+
+ The MIME type of the file as a read-only string, or "" if the type couldn't be determined.
+
+

Example: Showing file(s) size

+

The following example shows a possible use of the size property:

+
<!DOCTYPE html>
+<html>
+<head>
+<meta charset="UTF-8">
+<title>File(s) size</title>
+<script>
+function updateSize() {
+  var nBytes = 0,
+      oFiles = document.getElementById("uploadInput").files,
+      nFiles = oFiles.length;
+  for (var nFileId = 0; nFileId < nFiles; nFileId++) {
+    nBytes += oFiles[nFileId].size;
+  }
+  var sOutput = nBytes + " bytes";
+  // optional code for multiples approximation
+  for (var aMultiples = ["KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"], nMultiple = 0, nApprox = nBytes / 1024; nApprox > 1; nApprox /= 1024, nMultiple++) {
+    sOutput = nApprox.toFixed(3) + " " + aMultiples[nMultiple] + " (" + nBytes + " bytes)";
+  }
+  // end of optional code
+  document.getElementById("fileNum").innerHTML = nFiles;
+  document.getElementById("fileSize").innerHTML = sOutput;
+}
+</script>
+</head>
+
+<body onload="updateSize();">
+<form name="uploadForm">
+<p><input id="uploadInput" type="file" name="myFiles" onchange="updateSize();" multiple> selected files: <span id="fileNum">0</span>; total size: <span id="fileSize">0</span></p>
+<p><input type="submit" value="Send file"></p>
+</form>
+</body>
+</html>
+
+

Example: Showing thumbnails of user-selected images

+

Let's say you're developing the next great photo-sharing web site, and want to use HTML5 to display thumbnail previews of images before the user actually uploads them. Simply establish your input element or drop zone as discussed previously, and have them call a function such as the handleFiles() function below.

+
function handleFiles(files) {
+  for (var i = 0; i < files.length; i++) {
+    var file = files[i];
+    var imageType = /image.*/;
+
+    if (!file.type.match(imageType)) {
+      continue;
+    }
+
+    var img = document.createElement("img");
+    img.classList.add("obj");
+    img.file = file;
+    preview.appendChild(img);
+
+    var reader = new FileReader();
+    reader.onload = (function(aImg) { return function(e) { aImg.src = e.target.result; }; })(img);
+    reader.readAsDataURL(file);
+  }
+}
+
+

Here our loop handling the user-selected files looks at each file's type attribute to see if it's an image file (by doing a regular expression match on the string "image.*"). For each file that is an image, we create a new img element. CSS can be used to establish any pretty borders, shadows, and to specify the size of the image, so that doesn't even need to be done here.

+

Each image has the CSS class obj added to it, to make them easy to find in the DOM tree. We also add a file attribute to each image specifying the {{ domxref("File") }} for the image; this will let us fetch the images for actually uploading later. Finally, we use {{ domxref("Node.appendChild()") }} to add the new thumbnail to the preview area of our document.

+

Then we establish the {{ domxref("FileReader") }} to handle actually asynchronously loading the image and attaching it to the img element. After creating the new FileReader object, we set up its onload function, then call readAsDataURL() to start the read operation in the background. When the entire contents of the image file are loaded, they are converted into a data: URL, which is passed to the onload callback. Our implementation of this routine simply sets the img element's src attribute to the loaded image, which results in the image appearing in the thumbnail on the user's screen.

+

Example: Using object URLs to display images

+

This example uses object URLs to display image thumbnails. In addition, it displays other file information including their names and sizes. You can view the example live.

+

The HTML that presents the interface looks like this:

+
<input type="file" id="fileElem" multiple accept="image/*" style="display:none" onchange="handleFiles(this.files)">
+<a href="#" id="fileSelect">Select some files</a>
+<div id="fileList">
+  <p>No files selected!</p>
+</div>
+
+

This establishes our file {{ HTMLElement("input") }} element, as well as a link that invokes the file picker, since we keep the file input hidden to prevent that less-than-attractive UI from being displayed. This is explained above in the section {{ anch("Using hidden file input elements using the click() method") }}, as is the method that invokes the file picker.

+

The handleFiles() method follows:

+
window.URL = window.URL || window.webkitURL;
+
+var fileSelect = document.getElementById("fileSelect"),
+    fileElem = document.getElementById("fileElem"),
+    fileList = document.getElementById("fileList");
+
+fileSelect.addEventListener("click", function (e) {
+  if (fileElem) {
+    fileElem.click();
+  }
+  e.preventDefault(); // prevent navigation to "#"
+}, false);
+
+function handleFiles(files) {
+  if (!files.length) {
+    fileList.innerHTML = "<p>No files selected!</p>";
+  } else {
+    var list = document.createElement("ul");
+    for (var i = 0; i < files.length; i++) {
+      var li = document.createElement("li");
+      list.appendChild(li);
+
+      var img = document.createElement("img");
+      img.src = window.URL.createObjectURL(files[i]);
+      img.height = 60;
+      img.onload = function(e) {
+        window.URL.revokeObjectURL(this.src);
+      }
+      li.appendChild(img);
+
+      var info = document.createElement("span");
+      info.innerHTML = files[i].name + ": " + files[i].size + " bytes";
+      li.appendChild(info);
+    }
+    fileList.appendChild(list);
+  }
+}
+
+

This starts by fetching the URL of the {{ HTMLElement("div") }} with the ID fileList. This is the block into which we'll insert out file list, including thumbmails.

+

If the {{ domxref("FileList") }} object passed to handleFiles() is null, we simply set the inner HTML of the block to display "No files selected!". Otherwise, we start building our file list, as follows:

+
    +
  1. A new unordered list ({{ HTMLElement("ul") }}) element is created.
  2. +
  3. The new list element is inserted into the {{ HTMLElement("div") }} block by calling its {{ domxref("element.appendChild()") }} method.
  4. +
  5. For each {{ domxref("File") }} in the {{ domxref("FileList") }} represented by files: +
      +
    1. Create a new list item ({{ HTMLElement("li") }}) element and insert it into the list.
    2. +
    3. Create a new image ({{ HTMLElement("img") }}) element.
    4. +
    5. Set the image's source to a new object URL representing the file, using {{ domxref("window.URL.createObjectURL()") }} to create the blob URL.
    6. +
    7. Set the image's height to 60 pixels.
    8. +
    9. Set up the image's load event handler to release the object URL, since it's no longer needed once the image has been loaded. This is done by calling the {{ domxref("window.URL.revokeObjectURL()") }} method, passing in the object URL string as specified by img.src.
    10. +
    11. Append the new list item to the list.
    12. +
    +
  6. +
+

Example: Uploading a user-selected file

+

Another thing you might want to do is let the user upload the selected file or files (such as the images selected using the previous example) to a server. This can be done asynchronously very easily.

+

Creating the upload tasks

+

Continuing with the code that builds the thumbnails in the previous example, recall that every thumbnail image is in the CSS class obj, with the corresponding {{ domxref("File") }} attached in a file attribute. This lets us very easily select all the images the user has chosen for uploading using {{ domxref("Document.querySelectorAll()") }}, like this:

+
function sendFiles() {
+  var imgs = document.querySelectorAll(".obj");
+
+  for (var i = 0; i < imgs.length; i++) {
+    new FileUpload(imgs[i], imgs[i].file);
+  }
+}
+
+

Line 2 creates an array, called imgs, of all the elements in the document with the CSS class obj. In our case, these will be all the image thumbnails. Once we have that list, it's trivial to go through the list, creating a new FileUpload instance for each. Each of these handles uploading the corresponding file.

+

Handling the upload process for a file

+

The FileUpload function accepts two inputs: an image element and a file from which to read the image data.

+
function FileUpload(img, file) {
+  var reader = new FileReader();
+  this.ctrl = createThrobber(img);
+  var xhr = new XMLHttpRequest();
+  this.xhr = xhr;
+
+  var self = this;
+  this.xhr.upload.addEventListener("progress", function(e) {
+        if (e.lengthComputable) {
+          var percentage = Math.round((e.loaded * 100) / e.total);
+          self.ctrl.update(percentage);
+        }
+      }, false);
+
+  xhr.upload.addEventListener("load", function(e){
+          self.ctrl.update(100);
+          var canvas = self.ctrl.ctx.canvas;
+          canvas.parentNode.removeChild(canvas);
+      }, false);
+  xhr.open("POST", "http://demos.hacks.mozilla.org/paul/demos/resources/webservices/devnull.php");
+  xhr.overrideMimeType('text/plain; charset=x-user-defined-binary');
+  reader.onload = function(evt) {
+    xhr.sendAsBinary(evt.target.result);
+  };
+  reader.readAsBinaryString(file);
+}
+
+

The FileUpload() function shown above creates a throbber, which is used to display progress information, then creates an {{ domxref("XMLHttpRequest") }} to handle uploading the data.

+

Before actually transferring the data, several preparatory steps are taken:

+
    +
  1. The XMLHttpRequest's upload progress listener is set to update the throbber with new percentage information, so that as the upload progresses, the throbber will be updated based on the latest information.
  2. +
  3. The XMLHttpRequest's upload load event handler is set to update the throbber with 100% as the progress information (to ensure the progress indicator actually reaches 100%, in case of granularity quirks during the process). It then removes the throbber, since it's no longer needed. This causes the throbber to disappear once the upload is complete.
  4. +
  5. The request to upload the image file is opened by calling XMLHttpRequest's open() method to start generating a POST request.
  6. +
  7. The MIME type for the upload is set by calling the XMLHttpRequest function overrideMimeType(). In this case, we're using a generic MIME type; you may or may not need to set the MIME type at all, depending on your use case.
  8. +
  9. The FileReader object is used to convert the file to a binary string.
  10. +
  11. Finally, when the content is loaded the XMLHttpRequest function sendAsBinary() is called to upload the file's content.
  12. +
+

Handling the upload process for a file, asynchronously

+
<?php
+if (isset($_FILES['myFile'])) {
+    // Example:
+    move_uploaded_file($_FILES['myFile']['tmp_name'], "uploads/" . $_FILES['myFile']['name']);
+    exit;
+}
+?><!DOCTYPE html>
+<html>
+<head>
+    <title>dnd binary upload</title>
+    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
+    <script type="text/javascript">
+        function sendFile(file) {
+            var uri = "/index.php";
+            var xhr = new XMLHttpRequest();
+            var fd = new FormData();
+
+            xhr.open("POST", uri, true);
+            xhr.onreadystatechange = function() {
+                if (xhr.readyState == 4 && xhr.status == 200) {
+                    // Handle response.
+                    alert(xhr.responseText); // handle response.
+                }
+            };
+            fd.append('myFile', file);
+            // Initiate a multipart/form-data upload
+            xhr.send(fd);
+        }
+
+        window.onload = function() {
+            var dropzone = document.getElementById("dropzone");
+            dropzone.ondragover = dropzone.ondragenter = function(event) {
+                event.stopPropagation();
+                event.preventDefault();
+            }
+
+            dropzone.ondrop = function(event) {
+                event.stopPropagation();
+                event.preventDefault();
+
+                var filesArray = event.dataTransfer.files;
+                for (var i=0; i<filesArray.length; i++) {
+                    sendFile(filesArray[i]);
+                }
+            }
+    </script>
+</head>
+<body>
+    <div>
+        <div id="dropzone" style="margin:30px; width:500px; height:300px; border:1px dotted grey;">Drag & drop your file here...</div>
+    </div>
+</body>
+</html>
+
+

See also

+ +

{{ HTML5ArticleTOC() }}

+

{{ languages( { "zh-cn": "zh-cn/Using_files_from_web_applications", "ja": "ja/Using_files_from_web_applications" } ) }}

diff --git a/files/pt-br/web/api/filelist/index.html b/files/pt-br/web/api/filelist/index.html new file mode 100644 index 0000000000..3c5e32b6cd --- /dev/null +++ b/files/pt-br/web/api/filelist/index.html @@ -0,0 +1,134 @@ +--- +title: FileList +slug: Web/API/FileList +translation_of: Web/API/FileList +--- +
{{APIRef("File API")}}{{gecko_minversion_header("1.9")}}
+ +

Um objeto desse tipo é retornado pela propriedade files do elemento HTML {{HTMLElement("input")}}; isso permite acessar a lista de arquivos selecionados com o elemento <input type="file">. Também é usado para uma lista de arquivos soltos no conteúdo web usando a API drag and drop; consulte o objeto DataTransfer para detalhes de seu uso.

+ +
+

Nota: Antes do {{Gecko("1.9.2")}}, o elemento input suportava apenas um arquivo selecionado por vez, ou seja, o array FileList conteria apenas um arquivo. A partir do {{Gecko("1.9.2")}}, se o atributo multiple do elemento for definido, FileList pode conter múltiplos arquivos.

+
+ +

Utilizando a lista de arquivos

+ +

Todo elemento <input> possui um array files que permite o acesso aos seus arquivos. Por exemplo, se o HTML inclui o seguinte elemento:

+ +
<input id="fileItem" type="file">
+
+ +

O código a seguir acessa o primeiro elemento da lista de arquivos como um objeto File:

+ +
var file = document.getElementById('fileItem').files[0];
+
+ +

Visão geral dos métodos

+ + + + + + + +
File item(index);
+ +

Propriedades

+ + + + + + + + + + + + + + +
AtributoTipoDescrição
lengthintegerValor somente-leitura que indica o número de arquivos na lista.
+ +

Métodos

+ +

item()

+ +

Retorna um objeto File representando o arquivo no índice especificado na lista.

+ +
 File item(
+   index
+ );
+
+ +
Parâmetros
+ +
+
index
+
O índice (baseado em zero) do arquivo a ser recuperado da lista.
+
+ +
Valor de retorno
+ +

O objeto File representando o arquivo requisitado.

+ +

Exemplo

+ +

Este exemplo itera por todos os arquivos selecionados pelo usuário em um elemento input:

+ +
// fileInput é um elemento HTML input: <input type="file" id="myfileinput" multiple>
+var fileInput = document.getElementById("myfileinput");
+
+// files é um objeto FileList (similar ao NodeList)
+var files = fileInput.files;
+var file;
+
+// percorre os arquivos
+for (var i = 0; i < files.length; i++) {
+
+    // obtém o item
+    file = files.item(i);
+    // ou
+    file = files[i];
+
+    alert(file.name);
+}
+
+ +

A seguir, um exemplo completo.

+ +
<!DOCTYPE HTML>
+<html>
+
+<head>
+</head>
+
+<body>
+<!--multiple é definido para que múltiplos arquivos possam ser selecionados-->
+
+<input id="myfiles" multiple type="file">
+
+</body>
+
+<script>
+var puxarArquivos = function() {
+    var fileInput = document.querySelector("#myfiles");
+    var files = fileInput.files;
+
+    for (var i = 0; i < files.length; i++) {
+        var file = files[i];
+        alert(file.name);
+    }
+}
+
+// seta o 'onchange' do elemento input para chamar a função puxarArquivos
+document.querySelector("#myfiles").onchange = puxarArquivos;
+</script>
+
+</html>
+ +

Especificação

+ + diff --git a/files/pt-br/web/api/filereader/filereader/index.html b/files/pt-br/web/api/filereader/filereader/index.html new file mode 100644 index 0000000000..49b3bd389e --- /dev/null +++ b/files/pt-br/web/api/filereader/filereader/index.html @@ -0,0 +1,54 @@ +--- +title: FileReader() +slug: Web/API/FileReader/FileReader +translation_of: Web/API/FileReader/FileReader +--- +

O construtor FileReader() cria um novo FileReader.

+ +

Para mais detalhes de como usar o FileReader, veja Using files from web applications.

+ +

Sintaxe

+ +
var reader = new FileReader();
+ +

Parâmetros

+ +

Nenhum.

+ +

Exemplo

+ +

O seguinte trecho de código ilustra a criação de um objeto FileReader usando o construtor FileReader() e depois utilizando o objeto:

+ +
function printFile(file) {
+  var reader = new FileReader();
+  reader.onload = function(evt) {
+    console.log(evt.target.result);
+  };
+  reader.readAsText(file);
+}
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('File API')}}{{Spec2('File API')}}Initial definition
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/filereader/index.html b/files/pt-br/web/api/filereader/index.html new file mode 100644 index 0000000000..772159fd36 --- /dev/null +++ b/files/pt-br/web/api/filereader/index.html @@ -0,0 +1,162 @@ +--- +title: FileReader +slug: Web/API/FileReader +translation_of: Web/API/FileReader +--- +

{{ APIRef("File API")}}

+ +

Resumo

+ +

O objeto FileReader permite aplicações web ler assincronamente o conteúdo dos arquivos (ou buffers de dados puros) do computador do usuário, utilizando o objeto {{ domxref("File") }} ou {{ domxref("Blob") }} para especificar o arquivo ou os dados a serem lidos.

+ +

Objetos File podem ser obtidos a partir de um objeto {{ domxref("FileList") }} retornado como resultado da seleção de um usuário utilizando um elemento {{ HTMLElement("input") }}, a partir de uma operação de drag and drop DataTransfer, ou a partir de um mozGetAsFile() da api {{ domxref("HTMLCanvasElement") }}.

+ +

Construtor

+ +
FileReader FileReader();
+ +

Veja Using files from web applications para detalhes e exemplos.

+ +

Propriedades

+ +
+
{{domxref("FileReader.error")}} {{readonlyinline}}
+
Um {{domxref("DOMError")}} representa o erro que ocorreu durante a leitura do arquivo.
+
{{domxref("FileReader.readyState")}} {{readonlyinline}}
+
Um número indicando o estado do FileReader. Este poderá ser um dos seguintes estados {{ anch("State constants") }}.
+
{{domxref("FileReader.result")}} {{readonlyinline}}
+
O conteúdo do arquivo. Esta propriedade é válida apenas após a operação de leitura estar completa, e o formato dos dados dependem de qual método foi usado para iniciar a operação de leitura.
+
+ +

Manipuladores de eventos

+ +
+
{{domxref("FileReader.onabort")}}
+
Um manipulador para o evento {{event("abort")}}. Este evento é chamado cada vez que a operação de leitura é abortada.
+
{{domxref("FileReader.onerror")}}
+
Um manipulador para o evento {{event("error")}}. Este evento é chamado cada vez que a operação de leitura encontra um erro.
+
{{domxref("FileReader.onload")}}
+
Um manipulador para o evento {{event("load")}}. Este evento é chamado cada vez que a operação de leitura é completada com sucesso.
+
{{domxref("FileReader.onloadstart")}}
+
Um manipulador para o evento {{event("loadstart")}}. Este evento é chamado cada vez que a leitura começa.
+
{{domxref("FileReader.onloadend")}}
+
Um manipulador para o evento {{event("loadend")}}. Este evento é chamado cada vez que a operação de leitura é completada (tanto em caso de sucesso quanto de erro).
+
{{domxref("FileReader.onprogress")}}
+
Um manipulador para o evento {{event("progress")}}. Este evento é chamado durante a leitura do conteúdo de {{domxref("Blob")}}.
+
+ +
+

Nota: O FileReader herda de {{domxref("EventTarget")}}, todos estes eventos podem ser listados usando o método {{domxref("EventTarget.addEventListener()","addEventListener")}}.

+
+ +

Constantes de estado

+ + + +

Métodos

+ +
+
{{domxref("FileReader.abort()")}}
+
Aborta a operação de leitura. O retorno, no readyState será DONE.
+
{{domxref("FileReader.readAsArrayBuffer()")}} {{ gecko_minversion_inline("7.0") }}
+
Inicia a leitura do conteúdo do {{ domxref("Blob") }} espeficado, uma vez finalizado, o atributo result conterá um {{domxref("ArrayBuffer")}} representando os dados do arquivo.
+
{{domxref("FileReader.readAsBinaryString()")}}
+
Inicia a leitura do conteúdo do {{ domxref("Blob") }} especificado, uma vez finalizado, o atributo result conterá os dados raw binários do arquivo como  string.
+
{{domxref("FileReader.readAsDataURL()")}}
+
Inicia a leitura do conteúdo do {{ domxref("Blob") }} especificado, uma vez finalizado, o atributo result conterá um data: URL representando os dados do arquivo.
+
{{domxref("FileReader.readAsText()")}}
+
Inicia a leitura do conteúdo do {{ domxref("Blob") }} especificado, uma vez finalizado, o atributo result conterá o conteúdo do arquivo como string de  texto.
+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('File API','#FileReader-interface','FileReader')}}{{Spec2('File API')}}Definição inicial.
+ +

Compatibilidade

+ +

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

Notas de implementações

+ + + +

Notas específicas para Gecko

+ + + +

Veja também

+ + diff --git a/files/pt-br/web/api/filereader/onload/index.html b/files/pt-br/web/api/filereader/onload/index.html new file mode 100644 index 0000000000..53b5774e88 --- /dev/null +++ b/files/pt-br/web/api/filereader/onload/index.html @@ -0,0 +1,29 @@ +--- +title: FileReader.onload +slug: Web/API/FileReader/onload +tags: + - Arquivo + - Event Handler + - FileReader + - Manipulador de eventos + - Propriedade +translation_of: Web/API/FileReader/onload +--- +

{{APIRef}}

+ +

A propriedade FileReader.onload contém um manipulador de eventos (event handler) executado quando o evento de carregamento ({{event('load')}})  é ativado, quando o conteúdo lido com  readAsArrayBuffer, readAsBinaryString, readAsDataURL ou readAsText fica disponível.

+ +

Exemplo

+ +
// Callback de um <input type="file" onchange="onChange(event)">
+function onChange(event) {
+  var file = event.target.files[0];
+  var reader = new FileReader();
+  reader.onload = function(event) {
+    // O arquivo de texto será impresso aqui
+    console.log(event.target.result)
+  };
+
+  reader.readAsText(file);
+}
+
diff --git a/files/pt-br/web/api/filereader/readasarraybuffer/index.html b/files/pt-br/web/api/filereader/readasarraybuffer/index.html new file mode 100644 index 0000000000..ed94bccf4b --- /dev/null +++ b/files/pt-br/web/api/filereader/readasarraybuffer/index.html @@ -0,0 +1,107 @@ +--- +title: FileReader.readAsArrayBuffer() +slug: Web/API/FileReader/readAsArrayBuffer +tags: + - API + - DOM + - File API + - FileReader + - Files + - Method + - Reference + - readAsArrayBuffer +translation_of: Web/API/FileReader/readAsArrayBuffer +--- +

{{APIRef("File API")}}

+ +

O método readAsArrayBuffer() do objeto {{domxref("FileReader")}} é utilizado para ler o conteúdo de um {{domxref("Blob")}} ou {{domxref("File")}} específico. Quando a operação de leitura é finalizada, o {{domxref("FileReader.readyState","readyState")}} torna-se DONE (finalizado), e o evento {{event("loadend")}} é acionado. Então, o atributo {{domxref("FileReader.result","result")}} retorna um {{domxref("ArrayBuffer")}} representando os dados do arquivo.

+ +

Sintaxe

+ +
instanceOfFileReader.readAsArrayBuffer(blob);
+ +

Parâmetros

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

Especificações

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

Compatibilidade com Navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FuncionalidadeFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Suporte Básico{{CompatGeckoDesktop("1.9.2")}}[1]710[2]12.02[3]6.0.2
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FuncionalidadeFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari Mobile
Suporte Básico3231011.56.1
+
+ +

[1] Antes da versão 2.0 beta 7 do Gecko (Firefox 4.0 beta 7), todos os parâmetros do {{domxref("Blob")}} abaixo eram parâmetros do {{domxref("File")}}; a atualização foi realizada pra corresponder corretamente à especificação. Antes da versão 13.0 do Gecko {{geckoRelease("13.0")}} A propriedade .error do FileReader retornava um objeto {{domxref("FileError")}}. Esta interface foi removida e FileReader.error agora retorna o objeto {{domxref("DOMError")}} como definido na última versão da documentação do FileAPI.

+ +

[2] IE9 possui File API Lab.

+ +

[3] Opera suporta parcialmente na versão 11.1.

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/filereader/readasbinarystring/index.html b/files/pt-br/web/api/filereader/readasbinarystring/index.html new file mode 100644 index 0000000000..5d23087951 --- /dev/null +++ b/files/pt-br/web/api/filereader/readasbinarystring/index.html @@ -0,0 +1,120 @@ +--- +title: FileReader.readAsBinaryString() +slug: Web/API/FileReader/readAsBinaryString +tags: + - API + - API Arquivos + - Arquivos + - File API + - Métodos + - Referencias(2) +translation_of: Web/API/FileReader/readAsBinaryString +--- +
{{APIRef("File API")}} {{non-standard_header}}
+ +

O método readAsBinaryString é usado para iniciar a leitura do conteúdo de um {{domxref("Blob")}} especificado, ou {{domxref("File")}}. Quando a operação de leitura é finalizada, o {{domxref("FileReader.readyState","readyState")}} se torna "DONE", e o evento {{event("loadend")}} é acionado. Neste momento, o atributo {{domxref("FileReader.result","result")}} contém o dado binário bruto do arquivo.

+ +

Note que este método se tornou obsoleto desde 12 de Julho de 2012 Working Draft do W3C.

+ +

Sintaxe

+ +
instanciaDeFileReader.readAsBinaryString(blob);
+ +

Parametros

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

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

+ +

Este método foi removido dos padrões FileAPI {{domxref("FileReader.readAsArrayBuffer()")}} deve ser usado no lugar dele.

+ +

Compatibilidade de Browser

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Suporte Básico{{CompatGeckoDesktop("1.9.2")}}[1]7{{CompatNo}}12.02[3]6.0
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari Mobile
Suporte Básico3231011.56.0
+
+ +

[1] Anteriormente ao Gecko 2.0 beta 7 (Firefox 4.0 beta 7), todos os parametros  {{domxref("Blob")}} inferiores eram parametros {{domxref("File")}}; Isso foi atualizado para combinar com as especifiações corretamente. Anteriormente ao Gecko 13.0 {{geckoRelease("13.0")}} a propriedade FileReader.error retornava um objeto {{domxref("FileError")}}. Essa interface foi removida e FileReader.error agora retorna o objeto domxref("DOMError")}} como foi definido no último draft do FileAPI.

+ +

[2] IE9 possui um File API Lab.

+ +

[3] Opera possui partial support in 11.1.

+ +

Veja Também

+ + diff --git a/files/pt-br/web/api/filereader/readasdataurl/index.html b/files/pt-br/web/api/filereader/readasdataurl/index.html new file mode 100644 index 0000000000..a922bf8bd0 --- /dev/null +++ b/files/pt-br/web/api/filereader/readasdataurl/index.html @@ -0,0 +1,111 @@ +--- +title: FileReader.readAsDataURL() +slug: Web/API/FileReader/readAsDataURL +tags: + - API + - File API + - Files + - Image Preview + - Method +translation_of: Web/API/FileReader/readAsDataURL +--- +

{{APIRef("File API")}}

+ +

O método readAsDataURL é usado para ler o conteúdo do tipo {{domxref("Blob")}} ou {{domxref("File")}}.
+ Quando a operação de leitura acaba, a flag {{domxref("FileReader.readyState","readyState")}} muda para DONE e o evento {{event("loadend")}} é disparado.
+ Então o atributo {{domxref("FileReader.result","result")}} irá conter a URL codificada em base64 do arquivo.

+ +

Sintaxe

+ +
instanceOfFileReader.readAsDataURL(blob);
+ +

Parametros

+ +
+
blob
+
O conteúdo do tipo {{domxref("Blob")}} ou {{domxref("File")}} que queremos ler.
+
+ +

Exemplo

+ +

HTML

+ +
<input type="file" onchange="previewFile()"><br>
+<img src="" height="200" alt="Prévia da imagem...">
+ +

JavaScript

+ +
function previewFile() {
+  var preview = document.querySelector('img');
+  var file    = document.querySelector('input[type=file]').files[0];
+  var reader  = new FileReader();
+
+  reader.onloadend = function () {
+    preview.src = reader.result;
+  }
+
+  if (file) {
+    reader.readAsDataURL(file);
+  } else {
+    preview.src = "";
+  }
+}
+ +

Demo

+ +

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

+ +

Exemplo de leitura com múltiplos arquivos

+ +

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 do FileReader() não é suportado  por versões anteriores à 10 do Internet Explorer. Para uma maior compatibilidade você pode ver os exemplos prévia de imagem básica ou prévia de imagem avançada.
+ +

Especificações

+ +

{{page("/pt-BR/docs/Web/API/FileReader","Specifications")}}

+ +

Compatibilidade

+ +

{{page("/pt-BR/docs/Web/API/FileReader","Browser compatibility")}}

+ +

Veja também

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

O método readAsText é usado para ler conteúdos de um {{domxref("Blob")}} ou {{domxref("File")}} especificados. Quando a operação de leitura é concluida, o {{domxref("FileReader.readyState","readyState")}} é alterado para DONE, o {{event("loadend")}} é disparado, e o atributo {{domxref("FileReader.result","result")}} passa a conter o conteúdo do arquivo como um texto em formato string.

+ +

Sintaxe

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

Parâmetros

+ +
+
blob
+
O {{domxref("Blob")}} ou {{domxref("File")}} a ser lido.
+
encoding {{optional_inline}}
+
Uma string especificando a codificação a ser usada para o dado retornado. Por padrão, UTF-8 é assumido se o parâmetro não for especificado.
+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName("File API", "#FileReader-interface", "FileReader")}}{{Spec2("File API")}}Definição inicial
+ +

Compatibilidade em navedadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureFirefox (Gecko)ChromeEdgeInternet ExplorerOperaSafari
Suporte básico{{CompatGeckoDesktop("1.9.2")}}[1]7{{CompatVersionUnknown}}10[2]12.02[3]6.0.2
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureFirefox Mobile (Gecko)AndroidEdgeIE MobileOpera MobileSafari Mobile
Suporte básico323{{CompatVersionUnknown}}1011.56.1
+
+ +

[1] Antes do Gecko 2.0 beta 7 (Firefox 4.0 beta 7), todos os parâmetros {{domxref("Blob")}} abaixo eram parâmetros de {{domxref("File")}}; isso desde então foi atualizado para coincidir com a especificação corretamente. Antes do Gecko 13.0 {{geckoRelease("13.0")}} a propriedade FileReader.error retornava um objeto {{domxref("FileError")}}. Essa interface foi removida e agora FileReader.error está retornando um objeto {{domxref("DOMError")}} conforme definido no último rascunho da FileAPI.

+ +

[2] IE9 tem uma File API Lab.

+ +

[3] Opera tem suporte parcial em 11.1.

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/formdata/append/index.html b/files/pt-br/web/api/formdata/append/index.html new file mode 100644 index 0000000000..d181310952 --- /dev/null +++ b/files/pt-br/web/api/formdata/append/index.html @@ -0,0 +1,177 @@ +--- +title: FormData.append() +slug: Web/API/FormData/append +translation_of: Web/API/FormData/append +--- +

{{APIRef("XMLHttpRequest")}}

+ +

O método append()  da Interface {{domxref("FormData")}}  adiciona um novo valor dentro de uma chave existente dentro do objeto FormData ou  adiciona a  chave caso ainda não exista.

+ +

A diferença entre  {{domxref("FormData.set")}} e append() é que se uma  chave específica já exista, {{domxref("FormData.set")}} irá substituir o valor existente com um novo valor, já o append() irá adicionar um novo valor no fim do conjunto de valores.

+ +
+

Nota: Este  metodo esta desponivel no Web Workers.

+
+ +

Sintaxe

+ +

Existe duas versoes deste metodo: um de dois e um outro de tres:

+ +
formData.append(name, value);
+formData.append(name, value, filename);
+ +

Parametros

+ +
+
name
+
O nome do campo cujos dados estão contidas em value.
+
value
+
O valor deste campo . Nas duas versões este é a {{domxref("USVString")}}, ou  caso não seja , este é convertido em string. Na versão de tres parametros este pode ser {{domxref("Blob")}}, {{domxref("File")}}, ou  {{domxref("USVString")}}, de novo, caso nenhum deses forem especificados  este valor é convertido em uma string.
+
filename {{optional_inline}}
+
O filename reporta para o servidor (a {{domxref("USVString")}}), quando a {{domxref("Blob")}} ou {{domxref("File")}} é passado como o segundo parametro. O default filename para  {{domxref("Blob")}} o objecto é "blob".
+
+ +
+

Nota: Se espisificares  {{domxref("Blob")}} como a data append  para o objecto FormData , o filename a ser reportado para o servidor  no "Content-Disposition" header usado para mudar de browser em browser.

+
+ +

Retorna

+ +

Void.

+ +

Exemplo

+ +

As seguintes linhas criam um Objecto FormData vazio:

+ +
var formData = new FormData(); // Corrente vazio
+ +

Podes adicionar chaves/valores pares para usar (domxref("FormData.append")}}:

+ +
formData.append('username', 'Chris');
+formData.append('userpic', myFileInput.files[0], 'chris.jpg');
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçõesEstatoComentario
{{SpecName('XMLHttpRequest','#dom-formdata-append','append()')}}{{Spec2('Fetch')}} 
+ +

Compatibilidade do Browser

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracteristicasChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte Basico7+{{CompatGeckoDesktop("2.0")}}10+12+5+
append com filename{{CompatVersionUnknown}}{{CompatGeckoDesktop("22.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Disponivel para Desenvolvedores Web{{CompatVersionUnknown}}{{CompatGeckoDesktop("39.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracteristicasAndroidChrome para AndroidFirefox Mobile (Gecko)Firefox OS (Gecko)IE MobileOpera MobileSafari Mobile
Basic support3.0{{CompatUnknown}}{{CompatGeckoMobile("2.0")}}1.0.1{{CompatUnknown}} +

12+

+
{{CompatUnknown}}
append com filename{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop("22.0")}}1.2{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Disponivel para Desenvolvedores Web{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop("39.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+

Nota: XHR em  Android 4.0 envia conteudo vazio  para FormData com blob.

+
+ +

Notas Gecko

+ +

Antis do Gecko 7.0 {{geckoRelease("7.0")}}, se especificares {{domxref("Blob")}} como a conteudo a ser  adicionado ao objecto, o filename reportado no "Content-Disposition" HTTP header era um string vazio; este resulta em  erros sendo reportados por alguns servidores. Começando com Gecko 7.0, o filename "blob" é enviado.

+ +

Veja Tambem

+ + diff --git a/files/pt-br/web/api/formdata/delete/index.html b/files/pt-br/web/api/formdata/delete/index.html new file mode 100644 index 0000000000..042c16f083 --- /dev/null +++ b/files/pt-br/web/api/formdata/delete/index.html @@ -0,0 +1,138 @@ +--- +title: FormData.delete() +slug: Web/API/FormData/delete +translation_of: Web/API/FormData/delete +--- +

{{APIRef("XMLHttpRequest")}}

+ +

O metodo delete() da  interface {{domxref("FormData")}} deleta uma chave/valor pares do Objecto FormData .

+ +
+

Nota: Este metodo esta Disponivel em Web Workers.

+
+ +

Sintaxe

+ +
formData.delete(name);
+ +

Parametros

+ +
+
name
+
O name da chave que desejas apagar.
+
+ +

Retorna

+ +

Void.

+ +

Exemplo

+ +

Esta linha cria um objecto FormData vazio e subistitui com a chave/valor pares de  form:

+ +
var formData = new FormData(myForm);
+ +

Podes deletar chave/valor pares usando delete():

+ +
formData.delete('username');
+
+ +

Specificasões

+ + + + + + + + + + + + + + +
SpecificasõesStatusComment
{{SpecName('XMLHttpRequest','#dom-formdata-delete','delete()')}}{{Spec2('XMLHttpRequest')}} 
+ +

Compatibilidade do Browser 

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
CarracteristicasChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte Basico{{CompatVersionUnknown}}{{CompatGeckoDesktop("39.0")}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}
Disponivel em Web Workes{{CompatVersionUnknown}}{{CompatGeckoDesktop("39.0")}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracteristicasAndroidChrome for AndroidFirefox Mobile (Gecko)Firefox OS (Gecko)IE MobileOpera MobileSafari Mobile
Suporte Basico{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}} +

{{CompatVersionUnknown}}

+
{{CompatNo}}
Disponivel em web workers{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}
+
+ +

Veja Tambem

+ + diff --git a/files/pt-br/web/api/formdata/entries/index.html b/files/pt-br/web/api/formdata/entries/index.html new file mode 100644 index 0000000000..911c269074 --- /dev/null +++ b/files/pt-br/web/api/formdata/entries/index.html @@ -0,0 +1,77 @@ +--- +title: FormData.entries() +slug: Web/API/FormData/entries +tags: + - API + - FormData + - Iterador + - Referencia + - XMLHttpRequest API + - metodo +translation_of: Web/API/FormData/entries +--- +

{{APIRef("XMLHttpRequest")}}

+ +

O método FormData.entries() retorna um {{jsxref("Iteration_protocols",'iterator')}} permitindo percorrer todos os valores de chave/valor contidos nesse objeto. A chave de cada par é um objeto {{domxref("USVString")}}; o valor é {{domxref("USVString")}}, ou um {{domxref("Blob")}}.

+ +
+

Note: This method is available in Web Workers.

+
+ +

Sintaxe

+ +
formData.entries();
+ +

Valor retornado

+ +

Retorna um {{jsxref("Iteration_protocols","iterator")}}.

+ +

Exemplo

+ +
// Criação de um objeto teste de FormData
+var formData = new FormData();
+formData.append('key1', 'value1');
+formData.append('key2', 'value2');
+
+// Exibição dos valores chave/valor
+for(var pair of formData.entries()) {
+   console.log(pair[0]+ ', '+ pair[1]);
+}
+
+ +

O resultado é:

+ +
key1, value1
+key2, value2
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('XMLHttpRequest','#dom-formdata','entries() (as iterator<>)')}}{{Spec2('XMLHttpRequest')}}Initial definition
+ +

Compatibilidade de navegadores

+ + + +

{{Compat("api.FormData.entries")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/formdata/formdata/index.html b/files/pt-br/web/api/formdata/formdata/index.html new file mode 100644 index 0000000000..2202cac454 --- /dev/null +++ b/files/pt-br/web/api/formdata/formdata/index.html @@ -0,0 +1,184 @@ +--- +title: FormData() +slug: Web/API/FormData/FormData +translation_of: Web/API/FormData/FormData +--- +

{{APIRef("XMLHttpRequest")}}

+ +

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

+ +
+

Nota: Este recurso está disponível em Web Workers.

+
+ +

Sintaxe

+ +
var formData = new FormData(form)
+ +

Parâmetros

+ +
+
form {{optional_inline}}
+
Um elemento HTML {{HTMLElement("form")}} — quando especifico, o objeto {{domxref("FormData")}} será preenchido com as chaves/valores atuais do formulário usando a propriedade name de cada elemento para as chaves e seu valor enviado para os valores. Também condificará conteúdo de entrada do arquivo.
+
+ +

Exemplo

+ +

A linha a seguir cria um objeto FormData vázio:

+ +
var formData = new FormData(); // Currently empty
+ +

Você poderia adicionar uma chave/valor usando {{domxref("FormData.append")}}:

+ +
formData.append('username', 'Chris');
+
+ +

Ou você pode especificicar o opcional form argument ao criar o objeto FormData, para o popular com valores de forma especifica:

+ +
<form id="myForm" name="myForm">
+  <div>
+    <label for="username">Enter name:</label>
+    <input type="text" id="username" name="username">
+  </div>
+  <div>
+    <label for="useracc">Enter account number:</label>
+    <input type="text" id="useracc" name="useracc">
+  </div>
+  <div>
+    <label for="userfile">Upload file:</label>
+    <input type="file" id="userfile" name="userfile">
+  </div>
+<input type="submit" value="Submit!">
+</form>
+
+ +
+

Nota: Todos os elementos de entrada têm um atributo 'name'. Para que possa acessar seus valores mais tarde.

+
+ +
var myForm = document.getElementById('myForm');
+formData = new FormData(myForm);
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('XMLHttpRequest','#dom-formdata','FormData()')}}{{Spec2('XMLHttpRequest')}}Definição inicial
+ +

Compatibilidade dos navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support7{{CompatGeckoDesktop("2.0")}}10125
append with filename{{CompatVersionUnknown}}{{CompatGeckoDesktop("22.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
available in web workers{{CompatVersionUnknown}}{{CompatGeckoDesktop("39.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support3.0{{CompatUnknown}}{{CompatGeckoMobile("2.0")}}{{CompatUnknown}} +

12

+
{{CompatUnknown}}
append with filename{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("22.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Available in web workers{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("39.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+ +

 

+ +
+

Note: XHR in Android 4.0 sends empty content for FormData with blob.

+
+ +

Gecko notes

+ +

Prior to Gecko 7.0 {{geckoRelease("7.0")}}, if you specified a {{domxref("Blob")}} as the data to append to the object, the filename reported in the "Content-Disposition" HTTP header was an empty string; this resulted in errors being reported by some servers. Starting in Gecko 7.0, the filename "blob" is sent.

+ +

Veja também

+ + +
diff --git a/files/pt-br/web/api/formdata/get/index.html b/files/pt-br/web/api/formdata/get/index.html new file mode 100644 index 0000000000..6e4c11caad --- /dev/null +++ b/files/pt-br/web/api/formdata/get/index.html @@ -0,0 +1,142 @@ +--- +title: FormData.get() +slug: Web/API/FormData/get +translation_of: Web/API/FormData/get +--- +

{{APIRef("XMLHttpRequest")}}

+ +

O método get() da interface {{domxref("FormData")}} retorna o primeiro valor associado com a chave fornecida de um objeto do tipo FormData.

+ +
+

Nota: Este método está disponível em Web Workers.

+
+ +

Sintaxe

+ +
formData.get(nome);
+ +

Parâmetros

+ +
+
nome
+
Um {{domxref("USVString")}} representando o nome da chave que queira retornar.
+
+ +

Retorno

+ +

Um {{domxref("FormDataEntryValue")}} contendo o valor.

+ +

Exemplo

+ +

A linha abaixo cria um objeto vazio do tipo FormData.

+ +
var formData = new FormData();
+ +

Se adicionarmos dois valores usuario_nome usando {{domxref("FormData.append")}}:

+ +
formData.append('usuario_nome', 'Sabrina');
+formData.append('usuario_nome', 'Antônio');
+ +

A função get() abaixo apenas irá retornar o primeiro valor usuario_nome incluido:

+ +
formData.get('usuario_nome'); // Retorna "Sabrina"
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('XMLHttpRequest','#dom-formdata-get','get()')}}{{Spec2('XMLHttpRequest')}} 
+ +

Compatibilidade de navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
RecursoChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatNo}}{{CompatGeckoDesktop('39.0')}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}
Available in web workers{{CompatNo}}{{CompatGeckoDesktop('39.0')}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
RecursoAndroidChrome for AndroidFirefox Mobile (Gecko)Firefox OS (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}} +

{{CompatVersionUnknown}}

+
{{CompatNo}}
Available in web workers{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/formdata/getall/index.html b/files/pt-br/web/api/formdata/getall/index.html new file mode 100644 index 0000000000..5a9b51611c --- /dev/null +++ b/files/pt-br/web/api/formdata/getall/index.html @@ -0,0 +1,74 @@ +--- +title: FormData.getAll() +slug: Web/API/FormData/getAll +translation_of: Web/API/FormData/getAll +--- +

{{APIRef("XMLHttpRequest")}}

+ +

O metodo getAll() do {{domxref("FormData")}} retorna todos os valores associados com a chave dentro de um objeto FormData.

+ +
+

Nota: Este metodo esta disponivel no Web Workers.

+
+ +

Syntax

+ +
formData.getAll(name);
+ +

Parametros

+ +
+
nome
+
O {{domxref("USVString")}} representa o mome da chave que você quer pegar.
+
+ +

Retorno

+ +

Um array de {{domxref("FormDataEntryValue")}}s.

+ +

Examplo

+ +

A seguinte linha cria um objeto FormData vazio:

+ +
var formData = new FormData();
+ +

Se nos adicionarmos dois valores oara username {{domxref("FormData.append")}}:

+ +
formData.append('username', 'Chris');
+formData.append('username', 'Bob');
+ +

A seguinte função getAll() retornara um arrat com os valore dentro de username:

+ +
formData.getAll('username'); // Returns ["Chris", "Bob"]
+ +

Especificação

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('XMLHttpRequest','#dom-formdata-getall','getAll()')}}{{Spec2('XMLHttpRequest')}} 
+ +

Compatibilidade de Browsers

+ + + +

{{Compat("api.FormData.getAll")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/formdata/has/index.html b/files/pt-br/web/api/formdata/has/index.html new file mode 100644 index 0000000000..d9cdeff60b --- /dev/null +++ b/files/pt-br/web/api/formdata/has/index.html @@ -0,0 +1,81 @@ +--- +title: FormData.has() +slug: Web/API/FormData/has +tags: + - API + - FormData + - Referencia + - XHR + - XMLHttlRequest + - has + - metodo +translation_of: Web/API/FormData/has +--- +

{{APIRef("XMLHttpRequest")}}

+ +

O método has() da interface {{domxref("FormData")}} retorna um booleano declarando se o objeto FormData contém uma certa chave.

+ +
+

Note: This method is available in Web Workers.

+
+ +

Sintaxe

+ +
formData.has(name);
+ +

Parâmetros

+ +
+
name
+
Uma {{domxref("USVString")}} que representa o nome da chave que você que testar.
+
+ +

Retorna

+ +

Um {{domxref("Boolean")}}.

+ +

Exemplo

+ +

A linha a seguir cria um objeto FormData vazio:

+ +
var formData = new FormData();
+ +

O trecho a seguir mostra os resultados de testar a existência de username no objeto FormData, antes e depois de acrescentar um valor de username no objeto usando {{domxref("FormData.append")}}:

+ +
formData.has('username'); // Retorna false
+formData.append('username', 'Chris');
+formData.has('username'); // Retorna true
+
+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('XMLHttpRequest','#dom-formdata-has','has()')}}{{Spec2('XMLHttpRequest')}}
+ +

Compatibilidade de navegador

+ + + +

{{Compat("api.FormData.has")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/formdata/index.html b/files/pt-br/web/api/formdata/index.html new file mode 100644 index 0000000000..30ba7ccb6a --- /dev/null +++ b/files/pt-br/web/api/formdata/index.html @@ -0,0 +1,170 @@ +--- +title: FormData +slug: Web/API/FormData +translation_of: Web/API/FormData +--- +

{{APIRef("XMLHttpRequest")}}

+ +

A interface FormData fornece uma maneira fácil de construir um conjunto de pares chave/valor representando campos de um elemento form e seus valores, os quais podem ser facilmente enviados utilizado o método send() do XMLHttpRequest. Essa interface utiliza o mesmo formato que um form utilizaria se o tipo de codificação estivesse configurado como "multipart/form-data".

+ +

Um objeto FormData pode ser usado diretamente em uma estrutura {{jsxref("Statements/for...of", "for...of")}} em vez de {{domxref('FormData.entries()', 'entries()')}}: for (var p of myFormData) é o mesmo que for (var p of myFormData.entries()).

+ +
+

Nota: Esse recurso está disponível em https://developer.mozilla.org/pt-BR/docs/Web/API/Web_Workers_API

+
+ +

Construtor

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

Métodos

+ +
+
{{domxref("FormData.append")}}
+
Acrescenta um novo valor em uma chave existente dentro de um objeto FormData, ou adiciona a chave se ela ainda não existir.
+
{{domxref("FormData.delete")}}
+
Apaga um par chave/valor de um objeto FormData.
+
{{domxref("FormData.get")}}
+
Retorna o primeiro valor associado com uma dada chave de dentro de um objeto FormData.
+
{{domxref("FormData.getAll")}}
+
Retorna uma matriz de todos os valores associados a uma determinada chave de dentro de um FormData.
+
{{domxref("FormData.has")}}
+
Retorna um valor boleano indicando se um objeto FormData contém um certo par chave/valor.
+
{{domxref("FormData.set")}}
+
Define um novo valor para uma chave existente dentro de um objeto FormData, ou adiciona a chave/valor se ele ainda não existir.
+
+ +
+

Nota: Para ser claro, a diferença entre {{domxref("FormData.set()")}} e {{domxref("FormData.append()")}} é que, se a chave especificada não existir, {{domxref("FormData.set()")}} irá substituir o valor existente por um novo, enquanto {{domxref("FormData.append()")}} irá acrescentar um novo valor no final dos valores existentes. Veja as suas páginas dedicadas para código de exemplo.

+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('XMLHttpRequest','#interface-formdata','FormData')}}{{Spec2('XMLHttpRequest')}}FormData definido na especificação XHR
+ +

Compatibilidade com navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico7+{{CompatGeckoDesktop("2.0")}}10+12+5+
append com filename{{CompatVersionUnknown}}{{CompatGeckoDesktop("22.0")}}10+{{CompatUnknown}}{{CompatUnknown}}
delete, get, getAll, has, setBehind Flag{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome for AndroidFirefox Mobile (Gecko)Firefox OS (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico3.0{{CompatUnknown}}{{CompatGeckoMobile("2.0")}}1.0.1{{CompatUnknown}} +

12+

+
{{CompatUnknown}}
append com filename{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop("22.0")}}1.2{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
delete, get, getAll, has, set{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}
+
+ +
+

Nota: XHR in Android 4.0 envia conteúdo vazio para o FormData com blob.

+ +

Nota: Suporte do Chrome aos métodos que não seja append está atualmente atrás da bandeira "Enable Experimental Web Platform Features".

+
+ +

Notas da Gecko

+ +

Antes do Gecko 7.0 {{geckoRelease("7.0")}}, se você especificasse um {{domxref("Blob")}} como o dado a ser anexado ao objeto, o nome do arquivo relatado no cabeçalho HTTP "Content-Disposition" era uma string vazia; isso resultou em erros sendo relatados por alguns servidores. Começando em Gecko 7.0, o nome do arquivo "blob" é enviado.

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/formdata/set/index.html b/files/pt-br/web/api/formdata/set/index.html new file mode 100644 index 0000000000..a6b7dccb69 --- /dev/null +++ b/files/pt-br/web/api/formdata/set/index.html @@ -0,0 +1,150 @@ +--- +title: FormData.set() +slug: Web/API/FormData/set +translation_of: Web/API/FormData/set +--- +

{{APIRef("XMLHttpRequest")}}

+ +

O método set() da interface {{domxref("FormData")}} adiciona o novo valor para um chave existente em um objeto FormData, ou adicionar a combinação chave/valor caso ela não exista.

+ +

A diferença entre  set() e {{domxref("FormData.append")}} é que, se a chave especificada já existir, set() irá sobrescrever todos os valores existentes pelo novo valor, enquanto o {{domxref("FormData.append")}} apenas acrescenta o novo valor ao conjunto de valores existentes.

+ +
+

Nota: Esse método está disponível em Web Workers.

+
+ +

Sintaxe

+ +

Existem duas versões desse método: uma com dois e outra com três parâmetros:

+ +
formData.set(name, value);
+formData.set(name, value, filename);
+ +

Parâmetros

+ +
+
name
+
O nome do campo cujo dado está em value.
+
value
+
O valor do campo. Na versão de dois parâmetros, esse é um {{domxref("USVString")}}, e caso não seja, ele é convertido para uma string. Na versão de três parâmetros ele pode ser um {domxref("Blob")}}, {{domxref("File")}}, ou um {{domxref("USVString")}}. Se nenhum desses valores forem especificados, o valor será convertido para string.
+
filename {{optional_inline}}
+
O nome do arquivo a ser enviado (um {{domxref("USVString")}}), quando um {{domxref("Blob")}} ou um {{domxref("File")}} é passdo como o segundo parâmetro. O nome de arquivo padrão para objetos do tipo {{domxref("Blob")}} é "blob".
+
+ +
+

Nota: Se você especificar um {{domxref("Blob")}} como o dado a ser acrescentado ao objeto FormData, o nome do arquivo que será enviado para o servidor, enviado no atributo "Content-Disposition" no cabeçalho varia de navegador para navegador.

+
+ +

Exemplo

+ +

A linha a seguir cria um objeto FormData vazio:

+ +
var formData = new FormData(); // Currently empty
+ +

Você pode adicionar os pares chave/valor usando (domxref("FormData.set")}}:

+ +
formData.set('username', 'Chris');
+formData.set('userpic', myFileInput.files[0], 'chris.jpg');
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('XMLHttpRequest','#dom-formdata-set','set()')}}{{Spec2('XMLHttpRequest')}} 
+ +

Compatibilidade de navegador

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatChrome(50.0)}}{{CompatGeckoDesktop("39.0")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
DIsponível para web workers{{CompatChrome(50.0)}}{{CompatGeckoDesktop("39.0")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OS (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Suporte básico{{CompatNo}}{{CompatChrome(50.0)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}} +

{{CompatNo}}

+
{{CompatNo}}{{CompatChrome(50.0)}}
DIsponível para web workers{{CompatNo}}{{CompatChrome(50.0)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatChrome(50.0)}}
+
+ +

Ver também

+ + diff --git a/files/pt-br/web/api/fullscreenoptions/index.html b/files/pt-br/web/api/fullscreenoptions/index.html new file mode 100644 index 0000000000..9a85830521 --- /dev/null +++ b/files/pt-br/web/api/fullscreenoptions/index.html @@ -0,0 +1,29 @@ +--- +title: FullscreenOptions +slug: Web/API/FullscreenOptions +translation_of: Web/API/FullscreenOptions +--- +

{{APIRef("Fullscreen API")}}

+ +

O dicionário FullscreenOptions é usado para prover configurações quando chamado {{DOMxRef("Element.requestFullscreen", "requestFullscreen()")}} em um elemento para colocar este elmento em modo full-screen (tela inteira).

+ +

Propriedades

+ +
+
{{DOMxRef("FullscreenOptions.navigationUI", "navigationUI")}}{{Optional_Inline}}
+
Uma string controlando se deve ou não manter elementos da interface do usuário do navegador visíveis enquanto estiver no modo full-screen. O modo padrão, "auto", deixa que o navegador faça esta decisão.
+
+ +

Compatibilidade dos Navegadores

+ + + +

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

+ +

Veja Também

+ + diff --git a/files/pt-br/web/api/gamepad_api/index.html b/files/pt-br/web/api/gamepad_api/index.html new file mode 100644 index 0000000000..fe026468d8 --- /dev/null +++ b/files/pt-br/web/api/gamepad_api/index.html @@ -0,0 +1,90 @@ +--- +title: Gamepad API +slug: Web/API/Gamepad_API +translation_of: Web/API/Gamepad_API +--- +
{{DefaultAPISidebar("Gamepad API")}}
+ +

A Gamepad API é uma maneira dos desenvolvedores acessarem e responderem à sinais oriundos de gamepads e outros controladores de games de forma simples e consistente. A API contém três interfaces, dois eventos e uma função especialista, para responder aos gamepads sendo conectados e desconectados, e acessar outras informações sobre o próprio gamepad, e quais botões e outros controles estão sendo de fato passados.

+ +

Interfaces

+ +
+
Gamepad
+
Representa o gamepad/controlador conectado ao computador.
+
GamepadButton
+
Representa um botão num dos controles conectados.
+
GamepadEvent
+
O objeto de evento representando eventos disparados que são relacionados ao gamepad.
+
+ +

Experimental Gamepad extensions

+ +
+
GamepadHapticActuator
+
Representa o hardware no controlador designado à prover feedbacks táteis ao usuário (Se disponível), mais comumente um hardware de vibração.
+
GamepadPose
+
Representa a "localização" de um controle (ex. posição e orientação no espaço 3D) no caso de um controlador WebVR.
+
+ +

Veja também as extensões para a interface de Gamepad, para funcionalidades que permitem você acessar as informações acima.

+ +

Extensions to other interfaces

+ + + +
+
{{domxref("Navigator.getGamepads()")}}
+
Uma extensão para o objeto {{domxref("Navigator")}} que retorna um array  de objetos {{domxref("Gamepad")}}, um para cada controlador conectado.
+
+ +

Window events

+ +
+
{{domxref("Window.ongamepadconnected")}}
+
Representa um controlador de evento que irá rodar quando o gamepad é conectado (quando o evento {{event('gamepadconnected')}} for disparado).
+
{{domxref("Window.ongamepaddisconnected")}}
+
Representa um controlador de evento que irá rodar quando o gamepad é desconectado (quando o evento {{event('gamepaddisconnected')}} for disparado).
+
+ +

Guias e tutorias

+ + + +

Especificações

+ + + + + + + + + + + + + + + + + + + +
EspecificaçõesEstatusComentários
{{SpecName("GamepadExtensions")}}{{Spec2("GamepadExtensions")}}Defines the {{anch("Experimental Gamepad extensions")}}.
{{SpecName("Gamepad", "", "The Gamepad API specification")}}{{Spec2("Gamepad")}}Initial definition
+ +

Compatibilidade de navegadores

+ + + +

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

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/geolocation/clearwatch/index.html b/files/pt-br/web/api/geolocation/clearwatch/index.html new file mode 100644 index 0000000000..2aaa1d6658 --- /dev/null +++ b/files/pt-br/web/api/geolocation/clearwatch/index.html @@ -0,0 +1,84 @@ +--- +title: Geolocation.clearWatch() +slug: Web/API/Geolocation/clearWatch +translation_of: Web/API/Geolocation/clearWatch +--- +

{{securecontext_header}}{{ APIref("Geolocation API") }}

+ +

O método Geolocation.clearWatch() é usado para cancelar o registro dos manipuladores de monitoramento de localização / erro instalados anteriormente usando {{domxref("Geolocation.watchPosition()")}}.

+ +

Syntax

+ +
navigator.geolocation.clearWatch(id);
+ +

Parameters

+ +
+
id
+
O número do ID retornado pelo método {{domxref("Geolocation.watchPosition()")}} ao instalar o manipulador que você deseja remover.
+
+ +

Exemplo

+ +
var id, target, option;
+
+function success(pos) {
+  var crd = pos.coords;
+
+  if (target.latitude === crd.latitude && target.longitude === crd.longitude) {
+    console.log('Congratulation, you reach the target');
+    navigator.geolocation.clearWatch(id);
+  }
+};
+
+function error(err) {
+  console.warn('ERROR(' + err.code + '): ' + err.message);
+};
+
+target = {
+  latitude : 0,
+  longitude: 0,
+}
+
+options = {
+  enableHighAccuracy: false,
+  timeout: 5000,
+  maximumAge: 0
+};
+
+id = navigator.geolocation.watchPosition(success, error, options);
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Geolocation')}}{{Spec2('Geolocation')}}Initial specification.
+ +

Compatibiliade dos Navegadores

+ + + +

{{Compat("api.Geolocation.clearWatch")}}

+ +

Veja Também

+ + diff --git a/files/pt-br/web/api/geolocation/getcurrentposition/index.html b/files/pt-br/web/api/geolocation/getcurrentposition/index.html new file mode 100644 index 0000000000..c5aa7919f6 --- /dev/null +++ b/files/pt-br/web/api/geolocation/getcurrentposition/index.html @@ -0,0 +1,127 @@ +--- +title: Geolocation.getCurrentPosition() +slug: Web/API/Geolocation/getCurrentPosition +translation_of: Web/API/Geolocation/getCurrentPosition +--- +

{{ APIRef("Geolocation API") }}

+ +

O método Geolocation.getCurrentPosition() é utilizado para capturar a posição atual do dispositivo.

+ +

Sintaxe

+ +
navigator.geolocation.getCurrentPosition(success, error, options)
+ +

Parâmetros

+ +
+
success
+
Uma função de retorno que captura um objeto {{domxref("Position")}} como seu parâmetro de entrada.
+
error {{optional_inline}}
+
Uma função de retorno opcional que captura um objeto {{domxref ("PositionError")}} como seu parâmetro de entrada.
+
options {{optional_inline}}
+
Um objeto opcional {{domxref("PositionOptions")}}.
+
+ +

Exemplo

+ +
var options = {
+  enableHighAccuracy: true,
+  timeout: 5000,
+  maximumAge: 0
+};
+
+function success(pos) {
+  var crd = pos.coords;
+
+  console.log('Sua posição atual é:');
+  console.log('Latitude : ' + crd.latitude);
+  console.log('Longitude: ' + crd.longitude);
+  console.log('Mais ou menos ' + crd.accuracy + ' metros.');
+};
+
+function error(err) {
+  console.warn('ERROR(' + err.code + '): ' + err.message);
+};
+
+navigator.geolocation.getCurrentPosition(success, error, options);
+
+ +

Especificações

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

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico5{{CompatGeckoDesktop("1.9.1")}}910.60
+ Removido no 15.0
+ Reintroduzido no 16.0
5
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatUnknown()}}{{CompatUnknown()}}{{CompatGeckoMobile("4")}}{{CompatUnknown()}}10.60{{CompatUnknown()}}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/geolocation/index.html b/files/pt-br/web/api/geolocation/index.html new file mode 100644 index 0000000000..4ca0efa69a --- /dev/null +++ b/files/pt-br/web/api/geolocation/index.html @@ -0,0 +1,75 @@ +--- +title: Geolocation +slug: Web/API/Geolocation +tags: + - API + - Geolocalização + - Geolocation + - Geolocation API +translation_of: Web/API/Geolocation +--- +
{{APIRef("Geolocation API")}}
+ +

A interface Geolocation representa um objeto ábil de programaticamente obter a posição do aparelho. Dá ao conteúdo web acesso à localização do aparelho. Isto permite com que o website ou a aplicação ofereça resultados customizados baseados na localização do usuário.

+ +

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

+ +
+

Nota: Por questões de segurança, quando uma página tenta obter acesso às informações de localização o usuário é notificado e uma requisição é feita para o mesmo fornecesser a permissão. Saiba que cada navegaor possui suas próprias políticas e métodos para requisitar tal permissão.

+
+ +

Propriedades

+ +

A interface Geolocation não implementa nem herda qualquer propriedade.

+ +

Métodos

+ +

A interface Geolocation não herda qualquer métodos.

+ +
+
{{domxref("Geolocation.getCurrentPosition()")}}
+
Determina a posição atual do aparelho e retorna um objeto {{domxref("Position")}} com os dados.
+
{{domxref("Geolocation.watchPosition()")}}
+
Retorna um valor long representando a nova função de callback estabelecida para ser invocada a qualquer momento que o localização do aparelho alterar-se.
+
{{domxref("Geolocation.clearWatch()")}}
+
Remove qualquer encarregado previamente instalado usando watchPosition().
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('Geolocation')}}{{Spec2('Geolocation')}}Especificação Inicial
+ +

Compatibilidade dos navegadores

+ +

 

+ + + +

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

+ +

 

+ +
 
+ +

Veja Também

+ + diff --git a/files/pt-br/web/api/geolocation/watchposition/index.html b/files/pt-br/web/api/geolocation/watchposition/index.html new file mode 100644 index 0000000000..ffabaa2c76 --- /dev/null +++ b/files/pt-br/web/api/geolocation/watchposition/index.html @@ -0,0 +1,140 @@ +--- +title: Geolocation.watchPosition() +slug: Web/API/Geolocation/watchPosition +translation_of: Web/API/Geolocation/watchPosition +--- +

{{ APIref("Geolocation API") }}

+ +

O método Geolocation.watchPosition() é usado para registrar uma função manipuladora (handler function) que irá ser chamada automáticamente  cada vez que a posição no dispositivo mudar. Você pode, opcionalemnte, especificar uma função de retorno que manipulará qualquer erro.

+ +

Este método retorna um valor para o watch ID que pode ser usado para desregistrar o manipulador passando isto para o método {{domxref("Geolocation.clearWatch()")}}.

+ +

Síntaxe

+ +
id = navigator.geolocation.watchPosition(success, error, options)
+ +

Parâmetros

+ +
+
success
+
AUma função de retorno (callback) que pega um objeto {{domxref("Position")}} como parametro de entrada.  
+
error {{optional_inline}}
+
Uma função de retorno opcional que pega um objeto {{domxref("PositionError")}} como parametro de entrada.  
+
options {{optional_inline}}
+
Um objeto opcional {{domxref("PositionOptions")}}.
+
+ +

Exemplo

+ +
var id, target, options;
+
+function success(pos) {
+  var crd = pos.coords;
+
+  if (target.latitude === crd.latitude && target.longitude === crd.longitude) {
+    console.log('Parabéns, você alcançou o destino');
+    navigator.geolocation.clearWatch(id);
+  }
+}
+
+function error(err) {
+  console.warn('ERRO(' + err.code + '): ' + err.message);
+}
+
+target = {
+  latitude : 0,
+  longitude: 0
+};
+
+options = {
+  enableHighAccuracy: false,
+  timeout: 5000,
+  maximumAge: 0
+};
+
+id = navigator.geolocation.watchPosition(success, error, options);
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('Geolocation', '#watch-position', 'Geolocation.watchPosition()')}}{{Spec2('Geolocation')}}Especificação Inicial.
+ +

Compatibillidade de Navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico5{{CompatGeckoDesktop("1.9.1")}}910.60
+ Removido no 15.0
+ Reintroduzido no 16.0
5
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatUnknown()}}{{CompatUnknown()}}{{CompatGeckoMobile("4")}}{{CompatUnknown()}}10.60{{CompatUnknown()}}
+
+ +

 

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/geolocationcoordinates/altitude/index.html b/files/pt-br/web/api/geolocationcoordinates/altitude/index.html new file mode 100644 index 0000000000..b4b7850bf9 --- /dev/null +++ b/files/pt-br/web/api/geolocationcoordinates/altitude/index.html @@ -0,0 +1,45 @@ +--- +title: Coordinates.altitude +slug: Web/API/GeolocationCoordinates/altitude +translation_of: Web/API/GeolocationCoordinates/altitude +--- +
{{securecontext_header}}{{APIRef("Geolocation API")}}
+ +

A propriedade Coordinates.altitude somente-leitura é uma representação do tipo double da altitude em metros, relativo ao nível do mar. O valor é nulo se a implementação não pode fornecer este dado.

+ +

Sintaxe

+ +
alt = coordinates.altitude
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Geolocation', '#altitude', 'Coordinates.altitude')}}{{Spec2('Geolocation')}}Initial definition
+ +

Compatibilidade entre os navegadores

+ + + +

{{Compat("api.Coordinates.altitude")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/geolocationcoordinates/index.html b/files/pt-br/web/api/geolocationcoordinates/index.html new file mode 100644 index 0000000000..2263a8117a --- /dev/null +++ b/files/pt-br/web/api/geolocationcoordinates/index.html @@ -0,0 +1,141 @@ +--- +title: Coordinates +slug: Web/API/GeolocationCoordinates +translation_of: Web/API/GeolocationCoordinates +--- +
+
{{securecontext_header}}{{APIRef("Geolocation API")}}
+ +

Coordinates iinterface representa a posição e a altitude do dispositivo na Terra, bem como a precisão com que essas propriedades são calculadas.

+ +

Propriedades

+ +

A interface do Coordinates não herda nenhuma propiedade.

+ +
+
{{domxref("Coordinates.latitude")}} {{readonlyInline}} {{securecontext_inline}}
+
Retorna um double representando a latitude da posição em graus decimais.
+
{{domxref("Coordinates.longitude")}} {{readonlyInline}} {{securecontext_inline}}
+
Retorna um double representando a longitude da posição em graus decimais.
+
{{domxref("Coordinates.altitude")}} {{readonlyInline}} {{securecontext_inline}}
+
Retorna um double representando a altitude da posição em metros, em relação ao nível do mar. Esse valor pode ser null se a implementação não puder fornecer os dados.
+
{{domxref("Coordinates.accuracy")}} {{readonlyInline}} {{securecontext_inline}}
+
Retorna um double representação da precisão das propriedades em latitude e longitude, expressa em metros.
+
{{domxref("Coordinates.altitudeAccuracy")}} {{readonlyInline}} {{securecontext_inline}}
+
Retorna um double representação da precisão da altitude expressa em metros. Esse valor pode ser null.
+
{{domxref("Coordinates.heading")}} {{readonlyInline}} {{securecontext_inline}}
+
Retorna um double representação da direção na qual o dispositivo está viajando. Esse valor, especificado em graus, indica o quão longe do título verdadeiro do norte do dispositivo. 0 representam o verdadeiro norte e a direção é determinada no sentido horário (o que significa que o leste é 90graus e oeste é 270graus). Se speedé 0headingé NaNSe o dispositivo não conseguir fornecer headinginformações, esse valor é null.
+
{{domxref("Coordinates.speed")}} {{readonlyInline}} {{securecontext_inline}}
+
Retorna um doublerepresentação da velocidade do dispositivo em metros por segundo. Esse valor pode ser null.
+
+ +

Métodos

+ +

A interface da Coordinates não implementa, nem herda nenhum método.

+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Geolocation', '#coordinates', 'Coordinates')}}{{Spec2('Geolocation')}}Especificação inicial.
+ +

Browser compatibility

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico5{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.1")}}910.60
+ Removed in 15.0
+ Reintroduced in 16.0
5
Apenas contexto seguro47{{CompatUnknown()}}{{CompatGeckoDesktop("55")}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatUnknown()}}{{CompatUnknown()}}{{CompatVersionUnknown}}{{CompatGeckoMobile("4")}}{{CompatUnknown()}}10.60{{CompatUnknown()}}
Apenas contexto seguro{{CompatNo}}47{{CompatUnknown()}}{{CompatGeckoDesktop("55")}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Veja também

+ + +
+ + diff --git a/files/pt-br/web/api/geolocationposition/coords/index.html b/files/pt-br/web/api/geolocationposition/coords/index.html new file mode 100644 index 0000000000..d14cbc59a7 --- /dev/null +++ b/files/pt-br/web/api/geolocationposition/coords/index.html @@ -0,0 +1,116 @@ +--- +title: Position.coords +slug: Web/API/GeolocationPosition/coords +translation_of: Web/API/GeolocationPosition/coords +--- +
{{securecontext_header}}{{APIRef("Geolocation API")}}
+ +

A propriedade Position.coords é somente leitura. É um objeto de {{domxref("Coordinates")}} que contém uma representação geográfica: a localização, que é a latitude e longitude na Terra, a altitude e a velocidade do objeto em questão. Também contempla a precisão da informação sobre estes valores.

+ +

Sintaxe

+ +
coord = position.coords
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('Geolocation', '#coords', 'Position.coords')}}{{Spec2('Geolocation')}}Especificação inicial.
+ +

Compatibilidade com navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico5{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.1")}}910.60
+ Removido em 15.0
+ Reintroduzido em 16.0
5
Somente em contexto seguro47{{CompatUnknown()}}{{CompatGeckoDesktop("55")}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatUnknown()}}{{CompatUnknown()}}{{CompatVersionUnknown}}{{CompatGeckoMobile("4")}}{{CompatUnknown()}}10.60{{CompatUnknown()}}
Somente em contexto seguro{{CompatNo}}47{{CompatUnknown()}}{{CompatGeckoDesktop("55")}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/geolocationposition/index.html b/files/pt-br/web/api/geolocationposition/index.html new file mode 100644 index 0000000000..1fb810305d --- /dev/null +++ b/files/pt-br/web/api/geolocationposition/index.html @@ -0,0 +1,61 @@ +--- +title: Position +slug: Web/API/GeolocationPosition +translation_of: Web/API/GeolocationPosition +--- +
{{securecontext_header}}{{APIRef("Geolocation API")}}
+ +

A interface Position representa a posição do dispositivo em questão em um dado momento. A posição, representada por um objeto {{domxref("Coordinates")}}, compreende a posição 2D do dispositivo, em um esferóide representando a Terra, e também inclui sua altitude e velocidade.

+ +

Propriedades

+ +

A interface Position não herda nenhuma propriedade.

+ +
+
{{domxref("Position.coords")}} {{readonlyInline}} {{securecontext_inline}}
+
Retorna um objeto {{domxref("Coordinates")}} definindo a localização atual.
+
{{domxref("Position.timestamp")}} {{readonlyInline}} {{securecontext_inline}}
+
Retorna um {{domxref("DOMTimeStamp")}} representando o momento em que a localização foi detectada.
+
+ +

Métodos

+ +

A inteface Position não implementa ou herda nenhum método.

+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('Geolocation', '#position', 'Position')}}{{Spec2('Geolocation')}}Especificação inicial.
+ +

Compatibilidade com navegadores

+ +

 

+ + + +

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

+ +
 
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/geolocationpositionerror/index.html b/files/pt-br/web/api/geolocationpositionerror/index.html new file mode 100644 index 0000000000..d5f5ec0f96 --- /dev/null +++ b/files/pt-br/web/api/geolocationpositionerror/index.html @@ -0,0 +1,128 @@ +--- +title: PositionError +slug: Web/API/GeolocationPositionError +translation_of: Web/API/GeolocationPositionError +--- +
{{APIRef("Geolocation API")}}
+ +

A interface PositionError representa a rasão de um erro ocorrer quando usando o dispositivo de geolocalização.

+ +

Propriedades

+ +

A interface PositionError não herda nenhuma propriedade.

+ +
+
{{domxref("PositionError.code")}} {{readonlyInline}}
+
Retorna um tipo unsigned short representando o código de erro. Os valores possíveis são os seguintes: + + + + + + + + + + + + + + + + + + + + + + + +
ValorConstante associadaDescrição
1PERMISSION_DENIEDNão foi possível obter a informação sobre geolocalização por que a página não possuía permissão para fazê-lo.
2POSITION_UNAVAILABLEA obtenção da geolocalização falhou por que pelo menos uma fonte interna de posicionamento retornou um erro interno.
3TIMEOUTO tempo máximo permitido para obter a geolocalização, definido por {{domxref("PositionOptions.timeout")}} foi atingido antes de se obter a informação.
+
+
{{domxref("PositionError.message")}} {{readonlyInline}}
+
Retorna um {{domxref("DOMString")}} humanamente legível descrevendo os detalhes do erro. A especificação observa que esta informação é primariamente projetada para propósitos de debug e não deve ser exibida diretamente na interface com o usuário.
+
+ +

Métodos

+ +

A interface PositionError não implementa nem herda qualquer método.

+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('Geolocation', '#positionerror', 'PositionError')}}{{Spec2('Geolocation')}}Especificação inicial.
+ +

Compatibilidade com navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico5{{CompatGeckoDesktop("1.9.1")}}910.60
+ {{CompatNo}} 15.0
+ 16.0
5
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeAndroidChrome para AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("4")}}{{CompatUnknown}}10.60{{CompatUnknown}}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/globaleventhandlers/index.html b/files/pt-br/web/api/globaleventhandlers/index.html new file mode 100644 index 0000000000..1801888d2b --- /dev/null +++ b/files/pt-br/web/api/globaleventhandlers/index.html @@ -0,0 +1,536 @@ +--- +title: GlobalEventHandlers +slug: Web/API/GlobalEventHandlers +tags: + - API + - DOM + - HTML-DOM + - Mixin + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/API/GlobalEventHandlers +--- +
{{ApiRef("HTML DOM")}}
+ +

The GlobalEventHandlers mixin describes the event handlers common to several interfaces like {{domxref("HTMLElement")}}, {{domxref("Document")}}, or {{domxref("Window")}}. Each of these interfaces can implement more event handlers.

+ +

GlobalEventHandlers is a mixin and not an interface and no object of this type can be created.

+ +

Properties

+ +

The events properties, of the form onXYZ, are defined on the {{domxref("GlobalEventHandlers")}}, and implemented by {{domxref("HTMLElement")}}, {{domxref("Document")}}, {{domxref("Window")}}, and {{domxref("WorkerGlobalScope")}} for Web Workers.

+ +
+
{{domxref("GlobalEventHandlers.onabort")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("abort")}} event is raised.
+
{{domxref("GlobalEventHandlers.onblur")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("blur")}} event is raised.
+
{{domxref("GlobalEventHandlers.onerror")}}
+
Is an {{domxref("OnErrorEventHandler")}} representing the code to be called when the {{event("error")}} event is raised.
+
{{domxref("GlobalEventHandlers.onfocus")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("focus")}} event is raised.
+
{{domxref("GlobalEventHandlers.oncancel")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("cancel")}} event is raised.
+
{{domxref("GlobalEventHandlers.oncanplay")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("canplay")}} event is raised.
+
{{domxref("GlobalEventHandlers.oncanplaythrough")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("canplaythrough")}} event is raised.
+
{{domxref("GlobalEventHandlers.onchange")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("change")}} event is raised.
+
{{domxref("GlobalEventHandlers.onclick")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("click")}} event is raised.
+
{{domxref("GlobalEventHandlers.onclose")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("close")}} event is raised.
+
{{domxref("GlobalEventHandlers.oncontextmenu")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("contextmenu")}} event is raised.
+
{{domxref("GlobalEventHandlers.oncuechange")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("cuechange")}} event is raised.
+
{{domxref("GlobalEventHandlers.ondblclick")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("dblclick")}} event is raised.
+
{{domxref("GlobalEventHandlers.ondrag")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("drag")}} event is raised.
+
{{domxref("GlobalEventHandlers.ondragend")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("dragend")}} event is raised.
+
{{domxref("GlobalEventHandlers.ondragenter")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("dragenter")}} event is raised.
+
{{domxref("GlobalEventHandlers.ondragexit")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("dragexit")}} event is raised.
+
{{domxref("GlobalEventHandlers.ondragleave")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("dragleave")}} event is raised.
+
{{domxref("GlobalEventHandlers.ondragover")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("dragover")}} event is raised.
+
{{domxref("GlobalEventHandlers.ondragstart")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("dragstart")}} event is raised.
+
{{domxref("GlobalEventHandlers.ondrop")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("drop")}} event is raised.
+
{{domxref("GlobalEventHandlers.ondurationchange")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("durationchange")}} event is raised.
+
{{domxref("GlobalEventHandlers.onemptied")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("emptied")}} event is raised.
+
{{domxref("GlobalEventHandlers.onended")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("ended")}} event is raised.
+
{{domxref("GlobalEventHandlers.oninput")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("input")}} event is raised.
+
{{domxref("GlobalEventHandlers.oninvalid")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("invalid")}} event is raised.
+
{{domxref("GlobalEventHandlers.onkeydown")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("keydown")}} event is raised.
+
{{domxref("GlobalEventHandlers.onkeypress")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("keypress")}} event is raised.
+
{{domxref("GlobalEventHandlers.onkeyup")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("keyup")}} event is raised.
+
{{domxref("GlobalEventHandlers.onload")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("load")}} event is raised.
+
{{domxref("GlobalEventHandlers.onloadeddata")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("loadeddata")}} event is raised.
+
{{domxref("GlobalEventHandlers.onloadedmetadata")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("loadedmetadata")}} event is raised.
+
{{domxref("GlobalEventHandlers.onloadstart")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("loadstart")}} event is raised.
+
{{domxref("GlobalEventHandlers.onmousedown")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("mousedown")}} event is raised.
+
{{domxref("GlobalEventHandlers.onmouseenter")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("mouseenter")}} event is raised.
+
{{domxref("GlobalEventHandlers.onmouseleave")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("mouseleave")}} event is raised.
+
{{domxref("GlobalEventHandlers.onmousemove")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("mousemove")}} event is raised.
+
{{domxref("GlobalEventHandlers.onmouseout")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("mouseout")}} event is raised.
+
{{domxref("GlobalEventHandlers.onmouseover")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("mouseover")}} event is raised.
+
{{domxref("GlobalEventHandlers.onmouseup")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("mouseup")}} event is raised.
+
{{domxref("GlobalEventHandlers.onmousewheel")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("mousewheel")}} event is raised.
+
{{domxref("GlobalEventHandlers.onpause")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("pause")}} event is raised.
+
{{domxref("GlobalEventHandlers.onplay")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("play")}} event is raised.
+
{{domxref("GlobalEventHandlers.onplaying")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("playing")}} event is raised.
+
{{domxref("GlobalEventHandlers.onpointerdown")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("pointerdown")}} event is raised.
+
{{domxref("GlobalEventHandlers.onpointermove")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("pointermove")}} event is raised.
+
{{domxref("GlobalEventHandlers.onpointerup")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("pointerup")}} event is raised.
+
{{domxref("GlobalEventHandlers.onpointercancel")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("pointercancel")}} event is raised.
+
{{domxref("GlobalEventHandlers.onpointerover")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("pointerover")}} event is raised.
+
{{domxref("GlobalEventHandlers.onpointerout")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("pointerout")}} event is raised.
+
{{domxref("GlobalEventHandlers.onpointerenter")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("pointerevent")}} event is raised.
+
{{domxref("GlobalEventHandlers.onpointerleave")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("pointerleave")}} event is raised.
+
{{domxref("GlobalEventHandlers.onpointerlockchange")}} {{experimental_inline}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("pointerlockchange")}} event is raised.
+
{{domxref("GlobalEventHandlers.onpointerlockerror")}} {{experimental_inline}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("pointerlockerror")}} event is raised.
+
{{domxref("GlobalEventHandlers.onprogress")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("progress")}} event is raised.
+
{{domxref("GlobalEventHandlers.onratechange")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("ratechange")}} event is raised.
+
{{domxref("GlobalEventHandlers.onreset")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("reset")}} event is raised.
+
{{domxref("GlobalEventHandlers.onscroll")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("scroll")}} event is raised.
+
{{domxref("GlobalEventHandlers.onseeked")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("seeked")}} event is raised.
+
{{domxref("GlobalEventHandlers.onseeking")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("seeking")}} event is raised.
+
{{domxref("GlobalEventHandlers.onselect")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("select")}} event is raised.
+
{{domxref("GlobalEventHandlers.onselectionchange")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("selectionchange")}} event is raised.
+
{{domxref("GlobalEventHandlers.onshow")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("show")}} event is raised.
+
{{domxref("GlobalEventHandlers.onsort")}} {{experimental_inline}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("sort")}} event is raised.
+
{{domxref("GlobalEventHandlers.onstalled")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("stalled")}} event is raised.
+
{{domxref("GlobalEventHandlers.onsubmit")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("submit")}} event is raised.
+
{{domxref("GlobalEventHandlers.onsuspend")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("suspend")}} event is raised.
+
{{domxref("GlobalEventHandlers.ontimeupdate")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("timeupdate")}} event is raised.
+
{{domxref("GlobalEventHandlers.onvolumechange")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("volumechange")}} event is raised.
+
{{domxref("GlobalEventHandlers.ontouchcancel")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("touchcancel")}} event is raised.
+
{{domxref("GlobalEventHandlers.ontouchend")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("touchend")}} event is raised.
+
{{domxref("GlobalEventHandlers.ontouchmove")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("touchmove")}} event is raised.
+
{{domxref("GlobalEventHandlers.ontouchstart")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("touchstart")}} event is raised.
+
{{domxref("GlobalEventHandlers.onwaiting")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("waiting")}} event is raised.
+
+ +

Methods

+ +

This interface defines no method.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Selection API",'', 'Extension to GlobalEventHandlers')}}{{Spec2('Selection API')}}Adds onselectionchange.
{{SpecName('Pointer Lock', '#extensions-to-the-document-interface', 'Extension of Document')}}{{Spec2('Pointer Lock')}}Adds onpointerlockchange and onpointerlockerror on {{domxref("Document")}}. It is experimentally implemented on GlobalEventHandlers.
{{SpecName('HTML WHATWG', '#globaleventhandlers', 'GlobalEventHandlers')}}{{Spec2('HTML WHATWG')}}No change since the latest snapshot, {{SpecName("HTML5.1")}}.
{{SpecName('HTML5.1', '#globaleventhandlers', 'GlobalEventHandlers')}}{{Spec2('HTML5.1')}}Snapshot of {{SpecName("HTML WHATWG")}}. Added onsort since the {{SpecName("HTML5 W3C")}} snapshot.
{{SpecName("HTML5 W3C", "#globaleventhandlers", "GlobalEventHandlers")}}{{Spec2('HTML5 W3C')}}Snapshot of {{SpecName("HTML WHATWG")}}. Creation of GlobalEventHandlers (properties where on the target before it).
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
oncanplay, oncanplaythrough, ondurationchange, onemptied, onended, onloadeddata, onloadedmetadata, onloadstart, onpause, onplay, onplaying, onprogress, onratechange, onseeked, onseeking, onstalled, ontimeupdate, onvolumechange, onwaiting{{CompatGeckoDesktop(1.9.1)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
onsuspend{{CompatGeckoDesktop(1.9.2)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
ondrag, ondragend, ondragenter, ondragleave, ondragover, ondragstart, ondrop{{CompatGeckoDesktop(1.9.1)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
onmouseenter, onmouseleave{{CompatGeckoDesktop(10)}}30.05.517{{CompatUnknown}}
ondragexit{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
oncancel{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
onclose{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
oncuechange{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
ondragexit{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
onmousewheel{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
onsort {{experimental_inline}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
onmozfullscreenchange, onmozfullscreenerror {{non-standard_inline}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
onpointerlockchange, onpointerlockerror{{CompatGeckoDesktop(10)}}[1]{{CompatVersionUnknown}}[2]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
onpointercancel, onpointerdown, onpointerup, onpointermove, onpointerout, onpointerover, onpointerenter, onpointerleave{{CompatVersionUnknown}}[3]{{CompatNo}}10{{CompatUnknown}}{{CompatUnknown}}
onselectionchange{{CompatGeckoDesktop(43)}}[4]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
ontouchend, ontouchcancel, ontouchmove, ontouchstart{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
ondrag, ondragend, ondragenter, ondragleave, ondragover, ondragstart, ondrop{{CompatGeckoMobile(1.9.1)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
oncanplay, oncanplaythrough, ondurationchange, onemptied, onended, onloadeddata, onloadedmetadata, onloadstart, onpause, onplay, onplaying, onprogress, onratechange, onseeked, onseeking, onstalled, ontimeupdate, onvolumechange, onwaiting{{CompatGeckoMobile(1.9.1)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
onmouseenter, onmouseleave{{CompatGeckoMobile(10)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
onsuspend{{CompatGeckoMobile(1.9.2)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
ondragexit{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
oncancel{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
onclose{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
oncuechange{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
ondragexit{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
onmousewheel{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
onsort{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
onmozfullscreenchange, onmozfullscreenerror {{non-standard_inline}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
onpointerlockchange, onpointerlockerror{{CompatGeckoMobile(10)}}[1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
onpointercancel, onpointerdown, onpointerup, onpointermove, onpointerout, onpointerover, onpointerenter, onpointerleave{{CompatVersionUnknown}}[3]{{CompatNo}}10{{CompatNo}}{{CompatNo}}
onselectionchange{{CompatGeckoMobile(43)}}[4]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
ontouchend, ontouchcancel, ontouchmove, ontouchstart{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] In Gecko this is implemented as onmozpointerlockchange, onmozpointerlockerror.

+ +

[2] In Blink this is implemented as onwebkitpointerlockchange, onwebkitpointerlockerror.

+ +

[3] This is implemented behind the dom.w3c_pointer_events.enabled preference, defaulting to false.

+ +

[4] This is implemented behind the dom.select_events.enabled preference, that default to false, except on Nightly.

+ +

See also

+ + diff --git a/files/pt-br/web/api/globaleventhandlers/onabort/index.html b/files/pt-br/web/api/globaleventhandlers/onabort/index.html new file mode 100644 index 0000000000..9882a8b82d --- /dev/null +++ b/files/pt-br/web/api/globaleventhandlers/onabort/index.html @@ -0,0 +1,44 @@ +--- +title: GlobalEventHandlers.onabort +slug: Web/API/GlobalEventHandlers/onabort +translation_of: Web/API/GlobalEventHandlers/onabort +--- +
{{ ApiRef("HTML DOM") }}
+ +

Sumário

+ +

Um manipulador de eventos que aborta eventos enviados para a janela. (Não disponível para o Firefox 2 ou Safari)

+ +

TODO define what "abort" is. Closing the window via window manager? Stopping the load of the page? By which means and reasons (user, network/server)? At which stages would it fire / be catched? For IE, onabort is only available with img tags.

+ +

Sintaxe

+ +
window.onabort =funcRef
+
+ + + +

Exemplo

+ +
window.onabort = function() {
+  alert("Load aborted.");
+}
+ +

Especificação

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG','webappapis.html#handler-onabort','onabort')}}{{Spec2('HTML WHATWG')}} 
diff --git a/files/pt-br/web/api/globaleventhandlers/onblur/index.html b/files/pt-br/web/api/globaleventhandlers/onblur/index.html new file mode 100644 index 0000000000..ee4133a0da --- /dev/null +++ b/files/pt-br/web/api/globaleventhandlers/onblur/index.html @@ -0,0 +1,94 @@ +--- +title: GlobalEventHandlers.onblur +slug: Web/API/GlobalEventHandlers/onblur +tags: + - API + - HTML DOM + - Propriedade + - Referencia +translation_of: Web/API/GlobalEventHandlers/onblur +--- +
{{ApiRef("HTML DOM")}}
+ +

The onblur property returns the onBlur event handler code, if any, that exists on the current element.

+ +

Sintaxe

+ +
element.onblur = function;
+
+ + + +
element.onblur = function() { console.log("evento onblur detectado!"); };
+
+ +

Exemplo

+ +
<html>
+
+<head>
+<title>exemplo de evento onblur</title>
+
+<script type="text/javascript">
+
+var elem = null;
+
+function initElement()
+{
+  elem = document.getElementById("foo");
+  // NOTA: doEvent(); ou doEvent(param); NÃO irão funcionar aqui.
+  // Deve ser uma referência ao nome da função, não à chamada da função.
+  elem.onblur = doEvent;
+};
+
+function doEvent()
+{
+  elem.value = 'Tchauzinho';
+  console.log("Evento onblur detectado!")
+}
+</script>
+
+<style type="text/css">
+<!--
+#foo {
+border: solid blue 2px;
+}
+-->
+</style>
+</head>
+
+<body onload="initElement();">
+<form>
+<input type="text" id="foo" value="Olá!" />
+</form>
+
+<p>Clique no elemento acima para dá-lo focus, depois clique fora do elemento.<br /> Recarregue a pagina através do NavBar.</p>
+
+</body>
+</html>
+
+ +

Notas

+ +

O evento blur aparece quando um elemento perde o focus.

+ +

Em contraste cp, MSIE--O qual faz quase todos os elementos receberem o evento blur--quase todos os elementos em navegadores baseados no Gecko NÃO funcionam com este evento.

+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG','webappapis.html#handler-onblur','onblur')}}{{Spec2('HTML WHATWG')}} 
diff --git a/files/pt-br/web/api/globaleventhandlers/onchange/index.html b/files/pt-br/web/api/globaleventhandlers/onchange/index.html new file mode 100644 index 0000000000..c2dab3f1d8 --- /dev/null +++ b/files/pt-br/web/api/globaleventhandlers/onchange/index.html @@ -0,0 +1,46 @@ +--- +title: GlobalEventHandlers.onchange +slug: Web/API/GlobalEventHandlers/onchange +tags: + - API + - HTML DOM + - Propriedade + - Referencia +translation_of: Web/API/GlobalEventHandlers/onchange +--- +
+
{{ ApiRef("HTML DOM") }}
+
+ +

A propriedade onchange determina e retorna o manipulador de eventos para o evento {{event("change")}}.

+ +

Syntax

+ +
element.onchange = handlerFunction;
+var handlerFunction = element.onchange;
+
+ +

handlerFunction deve ser ou null ou uma função JavaScript especificando o manipulador para o evento.

+ +

Notas

+ +

Veja a página do manipulador de eventos do DOM para informações sobre como trabalhar com manipuladores on... 

+ +

Veja a documentação do evento {{event("change")}} para informações sobre o evento.

+ +

Especificação

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentários
{{SpecName('HTML WHATWG','webappapis.html#handler-onchange','onchange')}}{{Spec2('HTML WHATWG')}} 
diff --git a/files/pt-br/web/api/globaleventhandlers/onclick/index.html b/files/pt-br/web/api/globaleventhandlers/onclick/index.html new file mode 100644 index 0000000000..ea91496ac9 --- /dev/null +++ b/files/pt-br/web/api/globaleventhandlers/onclick/index.html @@ -0,0 +1,83 @@ +--- +title: GlobalEventHandlers.onclick +slug: Web/API/GlobalEventHandlers/onclick +translation_of: Web/API/GlobalEventHandlers/onclick +--- +
{{ ApiRef("HTML DOM") }}
+ +

A propriedade onclick do mixin {{domxref("GlobalEventHandlers")}} é o {{domxref("EventHandler")}} para o processamento de eventos de {{event("click")}} em um dado elemento.

+ +

O evento click acontece quando o usuário clica em um elemento. É disparado após os eventos {{event("mousedown")}} e{{event("mouseup")}} na respectiva ordem.

+ +
Note: Ao usar o evento click para disparar uma ação, considere também adicionar essa mesma ação ao evento {{event("keydown")}}, para permitir o uso dessa mesma ação a pessoas que não usam um mouse ou uma touchscreen.
+ +

Sintaxe

+ +
elemento.onclick = refDeFuncao;
+
+ +

Value

+ +

refDeFuncao é o nome de uma função ou uma expressão de função. Essa função recebe um objeto {{domxref("MouseEvent")}} como único argumento. Dentro da função, this será o elemento de qual o evento foi disparado.

+ +

Apenas um manipulador onclick pode estar associado a um objeto em um momento. Em vez disso, você talvez prefira usar o método {{domxref("EventTarget.addEventListener()")}}, já que ele é mais flexível.

+ +

Exemplo

+ +

Esse evento registra a posição dos cliques.

+ +

HTML

+ +
<p>Clique em qualquer lugar nesse exemplo.</p>
+<p id="log"></p>
+ +

JavaScript

+ +
let log = document.getElementById('log');
+
+document.onclick = inputChange;
+
+function inputChange(e) {
+  log.textContent = `Posição: (${e.clientX}, ${e.clientY})`;
+}
+ +

Result

+ +

{{EmbedLiveSample("Example")}}

+ +

Especificação

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG','webappapis.html#handler-onclick','onclick')}}{{Spec2('HTML WHATWG')}} 
+ +

Compatibilidade de Navegador

+ +
+ + +

{{Compat("api.GlobalEventHandlers.onclick")}}

+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/globaleventhandlers/oncontextmenu/index.html b/files/pt-br/web/api/globaleventhandlers/oncontextmenu/index.html new file mode 100644 index 0000000000..5649c6671f --- /dev/null +++ b/files/pt-br/web/api/globaleventhandlers/oncontextmenu/index.html @@ -0,0 +1,48 @@ +--- +title: GlobalEventHandlers.oncontextmenu +slug: Web/API/GlobalEventHandlers/oncontextmenu +tags: + - API + - HTML DOM + - Propriedade + - Referencia +translation_of: Web/API/GlobalEventHandlers/oncontextmenu +--- +
{{ ApiRef("HTML DOM") }}
+ +

Um uma propriedade do manipulador de eventos da janela para eventos com o botão direito do mouse. A menos que o comportamento padrão do navegador seja bloqueado (veja exemplos abaixo sobre como fazer isso), o menu de contexto do navegador irá ser ativado (apesar do IE8 ter um bug com ele e não irá ativar o menu de contexto se o manipulador de eventos contextmenu for definido). Note que este evento irá acontecer com qualquer evento não-desabilitado do botão direito do mouse e não depende de um elemento que contenha o atributo "contextmenu".

+ +

Sintaxe

+ +
window.oncontextmenu = funcRef;
+//funcRef se refere à função a ser chamada
+ +

Exemplo

+ +

Os exemplos abaixo irão desabilitar o clique com botão direito na página:

+ +
document.oncontextmenu = function () { // Usa o document ao invés de window para compatibilidade com o IE8
+   return false;
+};
+
+window.addEventListener('contextmenu', function (e) { // Não compatível com IE < 9
+    e.preventDefault();
+}, false);
+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG','webappapis.html#handler-oncontextmenu','oncontextmenu')}}{{Spec2('HTML WHATWG')}} 
diff --git a/files/pt-br/web/api/globaleventhandlers/onerror/index.html b/files/pt-br/web/api/globaleventhandlers/onerror/index.html new file mode 100644 index 0000000000..95fdc08ce3 --- /dev/null +++ b/files/pt-br/web/api/globaleventhandlers/onerror/index.html @@ -0,0 +1,97 @@ +--- +title: GlobalEventHandlers.onerror +slug: Web/API/GlobalEventHandlers/onerror +tags: + - API + - HTML DOM + - Propriedade + - Referencia +translation_of: Web/API/GlobalEventHandlers/onerror +--- +
{{ApiRef("HTML DOM")}}
+ +

Um event handler para o evento error . Eventos de erro são disparados contra diversos tipos de alvos, para diferentes tipos de erros: 

+ + + +

Instalando um manipulador de eventos de erro global é útil para compilação automatizada de relatórios de erro. 

+ +

Sintaxe

+ +

Por questões históricas, diferentes argumentos são passados para os manipuladores window.onerror e element.onerror;

+ +

window.onerror

+ +
window.onerror = function(message, source, lineno, colno, error) { ... }
+
+ +

Parâmetros da função:

+ + + +

 

+ +

Quando a função retorna verdadeira, ela evita o disparo do manipulador de evento padrão 

+ +

element.onerror

+ +
element.onerror = function(event) { ... }
+
+ +

element.onerror aceita uma função dom um único argumento do tipo {{domxref("Event")}}.

+ +

Notas

+ +

Quando um erro de sintaxe(?) ocorre em um script, carregado de uma origem diferente, os detalhes do erro de sintaxe não são reportados para previnir vazamento de informações (veja {{bug("363897")}}). Ao invés de exibir simplesmente "Script error." (erro de script), este comportamento pode ser sobrescrito em alguns navegadores usando o atributo  {{htmlattrxref("crossorigin","script")}} no {{HTMLElement("script")}} e tendo o servidor enviado os cabeçalhos HTTP CORS apropriados.  Uma solução alternativa é isolar o "Script error." e manipulá-lo sabendo que o detalhe do erro é visível somente no console do navegador e não acessível através do JavaScript.

+ +
window.onerror = function (msg, url, lineNo, columnNo, error) {
+    var string = msg.toLowerCase();
+    var substring = "script error";
+    if (string.indexOf(substring) > -1){
+        alert('Script Error: See Browser Console for Detail');
+    } else {
+        alert(msg, url, lineNo, columnNo, error);
+    }
+  return false;
+};
+ +

Quando usamos a marcação HTML inline (<body onerror="alert('an error occurred')">), a especificação HTML requer argumentos passados para o onerror identificados como event, source, lineno, colno, error. Os navegadors que não implementam este requerimento, podem ainda serem obtidos por arguments[0] até arguments[2].

+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG','webappapis.html#handler-onerror','onerror')}}{{Spec2('HTML WHATWG')}} 
+ +

Compatibilidade de navegadores

+ +

Antes do Firefox 14, quando um {{HTMLElement("script")}} falhava na inicialização, window.onerror era invocada com a mensagem "Error loading script"(erro de leitura de script). Isto foi corrigido no {{bug("737087")}}, agora scriptElement.onerror é chamado ao invés disto.

+ +

Desde o Firefox 31, os últimos 2 argumentos (colno and error) foram adicionados, o que significa que você tem acesso a pilha de rastreamento de um erro de script através do window.onerror por intermédio do Error object ({{bug("355430")}}.)

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/globaleventhandlers/onfocus/index.html b/files/pt-br/web/api/globaleventhandlers/onfocus/index.html new file mode 100644 index 0000000000..3d27899ec3 --- /dev/null +++ b/files/pt-br/web/api/globaleventhandlers/onfocus/index.html @@ -0,0 +1,36 @@ +--- +title: GlobalEventHandlers.onfocus +slug: Web/API/GlobalEventHandlers/onfocus +translation_of: Web/API/GlobalEventHandlers/onfocus +--- +
{{ApiRef("HTML DOM")}}
+ +

A propriedade onfocus retorna o código de manipulador de eventos onFocus no elemento atual.

+ +

Sintaxe

+ +
element.onfocus = código de manipulação de eventos
+
+ +

Notas

+ +

O evento Focus é gerado quando o usuario define o foco no elemento.

+ +

Oposta à MSIE, em que quase todos os tipos de elementos recebem o evento focus, em navegadores Gecko quase todos os tipos de elementos não funcionam com este evento.

+ +

Especificações

+ + + + + + + + + + + + + + +
especificaçãosStatusComentario
{{SpecName('HTML WHATWG','webappapis.html#handler-onfocus','onfocus')}}{{Spec2('HTML WHATWG')}} 
diff --git a/files/pt-br/web/api/globaleventhandlers/onkeyup/index.html b/files/pt-br/web/api/globaleventhandlers/onkeyup/index.html new file mode 100644 index 0000000000..394aa886b2 --- /dev/null +++ b/files/pt-br/web/api/globaleventhandlers/onkeyup/index.html @@ -0,0 +1,61 @@ +--- +title: GlobalEventHandlers.onkeyup +slug: Web/API/GlobalEventHandlers/onkeyup +tags: + - API + - HTML DOM + - Propriedade + - Referencia +translation_of: Web/API/GlobalEventHandlers/onkeyup +--- +
{{ApiRef("HTML DOM")}}
+ +

A propriedade onkeyup retorna o código de manipulador de eventos onKeyUp no elemento atual.

+ +

Sintaxe

+ +
element.onkeyup = código do manipulador do eventos
+
+ +

Exemplo

+ +
 <input type="text" onKeyUp="teclaPressionada(event)">
+ <script>
+    function teclaPressionada(evt) {
+       console.log(evt.keyCode)
+    }
+ </script>
+
+ +

Notas

+ +

O evento keyup é iniciado quando o usuário libera a tecla é pressionada.

+ +

Especificações

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG','webappapis.html#handler-onkeyup','onkeyup')}}{{Spec2('HTML WHATWG')}} 
+ +

Compatibilidade

+ +
+ + +

{{Compat("api.GlobalEventHandlers.onkeyup")}}

+
+ +
 
diff --git a/files/pt-br/web/api/globaleventhandlers/onload/index.html b/files/pt-br/web/api/globaleventhandlers/onload/index.html new file mode 100644 index 0000000000..2de2fb11c4 --- /dev/null +++ b/files/pt-br/web/api/globaleventhandlers/onload/index.html @@ -0,0 +1,74 @@ +--- +title: GlobalEventHandlers.onload +slug: Web/API/GlobalEventHandlers/onload +translation_of: Web/API/GlobalEventHandlers/onload +--- +
{{ApiRef("HTML DOM")}}
+ +

Um manipulador de eventos para o evento de carregamento do objeto {{domxref("window")}}.

+ +

Syntax

+ +
window.onload = funcRef;
+
+ + + +

Exemplos

+ +
window.onload = function() {
+  init();
+  doSomethingElse();
+};
+
+ +
<!doctype html>
+<html>
+  <head>
+    <title>onload test</title>
+    <script>
+      function load() {
+        console.log("Evento de carregamento detectado!");
+      }
+      window.onload = load;
+    </script>
+  </head>
+  <body>
+    <p>O evento de carregamento dispara quando o documento acabou de ser carregado!</p>
+  </body>
+</html>
+
+ +

Notas

+ +

O evento de carregamento dispara no final do processo de carregamento do documento. Neste ponto, todos os objetos do documento estão no DOM, e todas as imagens, scripts, links e sub-frames terminaram de carregar.

+ +

Existe também os Gecko-Specific DOM Events, como o DOMContentLoaded e o DOMFrameContentLoaded (que pode ser manipulado utilizando o {{domxref("EventTarget.addEventListener()")}}) que são disparados após o DOM para a página ser construído, mas não espera outros recursos serem carregados.

+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName("HTML WHATWG", "webappapis.html#handler-onload", "onload")}}{{Spec2("HTML WHATWG")}}Definição inicial
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/globaleventhandlers/onlostpointercapture/index.html b/files/pt-br/web/api/globaleventhandlers/onlostpointercapture/index.html new file mode 100644 index 0000000000..8df6a32e69 --- /dev/null +++ b/files/pt-br/web/api/globaleventhandlers/onlostpointercapture/index.html @@ -0,0 +1,70 @@ +--- +title: GlobalEventHandlers.onlostpointercapture +slug: Web/API/GlobalEventHandlers/onlostpointercapture +tags: + - API + - DOM + - Event Handler + - GlobalEventHandlers + - HTML + - Propriedade + - Referencia + - events + - onlostpointercapture +translation_of: Web/API/GlobalEventHandlers/onlostpointercapture +--- +
{{ApiRef("HTML DOM")}}
+ +

A propriedade onlostpointercapture do mixin {{domxref("GlobalEventHandlers")}} é uma {{domxref("EventHandler")}} que processa eventos {{event("lostpointercapture")}}.

+ +

Sintaxe

+ +
target.onlostpointercapture = functionRef;
+ +

Value

+ +

functionRef é o nome de uma função ou uma expressão de função. A função recebe um objeto {{domxref("PointerEvent")}} como seu único argumento.

+ +

Exemplo

+ +
function overHandler(event) {
+  // Determinar o manipulador lostpointercapture para o evento alvo (target event).
+  let lostCaptureHandler = event.target.onlostpointercapture;
+}
+
+function init() {
+  let el = document.getElementById('target');
+  el.onlostpointercapture = overHandler;
+}
+
+ +

Especificações

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Pointer Events 2', '#the-lostpointercapture-event', 'onlostpointercapture')}}{{Spec2('Pointer Events 2')}}
+ +

Compatibilidade de Navegador

+ + + +

{{Compat("api.GlobalEventHandlers.onlostpointercapture")}}

+ +

See also

+ + diff --git a/files/pt-br/web/api/globaleventhandlers/onscroll/index.html b/files/pt-br/web/api/globaleventhandlers/onscroll/index.html new file mode 100644 index 0000000000..1156bfb2f7 --- /dev/null +++ b/files/pt-br/web/api/globaleventhandlers/onscroll/index.html @@ -0,0 +1,94 @@ +--- +title: GlobalEventHandlers.onscroll +slug: Web/API/GlobalEventHandlers/onscroll +translation_of: Web/API/GlobalEventHandlers/onscroll +--- +
{{ApiRef("HTML DOM")}}
+ +

A propriedade onscroll do {{domxref("GlobalEventHandlers")}} é uma mistura de eventos {{domxref("EventHandler")}} que processam eventos scroll.

+ +

O evento scroll é disparado quando uma visão do documento ou um elemento foi rolado, seja por um usuário, uma API Web, ou o {{glossary("user agent")}}.

+ +
+

Nota: Não confunda onscroll com {{domxref("GlobalEventHandlers.onwheel", "onwheel")}}: onwheel manipula a rotação da roda do mouse, enquanto onscroll manipula rolagem do conteúdo do objeto.

+
+ +

Sintaxe

+ +
target.onscroll = functionRef;
+
+ +

Valor

+ +

functionRef é o nome de uma função ou uma  expressão de função. A função recebe um  {{domxref("UIEvent")}} objeto com um único argumento.

+ +

Apenas um manipulador onscroll pode ser associado à um objeto por vez. Para uma maior flexibilidade, você pode passar um {{event("scroll")}} evento para o {{domxref("EventTarget.addEventListener()")}} metódo ao invés disso.

+ +

Exemplo

+ +

Este exemplo monitora rolagens sobre o elemento {{HtmlElement("textarea")}}, e registra a posição vertical adequadamente.

+ +

HTML

+ +
<textarea>1 2 3 4 5 6 7 8 9</textarea>
+<p id="log"></p>
+ +

CSS

+ +
textarea {
+  width: 4rem;
+  height: 8rem;
+  font-size: 3rem;
+}
+ +

JavaScript

+ +
const textarea = document.querySelector('textarea');
+const log = document.getElementById('log');
+
+textarea.onscroll = logScroll;
+
+function logScroll(e) {
+  log.textContent = `Posição do scroll: ${e.target.scrollTop}`;
+}
+ +

Resultado

+ +

{{EmbedLiveSample("Exemplo", 700, 200)}}

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG','#handler-onscroll','onscroll')}}{{Spec2('HTML WHATWG')}}
{{SpecName("DOM3 Events", "#event-type-scroll", "onscroll")}}{{Spec2("DOM3 Events")}}Initial definition
+ +

Compatibilidade com o Navegador

+ + + +

{{Compat("api.GlobalEventHandlers.onscroll")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/history/index.html b/files/pt-br/web/api/history/index.html new file mode 100644 index 0000000000..8541516f41 --- /dev/null +++ b/files/pt-br/web/api/history/index.html @@ -0,0 +1,89 @@ +--- +title: History +slug: Web/API/History +translation_of: Web/API/History +--- +
{{APIRef ("HTML DOM")}}
+ +

A interface History permite a manipulação do histórico da sessão do navegador, ou seja, as páginas visitadas na guia ou quadro em que a página atual está carregada.

+ +

Propriedades

+ + + +

A interface History não herda nenhuma propriedade.

+ +
+
{{domxref("History.length")}} {{readOnlyInline}}
+
Returns an Integer representing the number of elements in the session history, including the currently loaded page. For example, for a page loaded in a new tab this property returns 1.
+
{{domxref("History.current")}} {{readOnlyInline}} {{ non-standard_inline() }} {{ obsolete_inline(26) }}
+
Returns a {{domxref("DOMString")}} representing the URL of the active item of the session history. This property was never available to web content and is no more supported by any browser. Use {{domxref("Location.href")}} instead.
+
{{domxref("History.next")}} {{readOnlyInline}} {{ non-standard_inline() }} {{ obsolete_inline(26) }}
+
Returns a {{domxref("DOMString")}} representing the URL of the next item in the session history. This property was never available to web content and is not supported by other browsers.
+
{{domxref("History.previous")}} {{readOnlyInline}} {{ non-standard_inline() }} {{ obsolete_inline(26) }}
+
Returns a {{domxref("DOMString")}} representing the URL of the previous item in the session history. This property was never available to web content and is not supported by other browsers.
+
{{domxref("History.scrollRestoration")}} {{experimental_inline}}
+
Allows web applications to explicitly set default scroll restoration behavior on history navigation. This property can be either auto or manual.
+
{{domxref("History.state")}} {{readOnlyInline}} {{ gecko_minversion_inline("2.0") }}
+
Returns an any value representing the state at the top of the history stack. This is a way to look at the state without having to wait for a {{event("popstate")}} event.
+
+ +

Methods

+ +

The History interface doesn't inherit any methods.

+ +
+
{{domxref("History.back()")}}
+
Goes to the previous page in session history, the same action as when the user clicks the browser's Back button. Equivalent to history.go(-1). +
Calling this method to go back beyond the first page in the session history has no effect and doesn't raise an exception.
+
+
{{domxref("History.forward()")}}
+
Goes to the next page in session history, the same action as when the user clicks the browser's Forward button; this is equivalent to history.go(1). +
Calling this method to go forward beyond the most recent page in the session history has no effect and doesn't raise an exception.
+
+
{{domxref("History.go()")}}
+
Loads a page from the session history, identified by its relative location to the current page, for example -1 for the previous page or 1  for the next page. If you specify an out-of-bounds value (for instance, specifying -1 when there are no previously-visited pages in the session history), this method silently has no effect. Calling go() without parameters or a value of 0 reloads the current page. Internet Explorer lets you specify a string, instead of an integer, to go to a specific URL in the history list.
+
{{domxref("History.pushState()")}} {{ gecko_minversion_inline("2.0") }}
+
Pushes the given data onto the session history stack with the specified title and, if provided, URL. The data is treated as opaque by the DOM; you may specify any JavaScript object that can be serialized.  Note that Firefox currently ignores the title parameter; for more information, see manipulating the browser history.
+
{{domxref("History.replaceState()")}} {{ gecko_minversion_inline("2.0") }}
+
Updates the most recent entry on the history stack to have the specified data, title, and, if provided, URL. The data is treated as opaque by the DOM; you may specify any JavaScript object that can be serialized.  Note that Firefox currently ignores the title parameter; for more information, see manipulating the browser history.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "browsers.html#the-history-interface", "History")}}{{Spec2('HTML WHATWG')}}Adds the scrollRestoration attribute.
{{SpecName('HTML5 W3C', "browsers.html#the-history-interface", "History")}}{{Spec2('HTML5 W3C')}}Initial definition.
{{SpecName('Custom Scroll Restoration', '#web-idl', "History")}}{{Spec2('Custom Scroll Restoration')}}Adds the scrollRestoration attribute.
+ +

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/pt-br/web/api/history_api/exemplo/index.html b/files/pt-br/web/api/history_api/exemplo/index.html new file mode 100644 index 0000000000..a4dfc4b68f --- /dev/null +++ b/files/pt-br/web/api/history_api/exemplo/index.html @@ -0,0 +1,418 @@ +--- +title: Exemplo de navegação Ajax +slug: Web/API/History_API/Exemplo +tags: + - Exemplo navegação ajax +translation_of: Web/API/History_API/Example +--- +

Esse é um exemplo de um web site em AJAX web site composto por apenas três páginas (first_page.php, second_page.php e third_page.php). Para ver como funciona, crie os arquivos a seguir (ou git clone https://github.com/giabao/mdn-ajax-nav-example.git ):

+ +
Nota: Para integrar completamente os elementos {{HTMLElement("form")}} com esse mecanismo, porfavor dê uma olhada no parágrafo Enviando formulários e enviando arquivos.
+ +

first_page.php:

+ +
+
<?php
+    $page_title = "Primeira página";
+
+    $as_json = false;
+    if (isset($_GET["view_as"]) && $_GET["view_as"] == "json") {
+        $as_json = true;
+        ob_start();
+    } else {
+?>
+<!doctype html>
+<html>
+<head>
+<?php
+        include "include/header.php";
+        echo "<title>" . $page_title . "</title>";
+?>
+</head>
+
+<body>
+
+<?php include "include/before_content.php"; ?>
+
+<p>Esse parágrafo só é mostrado quando a navegação começa em <strong>first_page.php</strong>.</p>
+
+<div id="ajax-content">
+<?php } ?>
+
+    <p>Esse é o conteúdo de <strong>first_page.php</strong>.</p>
+
+<?php
+    if ($as_json) {
+        echo json_encode(array("page" => $page_title, "content" => ob_get_clean()));
+    } else {
+?>
+</div>
+
+<p>Esse parágrafo só é mostrado quando a navegação começa em <strong>first_page.php</strong>.</p>
+
+<?php
+        include "include/after_content.php";
+        echo "</body>\n</html>";
+    }
+?>
+
+
+ +

second_page.php:

+ +
+
<?php
+    $page_title = "Segunda página";
+
+    $as_json = false;
+    if (isset($_GET["view_as"]) && $_GET["view_as"] == "json") {
+        $as_json = true;
+        ob_start();
+    } else {
+?>
+<!doctype html>
+<html>
+<head>
+<?php
+        include "include/header.php";
+        echo "<title>" . $page_title . "</title>";
+?>
+</head>
+
+<body>
+
+<?php include "include/before_content.php"; ?>
+
+<p>Esse parágrafo só é mostrado quando a navegação começa em <strong>second_page.php</strong>.</p>
+
+<div id="ajax-content">
+<?php } ?>
+
+    <p>Esse é o conteúdo de <strong>second_page.php</strong>.</p>
+
+<?php
+    if ($as_json) {
+        echo json_encode(array("page" => $page_title, "content" => ob_get_clean()));
+    } else {
+?>
+</div>
+
+<p>Esse parágrafo só é mostrado quando a navegação começa em <strong>second_page.php</strong>.</p>
+
+<?php
+        include "include/after_content.php";
+        echo "</body>\n</html>";
+    }
+?>
+
+
+ +

third_page.php:

+ +
+
<?php
+    $page_title = "Terceira página";
+    $page_content = "<p>Esse é o conteúdo de <strong>third_page.php</strong>. This content is stored into a php variable.</p>";
+
+    if (isset($_GET["view_as"]) && $_GET["view_as"] == "json") {
+        echo json_encode(array("page" => $page_title, "content" => $page_content));
+    } else {
+?>
+<!doctype html>
+<html>
+<head>
+<?php
+        include "include/header.php";
+        echo "<title>" . $page_title . "</title>";
+?>
+</head>
+
+<body>
+
+<?php include "include/before_content.php"; ?>
+
+<p>Esse parágrafo só é mostrado quando a navegação começa em <strong>third_page.php</strong>.</p>
+
+<div id="ajax-content">
+<?php echo $page_content; ?>
+</div>
+
+<p>Esse parágrafo só é mostrado quando a navegação começa em <strong>third_page.php</strong>.</p>
+
+<?php
+        include "include/after_content.php";
+        echo "</body>\n</html>";
+    }
+?>
+
+
+ +

css/style.css:

+ +
#ajax-loader {
+    position: fixed;
+    display: table;
+    top: 0;
+    left: 0;
+    width: 100%;
+    height: 100%;
+}
+
+#ajax-loader > div {
+    display: table-cell;
+    width: 100%;
+    height: 100%;
+    vertical-align: middle;
+    text-align: center;
+    background-color: #000000;
+    opacity: 0.65;
+}
+
+ +

include/after_content.php:

+ +
<p>Esse é o rodapé. Ele é compartilhado entre todas as páginas ajax.</p>
+
+ +

include/before_content.php:

+ +
<p>
+[ <a class="ajax-nav" href="first_page.php">Primeiro exemplo</a>
+| <a class="ajax-nav" href="second_page.php">Segundo exemplo</a>
+| <a class="ajax-nav" href="third_page.php">Terceiro exemplo</a>
+| <a class="ajax-nav" href="unexisting.php">Página inexistente</a> ]
+</p>
+
+
+ +

include/header.php:

+ +
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
+<script type="text/javascript" src="js/ajax_nav.js"></script>
+<link rel="stylesheet" href="css/style.css" />
+
+ +

js/ajax_nav.js:

+ +

(antes de implementar em um ambiente de trabalho, porfavor leia a nota sobre a compatibilidade de declaração de const)

+ +
+
"use strict";
+
+const ajaxRequest = new (function () {
+
+    function closeReq () {
+        oLoadingBox.parentNode && document.body.removeChild(oLoadingBox);
+        bIsLoading = false;
+    }
+
+    function abortReq () {
+        if (!bIsLoading) { return; }
+        oReq.abort();
+        closeReq();
+    }
+
+    function ajaxError () {
+        alert("Unknown error.");
+    }
+
+    function ajaxLoad () {
+        var vMsg, nStatus = this.status;
+        switch (nStatus) {
+            case 200:
+                vMsg = JSON.parse(this.responseText);
+                document.title = oPageInfo.title = vMsg.page;
+                document.getElementById(sTargetId).innerHTML = vMsg.content;
+                if (bUpdateURL) {
+                    history.pushState(oPageInfo, oPageInfo.title, oPageInfo.url);
+                    bUpdateURL = false;
+                }
+                break;
+            default:
+                vMsg = nStatus + ": " + (oHTTPStatus[nStatus] || "Unknown");
+                switch (Math.floor(nStatus / 100)) {
+                    /*
+                    case 1:
+                        // Informational 1xx
+                        console.log("Information code " + vMsg);
+                        break;
+                    case 2:
+                        // Successful 2xx
+                        console.log("Successful code " + vMsg);
+                        break;
+                    case 3:
+                        // Redirection 3xx
+                        console.log("Redirection code " + vMsg);
+                        break;
+                    */
+                    case 4:
+                        /* Client Error 4xx */
+                        alert("Client Error #" + vMsg);
+                        break;
+                    case 5:
+                        /* Server Error 5xx */
+                        alert("Server Error #" + vMsg);
+                        break;
+                    default:
+                        /* Unknown status */
+                        ajaxError();
+                }
+        }
+        closeReq();
+    }
+
+    function filterURL (sURL, sViewMode) {
+        return sURL.replace(rSearch, "") + ("?" + sURL.replace(rHost, "&").replace(rView, sViewMode ? "&" + sViewKey + "=" + sViewMode : "").slice(1)).replace(rEndQstMark, "");
+    }
+
+    function getPage (sPage) {
+        if (bIsLoading) { return; }
+        oReq = new XMLHttpRequest();
+        bIsLoading = true;
+        oReq.onload = ajaxLoad;
+        oReq.onerror = ajaxError;
+        if (sPage) { oPageInfo.url = filterURL(sPage, null); }
+        oReq.open("get", filterURL(oPageInfo.url, "json"), true);
+        oReq.send();
+        oLoadingBox.parentNode || document.body.appendChild(oLoadingBox);
+    }
+
+    function requestPage (sURL) {
+        if (history.pushState) {
+            bUpdateURL = true;
+            getPage(sURL);
+        } else {
+            /* Ajax navigation is not supported */
+            location.assign(sURL);
+        }
+    }
+
+    function processLink () {
+        if (this.className === sAjaxClass) {
+            requestPage(this.href);
+            return false;
+        }
+        return true;
+    }
+
+    function init () {
+        oPageInfo.title = document.title;
+        history.replaceState(oPageInfo, oPageInfo.title, oPageInfo.url);
+        for (var oLink, nIdx = 0, nLen = document.links.length; nIdx < nLen; document.links[nIdx++].onclick = processLink);
+    }
+
+    const
+
+        /* customizable constants */
+        sTargetId = "ajax-content", sViewKey = "view_as", sAjaxClass = "ajax-nav",
+
+        /* not customizable constants */
+        rSearch = /\?.*$/, rHost = /^[^\?]*\?*&*/, rView = new RegExp("&" + sViewKey + "\\=[^&]*|&*$", "i"), rEndQstMark = /\?$/,
+        oLoadingBox = document.createElement("div"), oCover = document.createElement("div"), oLoadingImg = new Image(),
+        oPageInfo = {
+            title: null,
+            url: location.href
+        }, oHTTPStatus = /* http://www.iana.org/assignments/http-status-codes/http-status-codes.xml */ {
+            100: "Continue",
+            101: "Switching Protocols",
+            102: "Processing",
+            200: "OK",
+            201: "Created",
+            202: "Accepted",
+            203: "Non-Authoritative Information",
+            204: "No Content",
+            205: "Reset Content",
+            206: "Partial Content",
+            207: "Multi-Status",
+            208: "Already Reported",
+            226: "IM Used",
+            300: "Multiple Choices",
+            301: "Moved Permanently",
+            302: "Found",
+            303: "See Other",
+            304: "Not Modified",
+            305: "Use Proxy",
+            306: "Reserved",
+            307: "Temporary Redirect",
+            308: "Permanent Redirect",
+            400: "Bad Request",
+            401: "Unauthorized",
+            402: "Payment Required",
+            403: "Forbidden",
+            404: "Not Found",
+            405: "Method Not Allowed",
+            406: "Not Acceptable",
+            407: "Proxy Authentication Required",
+            408: "Request Timeout",
+            409: "Conflict",
+            410: "Gone",
+            411: "Length Required",
+            412: "Precondition Failed",
+            413: "Request Entity Too Large",
+            414: "Request-URI Too Long",
+            415: "Unsupported Media Type",
+            416: "Requested Range Not Satisfiable",
+            417: "Expectation Failed",
+            422: "Unprocessable Entity",
+            423: "Locked",
+            424: "Failed Dependency",
+            425: "Unassigned",
+            426: "Upgrade Required",
+            427: "Unassigned",
+            428: "Precondition Required",
+            429: "Too Many Requests",
+            430: "Unassigned",
+            431: "Request Header Fields Too Large",
+            500: "Internal Server Error",
+            501: "Not Implemented",
+            502: "Bad Gateway",
+            503: "Service Unavailable",
+            504: "Gateway Timeout",
+            505: "HTTP Version Not Supported",
+            506: "Variant Also Negotiates (Experimental)",
+            507: "Insufficient Storage",
+            508: "Loop Detected",
+            509: "Unassigned",
+            510: "Not Extended",
+            511: "Network Authentication Required"
+        };
+
+    var
+
+        oReq, bIsLoading = false, bUpdateURL = false;
+
+    oLoadingBox.id = "ajax-loader";
+    oCover.onclick = abortReq;
+    oLoadingImg.src = "data:image/gif;base64,R0lGODlhEAAQAPIAAP///wAAAMLCwkJCQgAAAGJiYoKCgpKSkiH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAEAAQAAADMwi63P4wyklrE2MIOggZnAdOmGYJRbExwroUmcG2LmDEwnHQLVsYOd2mBzkYDAdKa+dIAAAh+QQJCgAAACwAAAAAEAAQAAADNAi63P5OjCEgG4QMu7DmikRxQlFUYDEZIGBMRVsaqHwctXXf7WEYB4Ag1xjihkMZsiUkKhIAIfkECQoAAAAsAAAAABAAEAAAAzYIujIjK8pByJDMlFYvBoVjHA70GU7xSUJhmKtwHPAKzLO9HMaoKwJZ7Rf8AYPDDzKpZBqfvwQAIfkECQoAAAAsAAAAABAAEAAAAzMIumIlK8oyhpHsnFZfhYumCYUhDAQxRIdhHBGqRoKw0R8DYlJd8z0fMDgsGo/IpHI5TAAAIfkECQoAAAAsAAAAABAAEAAAAzIIunInK0rnZBTwGPNMgQwmdsNgXGJUlIWEuR5oWUIpz8pAEAMe6TwfwyYsGo/IpFKSAAAh+QQJCgAAACwAAAAAEAAQAAADMwi6IMKQORfjdOe82p4wGccc4CEuQradylesojEMBgsUc2G7sDX3lQGBMLAJibufbSlKAAAh+QQJCgAAACwAAAAAEAAQAAADMgi63P7wCRHZnFVdmgHu2nFwlWCI3WGc3TSWhUFGxTAUkGCbtgENBMJAEJsxgMLWzpEAACH5BAkKAAAALAAAAAAQABAAAAMyCLrc/jDKSatlQtScKdceCAjDII7HcQ4EMTCpyrCuUBjCYRgHVtqlAiB1YhiCnlsRkAAAOwAAAAAAAAAAAA==";
+    oCover.appendChild(oLoadingImg);
+    oLoadingBox.appendChild(oCover);
+
+    onpopstate = function (oEvent) {
+        bUpdateURL = false;
+        oPageInfo.title = oEvent.state.title;
+        oPageInfo.url = oEvent.state.url;
+        getPage();
+    };
+
+    window.addEventListener ? addEventListener("load", init, false) : window.attachEvent ? attachEvent("onload", init) : (onload = init);
+
+    // Public methods
+
+    this.open = requestPage;
+    this.stop = abortReq;
+    this.rebuildLinks = init;
+
+})();
+
+
+ +
Nota: A atual implementação de const (declaração de constante) não é parte do ECMAScript 5. É suportada no Firefox e no Chrome (V8) e parcialmente suportada no Opera 9+ e no Safari. Ela  não é suportada nas versões do Internet Explorer 6 ao 9, ou na versão preview do Internet Explorer 10. const será definida no ECMAScript 6, mas com semânticas diferentes. Similarmente ao que acontece com variáveis definidas como let, constantes declaradas com const serão block-scoped, limitando seu escopo no bloco. Nós só usamos isso com propósito didático. Se você quer total compatibilidade com os navegadores, substitua todas as declarações const por declarações var.
+ +

Para mais informações, veja: Manipulando o histórico do navegador.

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/history_api/index.html b/files/pt-br/web/api/history_api/index.html new file mode 100644 index 0000000000..5b763f9a97 --- /dev/null +++ b/files/pt-br/web/api/history_api/index.html @@ -0,0 +1,257 @@ +--- +title: Manipulando o histórico do navegador +slug: Web/API/History_API +tags: + - Avançado + - DOM + - HTML5 + - Histórico +translation_of: Web/API/History_API +--- +

O objeto DOM {{ domxref("window") }} fornece acesso ao histórico do navegador através do objeto {{ domxref("window.history", "history") }}. Ele expõe métodos e propriedades úteis que permitem que você se mova para trás e para frente através do histórico de navegação do usuário, bem como -- iniciando com o HTML5 -- manipular o conteúdo da pilha de históricos.

+ + + +

Mover para trás e para a frente através do histórico do usuário é feito usando os métodos back(), forward() e go().

+ +

Movendo para frente e para trás

+ +

Para mover para trás no histórico, apenas faça:

+ +
window.history.back();
+
+ +

Isso funcionará exatamente como se o usuário clicasse no botão Voltar na barra de ferramentas do navegador.
+
+ Da mesma forma, você pode avançar (como se o usuário clicasse no botão Avançar), assim:

+ +
window.history.forward();
+
+ +

Movendo para um ponto específico no histórico

+ +

Você pode usar o método go() para carregar uma página específica do histórico. Cada página é identificada por sua posição relativa à página atual (sendo a página atual o indíce 0). 

+ +

Para retornar uma página (equivalente ao método back()):

+ +
window.history.go(-1);
+
+ +

Para avançar uma página (equivalente ao método forward()):

+ +
window.history.go(1);
+
+
+ +

O número de páginas do histórico pode ser determinado pela propriedade length:

+ +
const numberOfEntries = window.history.length;
+
+ +
Note: O Internet Explorer suporta URLs como argumento para o método go(); isso não é um comportamento padrão e não é suportado pelo Gecko.
+ +

Adicionando e modificando entradas

+ +

{{ gecko_minversion_header("2") }}

+ +

O HTML5 introduziu os métodos history.pushState() e history.replaceState(), que permitem adicionar e modificar entradas no histórico, respectivamente. Estes métodos funcionam em conjunto com o evento {{ domxref("window.onpopstate") }}.

+ +

Usar history.pushState() modifica a referência que é utilizada no cabeçalho HTTP para objetos XMLHttpRequest criados após a utilização do método. A referência será a URL do documento cuja janela é o this no momento de criação do objeto XMLHttpRequest.

+ +

Exemplo do método pushState()

+ +

Suponha que http://mozilla.org/foo.html executa o seguinte JavaScript:

+ +
const stateObj = { foo: "bar" };
+history.pushState(stateObj, "page 2", "bar.html");
+
+ +

Isto fará com que a barra URL mostre http://mozilla.org/bar.html, porém não fará com que o navegador carregue bar.html ou verifique se bar.html existe. 

+ +

Agora suponha que o usuário navegue para http://google.com e logo em seguida clique no botão Voltar. Nesse momento, a barra de URL mostrará http://mozilla.org/bar.html, e a página receberá um evento popstate cujo objeto de estado contém uma copia de stateObj se você ler o history.state você receberá o stateObj. O evento popstate não será disparado pois a página foi recarregada. A página carregada será bar.html.

+ +

Se clicarmos no botão Voltar novamente, a URL modificará para http://mozilla.org/foo.html, e o documento receberá um evento popstate, dessa vez com objeto de estado sendo nulo. Nesse momento, o documento também não altera seu conteúdo em relação ao passo anterior, porém o documento pode atualizar seu conteúdo manualmente após o recebimento do evento popstate.

+ +

O método pushState()

+ +

pushState() recebe três parâmetros: um objeto de estado, um título (que atualmente é ignorado) e (opcionalmente) uma URL. Vamos examinar cada um dos argumentos com mais detalhes:

+ + + +
Nota: No Gecko 2.0 {{ geckoRelease("2.0") }} até Gecko 5.0 {{ geckoRelease("5.0") }}, o objeto passado é serializado utilizando JSON. A partir do Gecko 6.0 {{ geckoRelease("6.0") }}, o objeto é serializado usando  o algorítmo de clonagem estruturada. Isso permite que uma variedade maior de objetos possam ser serializados.
+ +

De certa forma, chamar o método pushState() é similar a executar window.location = "#foo",  no sentido de que ambos criarão e ativarão uma nova entrada no histórico associado com o documento atual. Porém pushState() tem algumas vantagens:

+ + + +

Note que pushState() nunca causa a ativação de um evento hashchange, mesmo se a nova URL diferir somente na hash,

+ +

Em um documento XUL é criado o elemento XUL especificado.

+ +

Em outros documentos, é criado um elemento com um namespace null de URI.

+ +

O método replaceState()

+ +

history.replaceState() opera exatamente igual à history.pushState() com exceção de modificar a atual entrada no histórico ao invés de criar uma nova. Note que isso não impede a criação de uma nova entrada no histórico global do navegador.

+ +

replaceState() é particularmente útil quando você quer atualiza o objeto de estado ou a URL da atual entrada do histórico como resposta a alguma ação do usuário.

+ +
Nota: Em Gecko 2.0 {{ geckoRelease("2.0") }} até Gecko 5.0 {{ geckoRelease("5.0") }}, o objeto passado é serializado utilizando JSON. Começando do Gecko 6.0 {{ geckoRelease("6.0") }}, o objeto é serializado usando  o algorítmo de clonagem estruturada. Isso permite que uma variedade maior de objetos possam ser serializados.
+ +

Exemplo do método replaceState()

+ +

Suponha que http://mozilla.org/foo.html execute o seguinte JavaScript:

+ +
const stateObj = { foo: "bar" };
+history.pushState(stateObj, "page 2", "bar.html");
+
+
+ +

A explicação destas duas linhas acima pode ser encontrada na seção "Exemplo do método pushState()". Suponha, então, que http://mozilla.org/bar.html execute o seguinte JavaScript:

+ +
history.replaceState(stateObj, "page 3", "bar2.html");
+
+ +

Isso fará com que a barra de URL do navegador exiba http://mozilla.org/bar2.html, mas não fará com que o navegador carregue bar2.html ou cheque se bar2.html existe.

+ +

Suponha agora que o usuário navegue até http://www.microsoft.com e, em seguida, clique no botão voltar. Neste momento, a barra de URL mostrará http://mozilla.org/bar2.html. Caso o usuário clique novamente no botão voltar, a barra de URL mostrará http://mozilla.org/foo.html e ignorará completamente bar.html.

+ +

O evento popstate

+ +

O evento popstate é disparado sempre que a entrada do histórico ativo é alterada. Se a entrada do histórico ativa foi criada por uma chamada pushState ou afetada por uma chamada replaceState, a propriedade state do evento popstate contém uma cópia do objeto de estado da entrada do histórico.

+ +

Veja {{ domxref("window.onpopstate") }} para exemplo de utilização.

+ +

Lendo o estado atual

+ +

Quando sua página é carregada, ela pode ter um objeto de estado não nulo. Isso pode acontecer, por exemplo, se a página definir um objeto de estado (usando pushState() ou replaceState()) e, em seguida, o usuário reiniciar seu navegador. Quando sua página é recarregada, ela receberá um evento onload, mas nenhum evento popstate. No entanto, se você ler a propriedade history.state, receberá o objeto de estado que teria obtido se um popstate tivesse sido disparado.

+ +

Você pode ler o estado da entrada do histórico atual sem esperar por um evento popstate usando a propriedade history.state como o exemplo abaixo:

+ +
var currentState = history.state;
+
+ +

Exemplos

+ +

Para um exemplo completo de um web site AJAX, veja: Exemplo de navegação Ajax.

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG', "browsers.html#history", "History")}}{{Spec2('HTML WHATWG')}}Nenhuma alteração do {{SpecName("HTML5 W3C")}}.
{{SpecName('HTML5 W3C', "browsers.html#history", "History")}}{{Spec2('HTML5 W3C')}}Definição inicial
+ +

Compatibilidade de navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
RecursoChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
replaceState, pushState5{{CompatVersionUnknown}}{{ CompatGeckoDesktop("2.0") }}1011.505.0
history.state18{{CompatVersionUnknown}}{{ CompatGeckoDesktop("2.0") }}1011.506.0
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
RecursoAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
replaceState, pushState{{ CompatUnknown() }}{{CompatVersionUnknown}}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
history.state{{ CompatUnknown() }}{{CompatVersionUnknown}}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

Veja também

+ + + +

{{ languages( { "ja": "ja/DOM/Manipulating_the_browser_history"} ) }}

diff --git a/files/pt-br/web/api/htmlcanvaselement/getcontext/index.html b/files/pt-br/web/api/htmlcanvaselement/getcontext/index.html new file mode 100644 index 0000000000..c50cd97abb --- /dev/null +++ b/files/pt-br/web/api/htmlcanvaselement/getcontext/index.html @@ -0,0 +1,292 @@ +--- +title: HTMLCanvasElement.getContext() +slug: Web/API/HTMLCanvasElement/getContext +tags: + - API + - Canvas + - HTMLCanvasElement + - Referencia + - metodo +translation_of: Web/API/HTMLCanvasElement/getContext +--- +
{{APIRef("Canvas API")}}
+ +

O metodo HTMLCanvasElement.getContext() retorna um contexto de desenho no canvas, ou {{jsxref("null")}} se o contexto identificado não é suportado.

+ +

Syntax

+ +
canvas.getContext(contextType, contextAttributes);
+
+ +

Parametros

+ +
+
contextType
+
É um {{domxref("DOMString")}} contendo o contexto identificador definindo o contexto de desenho associado ao canvas.        Os valores possiveis são: +
    +
  • "2d", levando a criação de um objeto {{domxref("CanvasRenderingContext2D")}} representando uma  renderização bidimensional.
  • +
  • "webgl" (or "experimental-webgl") que criará um objeto {{domxref("WebGLRenderingContext")}} representando uma renderização tridimensional. Esse contexto está disponivel somente em browsers que implementam WebGL versão 1 (OpenGL ES 2.0).
  • +
  • "webgl2" que criará um objeto {{domxref("WebGL2RenderingContext")}} representando uma renderização tridimensional. Esse contexto está disponivel somente em browsers que implementam WebGL versão 2 (OpenGL ES 3.0). {{experimental_inline}}
  • +
  • "bitmaprenderer" que criará um  {{domxref("ImageBitmapRenderingContext")}} que apenas provê a funcionalidade de substituir o conteúdo do canvas pelo de um {{domxref("ImageBitmap")}}.
  • +
+ +
+

Note: O identificador "experimental-webgl" é usado em novas implementações do WebGL. Essas implementações ou ainda não passaram nos casos de teste, ou os drivers gráficos na plataforma ainda não estão estáveis. O Khronos Group certifica as implementações do WebGL sob certas regas de conformidade.

+
+
+
contextAttributes
+
+

Você pode usar alguns atributos de contexto quando criar o seu contexto de renderização, por exemplo:

+ +
canvas.getContext('webgl',
+                 { antialias: false,
+                   depth: false });
+ Atributos de contexto 2d: + +
    +
  • alpha: Boleano que indica se o canvas contém um canal alfa. Se definido como false, o browser saberá que o resultado será sempre opaco, o que pode acelerar o desenho de conteudo transparente e imagens.
  • +
  • {{non-standard_inline}} (Gecko only) willReadFrequently: Boleano que indica quando uma série de operações read-back estão planejadas. Isso forçará o uso de renderização 2D no canvas via software (ao invés de utilizar GPU) o que pode salvar memoria quando {{domxref("CanvasRenderingContext2D.getImageData", "getImageData()")}} for chamado frequentemente. Essa opção está disponivel somente, se a flag gfx.canvas.willReadFrequently.enable está definida como true (o que, por padrão, é o caso do B2G/Firefox OS apenas).
  • +
  • {{non-standard_inline}} (Blink only) storage: String que indica qual storage é usado ("persistent" por padrão).
  • +
+ Atributos de contexto WebGL: + +
    +
  • alpha: Boleano que indica se o canvas contém um buffer alfa.
  • +
  • depth: Boleano que indica que o buffer do desenho tem um buffer de profundidade de pelo menos 16 bits.
  • +
  • stencil: Boleano que indica que o buffer do desenho tem um buffer de stencil de pelo menos 8 bits.
  • +
  • antialias: Boleano que indica se deve realizar o anti-aliasing ou não.
  • +
  • premultipliedAlpha: Boleano que indica se o compositor da página vai assumir que o buffer do desenho contendo cores com alfa pré-multiplicado.
  • +
  • preserveDrawingBuffer: Se o valor é true os buffers não serão limpos e preservarão seus valores até serem limpos ou subrescritos pelo autor.
  • +
  • +

    failIfMajorPerformanceCaveat: Boleano que indica se um contexto será criado se a performance do sistema for baixa.

    +
  • +
+
+
+ +

Return value

+ +

Um {{domxref("RenderingContext")}} que pode ser:

+ + + +

Se o contextType não bater com um possivel contexto de desenho,null é retornado.

+ +

Examples

+ +

Dado este elemento {{HTMLElement("canvas")}}:

+ +
<canvas id="canvas" width="300" height="300"></canvas>
+
+ +

Você pega um contexto 2d do canvas com o código a seguir:

+ +
var canvas = document.getElementById('canvas');
+var ctx = canvas.getContext('2d');
+console.log(ctx); // CanvasRenderingContext2D { ... }
+
+ +

Agora você tem contexto de renderização 2d para o canvas e você pode desenhar nele.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "scripting.html#dom-canvas-getcontext", "HTMLCanvasElement.getContext")}}{{Spec2('HTML WHATWG')}}Nenhuma mudança desde o ultimo snapshot, {{SpecName('HTML5 W3C')}}
{{SpecName('HTML5.1', "scripting-1.html#dom-canvas-getcontext", "HTMLCanvasElement.getContext")}}{{Spec2('HTML5.1')}} 
{{SpecName('HTML5 W3C', "scripting-1.html#dom-canvas-getcontext", "HTMLCanvasElement.getContext")}}{{Spec2('HTML5 W3C')}}Snapshot do {{SpecName('HTML WHATWG')}} contendo a definição inicial.
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support (2d context){{CompatChrome(4)}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.2")}}{{CompatIE(9)}}{{CompatOpera(9)}}{{CompatSafari(3.1)}}
webgl context{{CompatChrome(9)}}[1]
+ {{CompatChrome(33)}}
{{CompatVersionUnknown}}{{CompatGeckoDesktop('1.9.2')}}[1]
+ {{CompatGeckoDesktop('24')}}
11.0[2]9.0[3]5.1[2]
webgl2 context {{CompatChrome(56)}}{{CompatUnknown}}{{CompatGeckoDesktop('25')}}[4]{{CompatNo}}{{CompatNo}}{{CompatNo}}
2d alpha context attribute32{{CompatUnknown}}{{CompatGeckoDesktop(30)}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}
+

failIfMajorPerformanceCaveat attribute

+
{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop(41)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
bitmaprenderer context{{CompatNo}}{{CompatUnknown}}{{CompatGeckoDesktop(46)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support (2d context){{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.9.2")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
webgl context{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}[2]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
webgl2 context {{CompatNo}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
2d alpha context attribute{{CompatNo}}{{CompatNo}}{{CompatUnknown}}{{CompatGeckoMobile(30)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
failIfMajorPerformanceCaveat attribute{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(41)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
bitmaprenderer context{{CompatNo}}{{CompatNo}}{{CompatUnknown}}{{CompatGeckoMobile(46)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] Chrome 9 e Gecko 1.9.2 inicialmente implementaram isso como um experimental-webgl. Desde o Chrome 33 e Gecko 24 é implementado como definido pelo padrão: webgl.

+ +

[2] Internet Explorer 11, WebKit 5.1 e Firefox Mobile implementaram isso como um experimental-webgl.

+ +

[3] Opera 9 implementou isso como um experimental-webgl, ativado nas preferencias do usuario, na versão 15.0 a preferencia de usuario foi removida.

+ +

[4] Gecko 25 implementou isso como um "experimental-webgl2" ativado na preferencia do usuario webgl.enable-prototype-webgl2. Apartir do Gecko 42, a string "webgl2"é usada na mesma configuração e "experimental-webgl2" não é mais aceito.

+ +

See also

+ + diff --git a/files/pt-br/web/api/htmlcanvaselement/height/index.html b/files/pt-br/web/api/htmlcanvaselement/height/index.html new file mode 100644 index 0000000000..fd737da382 --- /dev/null +++ b/files/pt-br/web/api/htmlcanvaselement/height/index.html @@ -0,0 +1,79 @@ +--- +title: HTMLCanvasElement.height +slug: Web/API/HTMLCanvasElement/height +tags: + - API + - Canvas + - HTMLCanvasElement + - Propriedade + - altura +translation_of: Web/API/HTMLCanvasElement/height +--- +
+
+
{{APIRef("Canvas API")}}
+
+
+ +

A propriedade HTMLCanvasElement.height é um inteiro positivo que reflete o atributo {{htmlattrxref("height", "canvas")}} do elemento HTML {{HTMLElement("canvas")}} interpretado em pixels no CSS. Quando o atributo não é especificado, ou se for definido como um valor inválido, como um inteiro negativo, o valor padrão de 150 será usado.

+ +

Essa é uma de duas propriedades, que controla o tamanho do canvas, sendo a outra {{domxref("HTMLCanvasElement.width")}}.

+ +

Sintaxe

+ +
var pxl = canvas.height;
+canvas.height = pxl;
+
+ +

Exemplos

+ +

Dado este elemento {{HTMLElement("canvas")}}:

+ +
<canvas id="canvas" width="300" height="300"></canvas>
+
+ +

Você pode capturar a altura do canvas com o seguinte código:

+ +
var canvas = document.getElementById('canvas');
+console.log(canvas.height); // 300
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "scripting.html#attr-canvas-height", "HTMLCanvasElement.height")}}{{Spec2('HTML WHATWG')}}No change since the latest snapshot, {{SpecName('HTML5 W3C')}}
{{SpecName('HTML5.1', "scripting-1.html#attr-canvas-height", "HTMLCanvasElement.height")}}{{Spec2('HTML5.1')}} 
{{SpecName('HTML5 W3C', "scripting-1.html#attr-canvas-height", "HTMLCanvasElement.height")}}{{Spec2('HTML5 W3C')}}Snapshot of the {{SpecName('HTML WHATWG')}} containing the initial definition.
+ +

Compatibilidade entre os browsers

+ + + +

{{Compat("api.HTMLCanvasElement.height")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/htmlcanvaselement/index.html b/files/pt-br/web/api/htmlcanvaselement/index.html new file mode 100644 index 0000000000..c2121aab9a --- /dev/null +++ b/files/pt-br/web/api/htmlcanvaselement/index.html @@ -0,0 +1,264 @@ +--- +title: HTMLCanvasElement +slug: Web/API/HTMLCanvasElement +tags: + - API + - Canvas + - HTML DOM + - Interface + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/API/HTMLCanvasElement +--- +
+
{{APIRef("Canvas API")}}
+
+ +

The HTMLCanvasElement interface provides properties and methods for manipulating the layout and presentation of canvas elements. The HTMLCanvasElement interface also inherits the properties and methods of the {{domxref("HTMLElement")}} interface.

+ +

{{InheritanceDiagram(600, 120)}}

+ +

Properties

+ +

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

+ +
+
{{domxref("HTMLCanvasElement.height")}}
+
Is a positive integer reflecting the {{htmlattrxref("height", "canvas")}} HTML attribute of the {{HTMLElement("canvas")}} element interpreted in CSS pixels. When the attribute is not specified, or if it is set to an invalid value, like a negative, the default value of 150 is used.
+
{{domxref("HTMLCanvasElement.mozOpaque")}} {{non-standard_inline}}
+
Is a {{jsxref("Boolean")}} reflecting the {{htmlattrxref("moz-opaque", "canvas")}} HTML attribute of the {{HTMLElement("canvas")}} element. It lets the canvas know whether or not translucency will be a factor. If the canvas knows there's no translucency, painting performance can be optimized.
+
{{domxref("HTMLCanvasElement.width")}}
+
Is a positive integer reflecting the {{htmlattrxref("width", "canvas")}} HTML attribute of the {{HTMLElement("canvas")}} element interpreted in CSS pixels. When the attribute is not specified, or if it is set to an invalid value, like a negative, the default value of 300 is used.
+
{{domxref("HTMLCanvasElement.mozPrintCallback")}}{{non-standard_inline}}
+
Is a function that is Initially null, Web content can set this to a JavaScript function that will be called if the page is printed. This function can then redraw the canvas at a higher resolution that is suitable for the printer being used. See this blog post.
+
+ +

Methods

+ +

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

+ +
+
{{domxref("HTMLCanvasElement.captureStream()")}} {{experimental_inline}}
+
Returns a {{domxref("CanvasCaptureMediaStream")}} that is a real-time video capture of the surface of the canvas.
+
{{domxref("HTMLCanvasElement.getContext()")}}
+
Returns a drawing context on the canvas, or null if the context ID is not supported. A drawing context lets you draw on the canvas. Calling getContext with "2d" returns a {{domxref("CanvasRenderingContext2D")}} object, whereas calling it with "experimental-webgl" (or "webgl") returns a {{domxref("WebGLRenderingContext")}} object. This context is only available on browsers that implement WebGL.
+
{{domxref("HTMLCanvasElement.toDataURL()")}}
+
Returns a data-URL containing a representation of the image in the format specified by the type parameter (defaults to png). The returned image is in a resolution of 96dpi.
+
{{domxref("HTMLCanvasElement.toBlob()")}}
+
Creates a {{domxref("Blob")}} object representing the image contained in the canvas; this file may be cached on the disk or stored in memory at the discretion of the user agent.
+
{{domxref("HTMLCanvasElement.transferControlToOffscreen()")}} {{experimental_inline}}
+
Transfers control to an {{domxref("OffscreenCanvas")}} object, either on the main thread or on a worker.
+
{{domxref("HTMLCanvasElement.mozGetAsFile()")}} {{non-standard_inline}} {{deprecated_inline}}
+
Returns a {{domxref("File")}} object representing the image contained in the canvas; this file is a memory-based file, with the specified name. If type is not specified, the image type is image/png.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Media Capture DOM Elements', '#html-media-element-media-capture-extensions', 'HTMLCanvasElement')}}{{Spec2('Media Capture DOM Elements')}}Adds the method captureStream().
{{SpecName('HTML WHATWG', "#the-canvas-element", "HTMLCanvasElement")}}{{Spec2('HTML WHATWG')}}The method getContext() now returns a {{domxref("RenderingContext")}} rather than an opaque object.
+ The methods probablySupportsContext(), setContext() and transferControlToProxy()have been added.
{{SpecName('HTML5.1', "scripting-1.html#the-canvas-element", "HTMLCanvasElement")}}{{Spec2('HTML5.1')}} 
{{SpecName('HTML5 W3C', "scripting-1.html#the-canvas-element", "HTMLCanvasElement")}}{{Spec2('HTML5 W3C')}}Initial definition.
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support (2D context)4.0{{CompatVersionUnknown}}{{CompatGeckoDesktop('1.9.2')}}9.09.0 [1]3.1
toBlob()50{{CompatNo}}{{CompatGeckoDesktop('19')}} [2]{{CompatUnknown}}{{CompatUnknown}}{{CompatNo}} (bug 71270)
probablySupportsContext(),
+ setContext(),
+ transferControlToProxy() {{obsolete_inline}}
{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
mozGetAsFile() {{non-standard_inline}} {{deprecated_inline}}{{CompatNo}}{{CompatNo}}{{CompatGeckoDesktop('2')}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
captureStream() {{experimental_inline}}{{CompatNo}}{{CompatNo}}{{CompatGeckoDesktop('41')}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
transferControlToOffscreen() {{experimental_inline}}{{CompatNo}}{{CompatNo}}{{CompatGeckoDesktop(44)}} [3]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support (2D context)2.1{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}10.0 [1]3.2
webgl context{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}} as experimental-webgl{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
toBlob(){{CompatNo}} (bug 67587)50{{CompatNo}}{{CompatGeckoMobile('18')}} [2]{{CompatUnknown}}{{CompatUnknown}}{{CompatNo}} (bug 71270)
probablySupportsContext(),
+ setContext(),
+ transferControlToProxy() {{obsolete_inline}}
{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
mozGetAsFile() {{non-standard_inline}} {{deprecated_inline}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile('2')}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
captureStream() {{experimental_inline}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile('41')}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
transferControlToOffscreen() {{experimental_inline}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile(44)}} [3]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] Opera Mini 5.0 and later has partial support.

+ +

[2] Support for the third parameter, has been added in Gecko 25 only: when used with the "image/jpeg" type, this argument specifies the image quality.

+ +

[3] This feature is behind a feature preference setting. In about:config, set gfx.offscreencanvas.enabled to true.

+ +

See also

+ + diff --git a/files/pt-br/web/api/htmlcanvaselement/todataurl/index.html b/files/pt-br/web/api/htmlcanvaselement/todataurl/index.html new file mode 100644 index 0000000000..503f9cb636 --- /dev/null +++ b/files/pt-br/web/api/htmlcanvaselement/todataurl/index.html @@ -0,0 +1,157 @@ +--- +title: HTMLCanvasElement.toDataURL() +slug: Web/API/HTMLCanvasElement/toDataURL +tags: + - API + - Canvas + - HTMLCanvasElement + - Imagens +translation_of: Web/API/HTMLCanvasElement/toDataURL +--- +
+
+
{{APIRef("Canvas API")}}
+
+
+ +

O método HTMLCanvasElement.toDataURL() retorna uma data URI, contendo uma representação da imagem no formato especificado pelo parâmetro type (por padrão, esse valor é PNG). A resolução da imagem retornada é de 96 dpi.

+ + + +

Sintaxe

+ +
canvas.toDataURL(type, encoderOptions);
+
+ +

Parâmetros

+ +
+
type {{optional_inline}}
+
Uma {{domxref("DOMString")}} indicando o formato da imagem. Por padrão, o formato definido é image/png.
+
encoderOptions {{optional_inline}}
+
Um {{jsxref("Number")}} entre 0 e 1, indicando a qualidade da imagem solicitada pelo tipo image/jpeg ou image/webp.
+ Se esse argumento for outro valor que não de 0 a 1, então o valor padrão (0.92) será usado. Outros valores serão ignorados.
+
+ +

Valor retornado

+ +

Uma {{domxref("DOMString")}} contendo a data URI solicitada.

+ +

Exemplos

+ +

Dado este elemento {{HTMLElement("canvas")}}:

+ +
<canvas id="canvas" width="5" height="5"></canvas>
+
+ +

Você poderá capturar a data-URL do canvas com as seguintes linhas:

+ +
var canvas = document.getElementById('canvas');
+var dataURL = canvas.toDataURL();
+console.log(dataURL);
+// "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNby
+// blAAAADElEQVQImWNgoBMAAABpAAFEI8ARAAAAAElFTkSuQmCC"
+
+ +

Defindo a qualidade de imagens jpeg

+ +
var fullQuality = canvas.toDataURL('image/jpeg', 1.0);
+// data:image/jpeg;base64,/9j/4AAQSkZJRgABAQ...9oADAMBAAIRAxEAPwD/AD/6AP/Z"
+var mediumQuality = canvas.toDataURL('image/jpeg', 0.5);
+var lowQuality = canvas.toDataURL('image/jpeg', 0.1);
+
+ +

Exemplo: Alterando imagens dinamicamente

+ +

Você poderá utilizar esta técnica em associação com os eventos do mouse para alterar dinamicamente uma imagem (escala de cinza vs. cor, neste exemplo):

+ +

HTML

+ +
<img class="grayscale" src="myPicture.png" alt="Description of my picture" />
+ +

JavaScript

+ +
window.addEventListener('load', removeColors);
+
+function showColorImg() {
+  this.style.display = 'none';
+  this.nextSibling.style.display = 'inline';
+}
+
+function showGrayImg() {
+  this.previousSibling.style.display = 'inline';
+  this.style.display = 'none';
+}
+
+function removeColors() {
+  var aImages = document.getElementsByClassName('grayscale'),
+      nImgsLen = aImages.length,
+      oCanvas = document.createElement('canvas'),
+      oCtx = oCanvas.getContext('2d');
+  for (var nWidth, nHeight, oImgData, oGrayImg, nPixel, aPix, nPixLen, nImgId = 0; nImgId < nImgsLen; nImgId++) {
+    oColorImg = aImages[nImgId];
+    nWidth = oColorImg.offsetWidth;
+    nHeight = oColorImg.offsetHeight;
+    oCanvas.width = nWidth;
+    oCanvas.height = nHeight;
+    oCtx.drawImage(oColorImg, 0, 0);
+    oImgData = oCtx.getImageData(0, 0, nWidth, nHeight);
+    aPix = oImgData.data;
+    nPixLen = aPix.length;
+    for (nPixel = 0; nPixel < nPixLen; nPixel += 4) {
+      aPix[nPixel + 2] = aPix[nPixel + 1] = aPix[nPixel] = (aPix[nPixel] + aPix[nPixel + 1] + aPix[nPixel + 2]) / 3;
+    }
+    oCtx.putImageData(oImgData, 0, 0);
+    oGrayImg = new Image();
+    oGrayImg.src = oCanvas.toDataURL();
+    oGrayImg.onmouseover = showColorImg;
+    oColorImg.onmouseout = showGrayImg;
+    oCtx.clearRect(0, 0, nWidth, nHeight);
+    oColorImg.style.display = "none";
+    oColorImg.parentNode.insertBefore(oGrayImg, oColorImg);
+  }
+}
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "scripting.html#dom-canvas-todataurl", "HTMLCanvasElement.toDataURL")}}{{Spec2('HTML WHATWG')}}No change since the latest snapshot, {{SpecName('HTML5 W3C')}}
{{SpecName('HTML5.1', "scripting-1.html#dom-canvas-todataurl", "HTMLCanvasElement.toDataURL")}}{{Spec2('HTML5.1')}}
{{SpecName('HTML5 W3C', "scripting-1.html#dom-canvas-todataurl", "HTMLCanvasElement.toDataURL")}}{{Spec2('HTML5 W3C')}}Snapshot of the {{SpecName('HTML WHATWG')}} containing the initial definition.
+ +

Compatibilidade entre navegadores

+ + + +

{{Compat("api.HTMLCanvasElement.toDataURL")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/htmlcollection/index.html b/files/pt-br/web/api/htmlcollection/index.html new file mode 100644 index 0000000000..4d462b4b6a --- /dev/null +++ b/files/pt-br/web/api/htmlcollection/index.html @@ -0,0 +1,68 @@ +--- +title: HTMLCollection +slug: Web/API/HTMLCollection +translation_of: Web/API/HTMLCollection +--- +

{{APIRef("HTML DOM")}}

+ +

A interface HTMLCollection representa uma coleção genérica (objeto array) de elementos (na ordem em que aparecem no documento) e oferece métodos e propriedades para selecioná-los da lista.

+ +
Nota: Esta interface é chamada HTMLCollection por razões históricas (antes do DOM4, coleções implementadas por esta interface somente podiam ter elementos HTML).
+ +

Uma coleção HTMLCollection de um HTML DOM está linkada com o documento; ela será automaticamente atualizada quando o documento for modificado.

+ +

Propriedades

+ +
+
{{domxref("HTMLCollection.length")}} {{readonlyInline}}
+
Retorna o número de itens da coleção.
+
+ +

Métodos

+ +
+
{{domxref("HTMLCollection.item()")}}
+
Retorna um nó especificado por index da lista. o primeiro index da lista é 0. Retorna null se index não existir na lista.
+
{{domxref("HTMLCollection.namedItem()")}}
+
Retorna o nó especificado pelo ID ou, caso não tenha ID, o item cuja propriedade name seja igual à pesquisa. Pesquisa por name só é feita em último caso, somente em HTML, e somente se os elementos referenciados suportarem o atributo name. Retorna null se nenhum nó corresponder ao nome pesquisado.
+
+ +

Uso no JavaScript

+ +

HTMLCollection expõe seus membros diretamente como propriedades, tanto por nome quanto por índice. IDs HTML podem conter : e . como caracteres válidos, o que fará necessária a utilização de colchetes para acessar as propriedades. Atualmente HTMLCollection não reconhece IDs puramente numéricos, o que pode causar conflitos com acesso em formato array, apesar do HTML5 os permitir.

+ +

Por exemplo, assumindo que há um elemento <form> no documento e seu id é "myForm":

+ +
var elem1, elem2;
+
+// document.forms é um HTMLCollection
+
+elem1 = document.forms[0];
+elem2 = document.forms.item(0);
+
+alert(elem1 === elem2); // exibe: "true"
+
+elem1 = document.forms.myForm;
+elem2 = document.forms.namedItem("myForm");
+
+alert(elem1 === elem2); // exibe: "true"
+
+elem1 = document.forms["named.item.with.periods"];
+ +

Compatibilidade entre Browsers

+ +

Diferentes browsers se comportam de maneira diferente quando um os mais elementos são pesquisados pela string utilizada  como índice (ou o argumento namedItem). Firefox 8 se comporta como especificado no DOM 2 e no DOM 4, retornando o primeiro elemento encontrado. WebKit browsers e o Internet Explorer, neste caso, retornam outro HTMLCollection e o Opera retorna um {{domxref("NodeList")}} com todos os elementos encontrados.

+ +

Especificações

+ + + +

Veja também

+ + diff --git a/files/pt-br/web/api/htmlcontentelement/getdistributednodes/index.html b/files/pt-br/web/api/htmlcontentelement/getdistributednodes/index.html new file mode 100644 index 0000000000..fa6b3bb8dc --- /dev/null +++ b/files/pt-br/web/api/htmlcontentelement/getdistributednodes/index.html @@ -0,0 +1,100 @@ +--- +title: HTMLContentElement.getDistributedNodes() +slug: Web/API/HTMLContentElement/getDistributedNodes +tags: + - Componente web + - HTML DOM + - HTMLContentElement + - HTMLContentElement.getDistributedNodes() + - Property + - getDistributedNodes() +translation_of: Web/API/HTMLContentElement/getDistributedNodes +--- +

{{ APIRef("Web Components") }}

+ +

O método HTMLContentElement.getDistributedNodes() retorna um static {{domxref("NodeList")}} do {{glossary("distributed nodes")}} associado com este elemento <content>.

+ +

Syntaxe

+ +
var nodeList = object.getDistributedNodes()
+
+ +

Exemplo

+ +
//Pegue os nós distribuídos
+var nodes = myContentObject.getDistributedNodes();
+ +

Specificações

+ + + + + + + + + + + + + + +
SpecificaçõesStatusComentário
{{SpecName('Shadow DOM', '#the-content-element', 'content')}}{{Spec2('Shadow DOM')}} 
+ +

Compatibilidade do browser

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
ComponenteChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Supporte básico35{{CompatGeckoDesktop("28")}} [1]{{CompatNo}}26{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support37{{CompatGeckoMobile("28")}} [1]{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Se Shadow DOM não é habilitado no Firefox, <content> elementos se comportará como {{domxref("HTMLUnknownElement")}}. Shadow DOM foi primeiro implementado em Firefox 28 e está atrás de uma preferência, dom.webcomponents.enabled, ao qual é desabilitado por padrão.

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/htmlcontentelement/index.html b/files/pt-br/web/api/htmlcontentelement/index.html new file mode 100644 index 0000000000..b3a23164a6 --- /dev/null +++ b/files/pt-br/web/api/htmlcontentelement/index.html @@ -0,0 +1,116 @@ +--- +title: HTMLContentElement +slug: Web/API/HTMLContentElement +tags: + - ContentElement + - Deprecated_header + - HTMLContentElement + - HTMLElement + - Web Components + - elemento depreciado + - shadow dom +translation_of: Web/API/HTMLContentElement +--- +

{{ APIRef("Web Components") }}

+ +

{{Deprecated_header}}

+ +

A interface do HTMLContentElement representa um {{HTMLElement("content")}} Element HTML, ao qual é usado em Shadow DOM

+ +

Propriedades

+ +

Esta interface herda as propriedades de {{domxref("HTMLElement")}}.

+ +
+
{{domxref("HTMLContentElement.select")}}
+
é um {{domxref("DOMString")}} que reflete o {{ htmlattrxref("select", "content") }} attributo HTML . O valor é uma lista de vírgula separada dos seletores CSS que selecionam o conteúdo para inserir em lugar do elemento <content>.
+
+ +

Méthodos

+ +

Esta interface herda os méthodos de {{domxref("HTMLElement")}}.

+ +
+
{{domxref("HTMLContentElement.getDistributedNodes()")}}
+
Returna um static {{domxref("NodeList")}} do {{glossary("distributed nodes")}} associado com este elemento <content>
+
+ +

Specificações

+ + + + + + + + + + + + + + +
SpecificaçõesStatusCommentários
{{SpecName('Shadow DOM', '#the-content-element', 'content')}}{{Spec2('Shadow DOM')}} 
+ +

Compatibilidade do browser

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
ComponentesChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte Básico35{{CompatGeckoDesktop("28")}} [1]{{CompatNo}}26{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support37{{CompatGeckoMobile("28")}} [1]{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Se Shadow DOM não é habilitado no Firefox, <content> elementos vai se comportar como {{domxref("HTMLUnknownElement")}}. Shadow DOM foi a primeira implementação do Firefox 28 e está atrásde uma preferência , dom.webcomponents.enabled, qual é desabilitado por padrão.

+ +

Veja também

+ + + +
+
 
+
diff --git a/files/pt-br/web/api/htmlcontentelement/seletor/index.html b/files/pt-br/web/api/htmlcontentelement/seletor/index.html new file mode 100644 index 0000000000..63fae05c69 --- /dev/null +++ b/files/pt-br/web/api/htmlcontentelement/seletor/index.html @@ -0,0 +1,98 @@ +--- +title: HTMLContentElement.select +slug: Web/API/HTMLContentElement/Seletor +tags: + - API + - HTMLContentElement + - HTMLContentElement.select + - Select +translation_of: Web/API/HTMLContentElement/select +--- +

{{ APIRef("Web Components") }}

+ +

A propriedade HTMLContentElement.select reflete o atributo selecionado. É um {{domxref("DOMString")}} contendo uma lista de spaço-separado de seletores CSS que seleciona o conteúdo para inserir em lugar do elemento <content>.

+ +

Sintaxe

+ +
object.select = "CSSselector CSSselector ...";
+
+ +

Exemplo

+ +
// Select <h1> elements and elements with class="error"
+myContentObject.select = "h1 .error";
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçõesStatusCommentário
{{SpecName('Shadow DOM', '#the-content-element', 'content')}}{{Spec2('Shadow DOM')}} 
+ +

Compatibilidade do browser

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
ComponenteChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico35{{CompatGeckoDesktop("28")}} [1]{{CompatNo}}26{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Suporte básico37{{CompatGeckoMobile("28")}} [1]{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Se Shadow DOM não estiver habilitado no Firefox, os elementos <content> se comportarão como {{domxref("HTMLUnknownElement")}}. Shadow DOM foi o primeiro implementado no Firefox 28 e está atrás de uma preferência, dom.webcomponents.enabled, ao qual é desabilitado por padrão.

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/htmldivelement/index.html b/files/pt-br/web/api/htmldivelement/index.html new file mode 100644 index 0000000000..f658b94f06 --- /dev/null +++ b/files/pt-br/web/api/htmldivelement/index.html @@ -0,0 +1,133 @@ +--- +title: HTMLDivElement +slug: Web/API/HTMLDivElement +tags: + - API + - HTMLDivElement + - Interface + - PrecisaNovoLayout + - Referência(2) +translation_of: Web/API/HTMLDivElement +--- +
+
{{ APIRef("HTML DOM") }}
+
+ +
 
+ +

A interface HTMLDivElement fornece propriedades especiais ( além da interface normal {{domxref ("HTMLElement")}} que também está a sua disposição por herança ) para manipular elementos div.

+ +

{{InheritanceDiagram(600,120)}}

+ +

Propriedades

+ +

As propriedades são herdadas de seu pai, {{domxref("HTMLElement")}}.

+ + + + + + + + + + + + + + +
NomeTipoDescrição
align {{obsolete_inline}}{{domxref("DOMString")}}Propriedade enumerada indicando alinhamento  dos conteúdos do elemento, respeitando ao contexto geral. Os valores possíveis são "left", "right", "justify", e"center".
+ +

Métodos

+ +

Nenhum método específico; os métodos são herdados de seu pai, {{domxref ("HTMLElement")}}.

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG', "grouping-content.html#the-div-element", "HTMLDivElement")}}{{Spec2('HTML WHATWG')}}No change from {{SpecName("HTML5 W3C")}}.
{{SpecName('HTML5 W3C', "grouping-content.html#the-div-element", "HTMLDivElement")}}{{Spec2('HTML5 W3C')}}No change from {{SpecName("DOM2 HTML")}}.
{{SpecName('DOM2 HTML', 'html.html#ID-22445964', 'HTMLDivElement')}}{{Spec2('DOM2 HTML')}}No change from {{SpecName("DOM1")}}.
{{SpecName('DOM1', 'level-one-html.html#ID-22445964', 'HTMLDivElement')}}{{Spec2('DOM1')}}Initial definition.
+ +

Compatibilidade de Navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico{{CompatVersionUnknown}}{{CompatGeckoDesktop(1.0)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatGeckoMobile(1.0)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

 

+ +

Ver também

+ + diff --git a/files/pt-br/web/api/htmlelement/blur/index.html b/files/pt-br/web/api/htmlelement/blur/index.html new file mode 100644 index 0000000000..25a2273aec --- /dev/null +++ b/files/pt-br/web/api/htmlelement/blur/index.html @@ -0,0 +1,89 @@ +--- +title: HTMLElement.blur() +slug: Web/API/HTMLElement/blur +tags: + - API + - DOM HTML + - Foco + - HTMLElement + - Referencia + - metodo +translation_of: Web/API/HTMLOrForeignElement/blur +--- +
{{ APIRef("HTML DOM") }}
+ +

O método HTMLElement.blur() remove o foco do teclado no elemento corrente.

+ +

Sintaxe

+ +
elemento.blur();
+ +

Exemplos

+ +

Removendo o foco de um input de texto

+ +

HTML

+ +
<input type="text" id="meuTexto" value="Texto Exemplo">
+<br><br>
+<button type="button" onclick="focusInput()">Clique para definir o foco</button>
+<button type="button" onclick="blurInput()">Clique para remover o foco</button>
+ +

JavaScript

+ +
function focusInput() {
+  document.getElementById('meuTexto').focus();
+}
+function blurInput() {
+  document.getElementById('meuTexto').blur();
+}
+ +

Resultado

+ +

{{ EmbedLiveSample('Remove_focus_from_a_text_input') }}

+ +

Especificação

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG', 'editing.html#dom-blur', 'blur')}}{{Spec2('HTML WHATWG')}} 
{{SpecName('HTML5.1', 'editing.html#blur()-0', 'blur')}}{{Spec2('HTML5.1')}} 
{{SpecName('HTML5 W3C', 'editing.html#dom-blur', 'blur')}}{{Spec2('HTML5 W3C')}} 
{{SpecName('DOM2 HTML', 'html.html#ID-28216144', 'blur')}}{{Spec2('DOM2 HTML')}} 
+ +

Compatibilidade com navegadores

+ + + +

{{Compat("api.HTMLElement.blur")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/htmlelement/click/index.html b/files/pt-br/web/api/htmlelement/click/index.html new file mode 100644 index 0000000000..8bfe8a9d66 --- /dev/null +++ b/files/pt-br/web/api/htmlelement/click/index.html @@ -0,0 +1,115 @@ +--- +title: HTMLElement.click() +slug: Web/API/HTMLElement/click +tags: + - API + - HTML DOM + - HTMLElement + - Method + - Reference +translation_of: Web/API/HTMLElement/click +--- +
+
{{ APIRef("HTML DOM") }}
+
+ +

O método HTMLElement.click() simula o clique do mouse em um elemento.

+ +

Quando clique é usado com elementos que o suportam (por exemplo, um dos {{HTMLElement ("input")}} tipos listados acima), ele também dispara evento de clique do elemento que vai propagar pelos elementos mais acima na árvore de documentos (ou cadeia do evento) e disparando seus eventos de clique também. No entanto, o evento de clique, propagado como bubble, não vai iniciar a navegação do elemento {{HTMLElement("a")}} como se uma verdadeiro clique do mouse tivesse sido recebido. 

+ +

Sintaxe

+ +
elt.click()
+ +

Especificação

+ + + + + + + + + + + + + + + + +
SpecificationStatusComentário
{{SpecName('DOM2 HTML', 'html.html#ID-2651361')}}{{Spec2('DOM2 HTML')}}Initial definition
+ +

Browser compatibilidade

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support20[3]5[1]{{CompatVersionUnknown}}{{CompatVersionUnknown}}[2]6[3]
input@file (limited){{CompatVersionUnknown}}4{{CompatVersionUnknown}}12.10{{CompatVersionUnknown}}
input@file (full){{CompatVersionUnknown}}4{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Antes Gecko 5.0 {{geckoRelease("5.0")}}, Gecko não implementa o método de clique em outros elementos que podem ser esperados para responder a cliques do mouse como links (elementos {{HTMLElement("a")}}), nem seria necessariamente acionado o evento clique de outros elementos.

+ +

[2] Em versões do Opera o método click() irá silenciosamente ser ignorado se for realizado baseado no motor de layout Presto em {{HTMLElement("input")}} com o atributo type definido para o arquivo e seu CSS {{cssxref('display')}} propriedade definida como nenhum.

+ +

[3] As versões mais antigas tinham HTMLInputElement.click() e HTMLButtonElement.click() apenas.

diff --git a/files/pt-br/web/api/htmlelement/contenteditable/index.html b/files/pt-br/web/api/htmlelement/contenteditable/index.html new file mode 100644 index 0000000000..22d356ae0d --- /dev/null +++ b/files/pt-br/web/api/htmlelement/contenteditable/index.html @@ -0,0 +1,102 @@ +--- +title: HTMLElement.contentEditable +slug: Web/API/HTMLElement/contentEditable +translation_of: Web/API/HTMLElement/contentEditable +--- +
+
{{APIRef("HTML DOM")}}
+
+ +

A propriedade HTMLElement.contentEditable é usada para indicar se o elemento é editável ou não. Esse atributo enumerado pode ter os seguintes valores:

+ + + +

Você pode usar a propriedade {{domxref( "HTMLElement.isContentEditable")}} para testar o valor calculado {{domxref ("Boolean")}} desta propriedade.

+ +

Sintaxe

+ +
editable = element.contentEditable element.contentEditable= "true"
+
+ +

Especificação

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG', 'interaction.html#contenteditable', 'contenteditable')}}{{Spec2('HTML WHATWG')}}Initial definition
+ +

Compatibilidade Browsers

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support11{{CompatGeckoDesktop(1.9)}}6[1]10.63.2
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support3{{CompatGeckoMobile(1.9)}}6[1]{{CompatNo}}5
+
+ +

[1] Internet Explorer has a bunch of bugs regarding the implementation of this feature. IE10 crashes in some cases when editing lists (bug 796187). IE11+ uses invalid positioning for caret when an element is floated (bug 858749). In IE9-10 the window freezes when using mousewheel while dragging (bug 809254). IE10-11 does not fire the input event (bug 794285). IE10 crashes after selecting "Cut" from the context menu (bug 801770). IE11+ does not allow placing the caret in an empty table cell (bug 807199). IE10 does not fire contextmenu event when right-clicking on misspelled words (bug 774350). IE11 appends {{HTMLElement("br")}} elements to {{HTMLElement("body")}} when showing/hiding an {{HTMLElement("iframe")}} with contenteditable document inside (bug 864804). IE11 does not allow disabling resize handles for images/inputs (bug 907422).

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/htmlelement/contextmenu/index.html b/files/pt-br/web/api/htmlelement/contextmenu/index.html new file mode 100644 index 0000000000..e03c61a256 --- /dev/null +++ b/files/pt-br/web/api/htmlelement/contextmenu/index.html @@ -0,0 +1,44 @@ +--- +title: HTMLElement.contextMenu +slug: Web/API/HTMLElement/contextMenu +tags: + - API + - Depreciado + - Elemento + - HTML + - HTML DOM + - Propriedade + - Referencia + - UX +translation_of: Web/API/HTMLElement/contextMenu +--- +
{{APIRef("HTML DOM")}}{{deprecated_header()}} +

A propriedade HTMLElement.contextMenu refere-se ao menu de contexo atribuído aum elemento usando o {{htmlattrxref("contextmenu")}} atributo. O menu em sí é criado usando o {{HTMLElement("menu")}} elemento.

+ +

Sintaxe

+ +
var elementContextMenu = element.contextMenu;
+
+ +

Exemplo

+ +
var contextMenu = document.getElementById("element").contextMenu;
+
+// Altere o label da primeira entrada do menu
+contextMenu.firstElementChild.label = "New label";
+
+ +

Compatibilidade de navegadores

+ + + +

{{Compat("api.HTMLElement.contextMenu")}}

+ +

Veja também

+ + +
diff --git a/files/pt-br/web/api/htmlelement/dataset/index.html b/files/pt-br/web/api/htmlelement/dataset/index.html new file mode 100644 index 0000000000..2cb4ba63b0 --- /dev/null +++ b/files/pt-br/web/api/htmlelement/dataset/index.html @@ -0,0 +1,97 @@ +--- +title: HTMLElement.dataset +slug: Web/API/HTMLElement/dataset +translation_of: Web/API/HTMLOrForeignElement/dataset +--- +

{{ APIRef }}

+ +

A propriedade HTMLElement.dataset permite o acesso, em modo de leitura e escrita, a todos os atributos de dados personalizado (data-*) no elemento. Ele é um mapa de DOMString, com uma entrada para cada atributo de dados personalizado.

+ +

O nome de um atributo de dados customizado inicia com data-. Ele deve conter somente letras, números e os seguintes caracteres: dash (-), dot (.), collon(:), underscore (_). Além disso, ele não deve conter letras ASCII captalizadas (A à Z).

+ +

Um atributo de dados personalizado é transformado em uma chave para uma entrada no {{ domxref("DOMStringMap") }} de acordo com as seguintes regras

+ + + +

A transformação oposta, que mapeia uma chave para um nome de atributo, usa as seguintes regras:

+ + + +

A restrição nas regras acima garantem que as duas trasnformações são inversa uma da outra.

+ +

Por exemplo, o atributo data-abc-def corresponde a chave abcDef.

+ +

Sintaxe

+ +
string = element.dataset.camelCasedName;
+element.dataset.camelCasedName = string;
+ +

Exemplos

+ +
<div id="user" data-id="1234567890" data-user="johndoe" data-date-of-birth>John Doe
+</div>
+
+var el = document.querySelector('#user');
+
+// el.id == 'user'
+// el.dataset.id === '1234567890'
+// el.dataset.user === 'johndoe'
+// el.dataset.dateOfBirth === ''
+
+el.dataset.dateOfBirth = '1960-10-03'; // set the DOB.
+
+// 'someDataAttr' in el.dataset === false
+
+el.dataset.someDataAttr = 'mydata';
+// 'someDataAttr' in el.dataset === true
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + +
EspeficicaçãoStatusComentário
{{SpecName('HTML WHATWG', "dom.html#dom-dataset", "HTMLElement.dataset")}}{{Spec2('HTML WHATWG')}}Sem mudanças desde o último  snapshot, {{SpecName('HTML5.1')}}
{{SpecName('HTML5.1', "dom.html#dom-dataset", "HTMLElement.dataset")}}{{Spec2('HTML5.1')}}Snapshot de {{SpecName('HTML WHATWG')}}, sem mudanças desde {{SpecName('HTML5 W3C')}}
{{SpecName('HTML5 W3C', "dom.html#dom-dataset", "HTMLElement.dataset")}}{{Spec2('HTML5 W3C')}}Snapshot de {{SpecName('HTML WHATWG')}}, definição inicial.
+ +

Compatibilidade com Browsers

+ + + +

{{Compat("api.HTMLElement.dataset")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/htmlelement/focus/index.html b/files/pt-br/web/api/htmlelement/focus/index.html new file mode 100644 index 0000000000..8f798b3d86 --- /dev/null +++ b/files/pt-br/web/api/htmlelement/focus/index.html @@ -0,0 +1,62 @@ +--- +title: HTMLElement.focus() +slug: Web/API/HTMLElement/focus +translation_of: Web/API/HTMLOrForeignElement/focus +--- +
{{ APIRef("HTML DOM") }}
+ +

O método HTMLElement.focus()  seta o foco em um determinado elemento em especifico, caso esse elemento permita ter o foco neste elemento.

+ +

Síntaxe

+ +
element.focus()
+ +

Especificação

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG', 'editing.html#dom-focus', 'focus')}}{{Spec2('HTML WHATWG')}} 
{{SpecName('HTML5.1', 'editing.html#focus()-0', 'focus')}}{{Spec2('HTML5.1')}} 
{{SpecName('HTML5 W3C', 'editing.html#dom-focus', 'focus')}}{{Spec2('HTML5 W3C')}} 
{{SpecName('DOM2 HTML', 'html.html#ID-32130014', 'focus')}}{{Spec2('DOM2 HTML')}} 
{{SpecName('DOM1', 'level-one-html.html#method-focus', 'focus')}}{{Spec2('DOM1')}} 
+ +

Notas

+ +

Caso você utilize o HTMLElement.focus() por meio da manipulação de um evento mousedown , você deve utilizar o evento event.preventDefault() a fim de o foco não sair do arquivo HTMLElement.

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/htmlelement/index.html b/files/pt-br/web/api/htmlelement/index.html new file mode 100644 index 0000000000..f264d6158b --- /dev/null +++ b/files/pt-br/web/api/htmlelement/index.html @@ -0,0 +1,410 @@ +--- +title: HTMLElement +slug: Web/API/HTMLElement +tags: + - API + - HTML DOM + - Interface + - NeedsMobileBrowserCompatibility + - NeedsNewLayout + - NeedsTranslation + - Reference + - Référence(2) + - TopicStub +translation_of: Web/API/HTMLElement +--- +
+
{{ APIRef("HTML DOM") }}
+
+ +
 
+ +

A interface HTMLElement representa qualquer elemento HTML. Alguns elementos implementam diretamente essa interface, outros a implementam por meio de uma interface que a herda.

+ +

Propriedades

+ +

Propriedades herdadas do elemento pai, {{domxref("Element")}}, e aquelas implementadas de {{domxref("GlobalEventHandlers")}} e de {{domxref("TouchEventHandlers")}}.

+ +
+
{{domxref("HTMLElement.accessKey")}}
+
Is a {{domxref("DOMString")}} representing the access key assigned to the element.
+
{{domxref("HTMLElement.accessKeyLabel")}} {{readonlyInline}}
+
Returns a {{domxref("DOMString")}} containing the element's assigned access key.
+
{{domxref("HTMLElement.contentEditable")}}
+
Is a {{domxref("DOMString")}}, where a value of "true" means the element is editable and a value of "false" means it isn't.
+
{{domxref("HTMLElement.isContentEditable")}} {{readonlyInline}}
+
Returns a {{domxref("Boolean")}} that indicates whether or not the content of the element can be edited.
+
{{domxref("HTMLElement.contextMenu")}}
+
Is an {{domxref("HTMLMenuElement")}} representing the contextual menu associated with the element. It may be null
+
{{domxref("HTMLElement.dataset")}} {{readonlyInline}}
+
Returns a {{domxref("DOMStringMap")}} that allows access to read and write the element custom data attributes (data-*) .
+
{{domxref("HTMLElement.dir")}}
+
Is a {{domxref("DOMString")}}, reflecting the dir global attribute, representing the directionality of the element. Possible values are "ltr", "rtl", and "auto".
+
{{domxref("HTMLElement.draggable")}}
+
Is a {{jsxref("Boolean")}} indicating if the element can be dragged.
+
{{domxref("HTMLElement.dropzone")}} {{readonlyInline}}
+
Returns a {{domxref("DOMSettableTokenList")}} reflecting the dropzone global attribute and describing the behavior of the element regarding a drop operation.
+
{{domxref("HTMLElement.hidden")}}
+
Is a {{jsxref("Boolean")}} indicating if the element is hidden or not.
+
{{domxref("HTMLElement.itemScope")}} {{experimental_inline}}
+
Is a {{jsxref("Boolean")}}…
+
{{domxref("HTMLElement.itemType")}} {{readonlyInline}}{{experimental_inline}}
+
Returns a {{domxref("DOMSettableTokenList")}}…
+
{{domxref("HTMLElement.itemId")}} {{experimental_inline}}
+
Is a {{domxref("DOMString")}}…
+
{{domxref("HTMLElement.itemRef")}} {{readonlyInline}}{{experimental_inline}}
+
Returns a {{domxref("DOMSettableTokenList")}}…
+
{{domxref("HTMLElement.itemProp")}} {{readonlyInline}}{{experimental_inline}}
+
Returns a {{domxref("DOMSettableTokenList")}}…
+
{{domxref("HTMLElement.itemValue")}} {{experimental_inline}}
+
Returns an {{jsxref("Object")}}…
+
{{domxref("HTMLElement.lang")}}
+
Is a {{domxref("DOMString")}} representing the language of an element's attributes, text, and element contents.
+
{{domxref("HTMLElement.offsetHeight")}} {{readonlyInline}}{{experimental_inline}}
+
Returns a double containing the height of an element, relative to the layout.
+
{{domxref("HTMLElement.offsetLeft")}}{{readonlyInline}}{{experimental_inline}}
+
Returns a double, the distance from this element's left border to its offsetParent's left border.
+
{{domxref("HTMLElement.offsetParent")}}{{readonlyInline}}{{experimental_inline}}
+
Returns an {{domxref("Element")}} that is the element from which all offset calculations are currently computed.
+
{{domxref("HTMLElement.offsetTop")}}{{readonlyInline}}{{experimental_inline}}
+
Returns a double, the distance from this element's top border to its offsetParent's top border.
+
{{domxref("HTMLElement.offsetWidth")}}{{readonlyInline}}{{experimental_inline}}
+
Returns a double containing the width of an element, relative to the layout.
+
{{domxref("HTMLElement.properties")}} {{readonlyInline}}{{experimental_inline}}
+
Returns an {{domxref("HTMLPropertiesCollection")}}…
+
{{domxref("HTMLElement.spellcheck")}}{{ gecko_minversion_inline("1.9")}}
+
Is a {{jsxref("Boolean")}} that controls spell-checking. It is present on all HTML elements, though it hasn't an effect on all of them.
+
{{domxref("HTMLElement.style")}}
+
Is {{domxref("CSSStyleDeclaration")}}, an object representing the declarations of an element's style attributes.
+
{{domxref("HTMLElement.tabIndex")}}
+
Is a long representing the position of the element in the tabbing order.
+
{{domxref("HTMLElement.title")}}
+
Is a {{domxref("DOMString")}} containing the text that appears in a popup box when mouse is over the element.
+
{{domxref("HTMLElement.translate")}} {{experimental_inline}}
+
Is a {{jsxref("Boolean")}}
+
+ +

Event handlers

+ +

Most events properties, of the form onXYZ, are defined on the {{domxref("GlobalEventHandlers")}} or {{domxref("TouchEventHandlers")}}, implemented by HTMLElement. A few more are specific to HTMLElement.

+ +
+
{{ domxref("HTMLElement.oncopy") }}  {{ non-standard_inline() }}
+
Returns the event handling code for the copy event ({{bug("280959")}}).
+
{{ domxref("HTMLElement.oncut") }}  {{ non-standard_inline() }}
+
Returns the event handling code for the cut event ({{bug("280959")}}).
+
{{ domxref("HTMLElement.onpaste") }} {{ non-standard_inline() }}
+
Returns the event handling code for the paste event ({{bug("280959")}}).
+
{{domxref("TouchEventHandlers.ontouchstart")}} {{non-standard_inline}}
+
Returns the event handling code for the {{event("touchstart")}} event.
+
{{domxref("TouchEventHandlers.ontouchend")}} {{non-standard_inline}}
+
Returns the event handling code for the {{event("touchend")}} event.
+
{{domxref("TouchEventHandlers.ontouchmove")}} {{non-standard_inline}}
+
Returns the event handling code for the {{event("touchmove")}} event.
+
{{domxref("TouchEventHandlers.ontouchenter")}} {{non-standard_inline}}
+
Returns the event handling code for the {{event("touchenter")}} event.
+
{{domxref("TouchEventHandlers.ontouchleave")}} {{non-standard_inline}}
+
Returns the event handling code for the {{event("touchleave")}} event.
+
{{domxref("TouchEventHandlers.ontouchcancel")}} {{non-standard_inline}}
+
Returns the event handling code for the {{event("touchcancel")}} event.
+
+ +

Methods

+ +

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

+ +
+
{{domxref("HTMLElement.blur()")}}
+
Removes keyboard focus from the currently focused element.
+
{{domxref("HTMLElement.click()")}}
+
Sends a mouse click event to the element.
+
{{domxref("HTMLElement.focus()")}}
+
Makes the element the current keyboard focus.
+
{{domxref("HTMLElement.forceSpellCheck()")}} {{experimental_inline}}
+
Makes the spell checker runs on the element.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSSOM View', '#extensions-to-the-htmlelement-interface', 'HTMLElement')}}{{Spec2('CSSOM View')}}Added the following properties: offsetParent, offsetTop, offsetLeft, offsetWidth, and offsetHeight.
{{SpecName('HTML WHATWG', 'elements.html#htmlelement', 'HTMLElement')}}{{Spec2('HTML WHATWG')}}Added the following properties: translate, itemScope, itemType, itemId, itemRef, itemProp, properties, and itemValue.
+ Added the following method: forceSpellcheck().
+ Moved the onXYZ attributes to the {{domxref("GlobalEventHandlers")}} interface and added an inheritance from it.
{{SpecName('HTML5 W3C', 'dom.html#htmlelement', 'HTMLElement')}}{{Spec2('HTML5 W3C')}}Added the following properties: dataset, hidden, tabindex, accessKey, accessKeyLabel, draggable, dropzone, contentEditable, isContentEditable, contextMenu, spellcheck, commandType, commandLabel, commandIcon, commandHidden, commandDisabled, commandChecked, style, and all the onXYZ properties.
+ Moved the id and className properties to the {{domxref("Element")}} interface.
{{SpecName('DOM2 HTML', 'html.html#ID-011100101', 'HTMLElement')}}{{Spec2('DOM2 HTML')}}No change from {{SpecName('DOM2 HTML')}}
{{SpecName('DOM1', 'level-one-html.html#ID-011100101', 'HTMLElement')}}{{Spec2('DOM1')}}Initial definition.
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Basic support{{CompatGeckoDesktop("1.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
{{domxref("HTMLElement.accessKey", "accessKey")}}{{CompatGeckoDesktop("5.0")}}17.0{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}(535.10)
{{domxref("HTMLElement.accessKeyLabel", "accessKeyLabel")}}{{CompatGeckoDesktop("8.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatNo}}{{WebkitBug(72715)}}
{{domxref("HTMLElement.blur()", "blur()")}}{{CompatGeckoDesktop("5.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
{{domxref("HTMLElement.click()", "click()")}}{{CompatGeckoDesktop("5.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}(535.24)
{{domxref("HTMLElement.dataset", "dataset")}}{{CompatGeckoDesktop("6.0")}}9.0{{CompatUnknown}}11.105.1
{{domxref("HTMLElement.focus()", "focus()")}}{{CompatGeckoDesktop("5.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
{{domxref("HTMLElement.contentEditable", "contentEditable")}}{{CompatGeckoDesktop("1.9")}}{{CompatVersionUnknown}}5.59{{CompatVersionUnknown}}
{{domxref("HTMLElement.spellcheck", "spellcheck")}}{{CompatGeckoDesktop("1.8.1")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
{{domxref("HTMLElement.style", "style")}}{{CompatVersionUnknown}} (returns a {{domxref("CSS2Properties")}}, rather than a {{domxref("CSSStyleDeclaration")}}){{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
{{domxref("HTMLElement.forceSpellCheck", "forceSpellCheck()")}} {{experimental_inline}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
{{domxref("HTMLElement.dataset", "dataset")}}{{CompatGeckoDesktop("6.0")}}8.01111.106
{{domxref("HTMLElement.draggable", "draggable")}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}12.0{{CompatUnknown}}
{{domxref("HTMLElement.dropzone", "dropzone")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}12.0{{CompatNo}}
{{domxref("HTMLElement.offsetLeft", "offsetLeft")}}, {{domxref("HTMLElement.offsetTop", "offsetTop")}}, {{domxref("HTMLElement.offsetParent", "offsetParent")}}, {{domxref("HTMLElement.offsetHeight", "offsetHeight")}} and {{domxref("HTMLElement.offsetWidth", "offsetWidth")}} {{experimental_inline}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}
{{domxref("HTMLElement.translate", "translate")}} {{experimental_inline}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
{{domxref("HTMLElement.itemScope", "itemScope")}}, {{domxref("HTMLElement.itemType", "itemType")}}, {{domxref("HTMLElement.itemRef", "itemRef")}}, {{domxref("HTMLElement.itemId", "itemId")}}, {{domxref("HTMLElement.itemProp", "itemProp")}}, and {{domxref("HTMLElement.itemValue", "itemValue")}} {{experimental_inline}}{{CompatGeckoDesktop("6.0")}}{{CompatNo}}{{CompatNo}}11.60
+ (Removed in Opera 15)
{{CompatNo}}
{{domxref("HTMLElement.properties", "properties")}} {{experimental_inline}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
{{domxref("HTMLElement.ontouchstart")}}, {{domxref("HTMLElement.ontouchend")}}, {{domxref("HTMLElement.ontouchmove")}}, {{domxref("HTMLElement.ontouchenter")}}, {{domxref("HTMLElement.ontouchleave")}}, and {{domxref("HTMLElement.ontouchcancel")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatVersionUnknown}}
{{domxref("HTMLElement.oncopy")}}, {{domxref("HTMLElement.oncut")}}, and {{domxref("HTMLElement.onpaste")}} {{Non-standard_inline}}{{CompatGeckoDesktop("1.9")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari Mobile
Basic support +

{{CompatGeckoMobile("1.0")}}

+
{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
{{domxref("HTMLElement.accessKey", "accessKey")}}{{CompatGeckoMobile("5.0")}}
{{domxref("HTMLElement.accessKeyLabel", "accessKeyLabel")}}{{CompatGeckoMobile("8.0")}}
{{domxref("HTMLElement.blur()", "blur()")}}{{CompatGeckoMobile("5.0")}}
{{domxref("HTMLElement.click()", "click()")}}{{CompatGeckoMobile("5.0")}}
{{domxref("HTMLElement.dataset", "dataset")}}{{CompatGeckoMobile("6.0")}}
{{domxref("HTMLElement.focus()", "focus()")}}{{CompatGeckoMobile("5.0")}}
{{domxref("HTMLElement.oncopy")}}, {{domxref("HTMLElement.oncut")}}, and {{domxref("HTMLElement.onpaste")}} {{Non-standard_inline}}{{CompatGeckoMobile("1.9")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

See also

+ + diff --git a/files/pt-br/web/api/htmlelement/lang/index.html b/files/pt-br/web/api/htmlelement/lang/index.html new file mode 100644 index 0000000000..6f877f1e33 --- /dev/null +++ b/files/pt-br/web/api/htmlelement/lang/index.html @@ -0,0 +1,51 @@ +--- +title: HTMLElement.lang +slug: Web/API/HTMLElement/lang +translation_of: Web/API/HTMLElement/lang +--- +
{{ APIRef("HTML DOM") }}
+ +

The HTMLElement.lang property gets or sets the base language of an element's attribute values and text content.

+ +

The language code returned by this property is defined in RFC 1766. Common examples include "en" for English, "ja" for Japanese, "es" for Spanish and so on. The default value of this attribute is unknown. Note that this attribute, though valid at the individual element level described here, is most often specified for the root element of the document.

+ +

This also only works with the lang attribute and not with xml:lang.

+ +

Sintaxe

+ +
var languageUsed = elementNodeReference.lang; // Get the value of lang
+elementNodeReference.lang = NewLanguage; // Set new value for lang
+
+ +

languageUsed é uma variável string que obtém o idioma no qual o texto do elemento atual é gravado. NewLanguage é uma variável  string cujo valor define o idioma no qual o texto do elemento atual é gravado.

+ +

Exemplo

+ +
// this snippet compares the base language and
+// redirects to another url based on language
+if (document.documentElement.lang === "en") {
+  window.location.href = "Some_document.html.en";
+} else if (document.documentElement.lang === "ru") {
+  window.location.href = "Some_document.html.ru";
+}
+ +

Especificação

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('DOM2 HTML', 'html.html#ID-59132807', 'lang')}}{{Spec2('DOM2 HTML')}} 
+ +

 

diff --git a/files/pt-br/web/api/htmlelement/offsetheight/index.html b/files/pt-br/web/api/htmlelement/offsetheight/index.html new file mode 100644 index 0000000000..fdf05ca699 --- /dev/null +++ b/files/pt-br/web/api/htmlelement/offsetheight/index.html @@ -0,0 +1,126 @@ +--- +title: HTMLElement.offsetHeight +slug: Web/API/HTMLElement/offsetHeight +translation_of: Web/API/HTMLElement/offsetHeight +--- +

{{ APIRef("HTML DOM") }}

+ +

A propriedade HTMLElement.offsetHeight é somente leitura e retorna um valor do tipo inteiro a altura de um elemento incluindo  padding-top+padding-bottom+border-top+border-bottom.

+ +

Typically, an element's offsetHeight is a measurement in pixels of the element's CSS height, including border, padding and the element's horizontal scrollbar (if present, if rendered).

+ +

For the document body object, the measurement includes total linear content height instead of the element's CSS height. Floated elements extending below other linear content are ignored.

+ +
+

This property will round the value to an integer. If you need a fractional value, use {{ domxref("element.getBoundingClientRect()") }}.

+
+ +

Syntax

+ +
var intElemOffsetHeight = element.offsetHeight;
+ +

intElemOffsetHeight is a variable storing an integer corresponding to the offsetHeight pixel value of the element. The offsetHeight property is read-only.

+ +

Example

+ +

 

+ +

             Image:Dimensions-offset.png

+ + +

The example image above shows a scrollbar and an offsetHeight which fits on the window. However, non-scrollable elements may have large offsetHeight values, much larger than the visible content. These elements are typically contained within scrollable elements; consequently these non-scrollable elements may be completely or partly invisible, depending on the scrollTop setting of the scrollable container.

+ +

 

+ +

Specification

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSSOM View', '#dom-htmlelement-offsetHeight', 'offsetLeft')}}{{Spec2('CSSOM View')}} 
+ +

Notes

+ +

offsetHeight is a property of the DHTML object model which was first introduced by MSIE. It is sometimes referred to as an element's physical/graphical dimensions, or an element's border-box height.

+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}31{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
+
+ +

In compliance with the specification, this property will return null on Webkit if the element is hidden (the style.display of this element or any ancestor is "none") or if the style.position of the element itself is set to "fixed".

+ +

This property will return null on Internet Explorer (9) if the style.position of the element itself is set to "fixed". (Having display:none does not affect this browser.)

+ +

See Also

+ + diff --git a/files/pt-br/web/api/htmlelement/offsetleft/index.html b/files/pt-br/web/api/htmlelement/offsetleft/index.html new file mode 100644 index 0000000000..68f5f0b986 --- /dev/null +++ b/files/pt-br/web/api/htmlelement/offsetleft/index.html @@ -0,0 +1,142 @@ +--- +title: HTMLElement.offsetLeft +slug: Web/API/HTMLElement/offsetLeft +tags: + - API + - ApenasLeitura + - Propriedade + - Referência(2) +translation_of: Web/API/HTMLElement/offsetLeft +--- +
{{ APIRef("HTML DOM") }}
+ +

HTMLElement.offsetLeft é um método apenas de leitura que retorna a medida, em pixels, da distância do canto superior esquerdo do elemento atual para o nó {{domxref("HTMLElement.offsetParent")}}.

+ +

Para elementos "block-level", que ocupam todo o espaço do elemento pai, o offsetTop, offsetLeft, offsetWidth, e offsetHeight representam a borda de um elemento relativo ao offsetParent.

+ +

Entretando, para elementos "inline-level"  (como o span) que podem envolver de uma linha para outra, o offsetTop e offsetLeft representam a posição da primeira borda (use {{domxref("Element.getClientRects()")}} para retornar a largura e altura), enquanto offsetWidth e offsetHeight representam as dimensões do bloco delimitador (use {{domxref("Element.getBoundingClientRect()")}} pra retornar sua posição). Portanto, um bloco que possua um left, top, widht ou height do offsetLeft, offsetTop, offsetWidth e offsetHeight não será um delimitador para um span com texto envolvido.

+ +

Sintaxe

+ +
left = element.offsetLeft;
+
+ +

left é um número inteiro representando o deslocamento para esquerda, em pixels,  do elemento pai mais próximo posicionado com relative.

+ +

Exemplo

+ +
var colorTable = document.getElementById("t1");
+var tOLeft = colorTable.offsetLeft;
+
+if (tOLeft > 5) {
+  // deslocamento à esquerda maior que 5: faça alguma coisa
+}
+
+ +

Esse exemplo mostra uma frase 'longa' envolvida por uma div com uma borda azul, e uma caixa vermelha que deveria delimitar o span.

+ +

Image:offsetLeft.jpg

+ +
<div style="width: 300px; border-color:blue;
+  border-style:solid; border-width:1;">
+  <span>Short span. </span>
+  <span id="long">Long span that wraps within this div.</span>
+</div>
+
+<div id="box" style="position: absolute; border-color: red;
+  border-width: 1; border-style: solid; z-index: 10">
+</div>
+
+<script>
+  var box = document.getElementById("box");
+  var long = document.getElementById("long");
+  box.style.left = long.offsetLeft + document.body.scrollLeft + "px";
+  box.style.top = long.offsetTop + document.body.scrollTop + "px";
+  box.style.width = long.offsetWidth + "px";
+  box.style.height = long.offsetHeight + "px";
+</script> 
+ +

Especificação

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('CSSOM View', '#dom-htmlelement-offsetleft', 'offsetLeft')}}{{Spec2('CSSOM View')}} 
+ +

Compatibilidade do navegador

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte Básico{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome para Android
Suporte Básico{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
+
+ +

Em conformidade com a especificação, essa propriedade  retornará null no Webkit se o elemento não estiver sendo exibido (o style.display desse elemento ou ancestral estiver como "none") ou se o style.position do elemento estiver setado como "fixed".

+ +

Essa propriedade retornará null no Internet Explorer (9) se o style.position do elemento estiver setado como "fixed". (Ter display:none não afeta esse browser.)

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/htmlelement/offsetparent/index.html b/files/pt-br/web/api/htmlelement/offsetparent/index.html new file mode 100644 index 0000000000..d08c3d3e09 --- /dev/null +++ b/files/pt-br/web/api/htmlelement/offsetparent/index.html @@ -0,0 +1,40 @@ +--- +title: HTMLElement.offsetParent +slug: Web/API/HTMLElement/offsetParent +translation_of: Web/API/HTMLElement/offsetParent +--- +
+
{{ APIRef("HTML DOM") }}
+
+ +

A propriedade somente de leitura HTMLElement.offsetParent retorna uma referência ao objeto ao qual está contido(mais próximo na hierarquia do conteúdo) posicionado contendo o elemento. Caso o elemento não esteja posicionado, mais próximo a célula da tabela ou do elemento raiz (nos padrões do modo de conformidade do html; no modo quirks de redenrização) é o offsetParent. quando o elemento está definido style.display para "none", offsetParent retorna null. A propriedade offsetParent é útil devido a {{domxref("HTMLElement.offsetTop","offsetTop")}} e {{domxref("HTMLElement.offsetLeft","offsetLeft")}} serem relativos ao seu preenchimento da borda.

+ +
parentObj = element.offsetParent;
+
+ + + +

Especificação

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSSOM View', '#dom-htmlelement-offsetparent', 'offsetParent')}}{{Spec2('CSSOM View')}} 
+ +

Compatibilidade do Navegador

+ +

{{Compat("api.HTMLElement.offsetParent")}}

diff --git a/files/pt-br/web/api/htmlelement/offsettop/index.html b/files/pt-br/web/api/htmlelement/offsettop/index.html new file mode 100644 index 0000000000..f0a19ee86d --- /dev/null +++ b/files/pt-br/web/api/htmlelement/offsettop/index.html @@ -0,0 +1,62 @@ +--- +title: HTMLElement.offsetTop +slug: Web/API/HTMLElement/offsetTop +tags: + - API + - ApenasLeitura + - Propriedade +translation_of: Web/API/HTMLElement/offsetTop +--- +
+
{{ APIRef("HTML DOM") }}
+
+ +

O HTMLElement.offsetTop é um método apenas de leitura que retorna a medida, em pixels, da distância do elemento atual em relação ao topo do {{domxref("HTMLelement.offsetParent","offsetParent")}}.

+ +

Sintaxe

+ +
topPos = element.offsetTop;
+
+ +

Parâmetros

+ + + +

Exemplo

+ +
var d = document.getElementById("div1");
+var topPos = d.offsetTop;
+
+if (topPos > 10) {
+  // deslocamento em relação ao topo maior
+  // que 10pixels do topo
+}
+ +

Especificação

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('CSSOM View', '#dom-htmlelement-offsettop', 'offsetTop')}}{{Spec2('CSSOM View')}} 
+ +

Compatibilidade do navegador

+ +

{{Compat("api.HTMLElement.offsetTop")}}

+ +

Em conformidade com a especificação, essa propriedade retornará null no Webkit se o elemento não estiver sendo exibido (o style.display desse elemento ou ancestral estiver como "none") ou se o style.position do elemento estiver setado como "fixed".

+ +

Essa propriedade retornará null no Internet Explorer (9) se o style.position do elemento estiver setado como "fixed". (Ter display:none não afeta esse browser.)

diff --git a/files/pt-br/web/api/htmlelement/offsetwidth/index.html b/files/pt-br/web/api/htmlelement/offsetwidth/index.html new file mode 100644 index 0000000000..63d60ee4c1 --- /dev/null +++ b/files/pt-br/web/api/htmlelement/offsetwidth/index.html @@ -0,0 +1,65 @@ +--- +title: HTMLElement.offsetWidth +slug: Web/API/HTMLElement/offsetWidth +translation_of: Web/API/HTMLElement/offsetWidth +--- +
{{ APIRef("HTML DOM") }}
+ +

A propriedade HTMLElement.offsetWidth é de somente leitura e retorna a largura de um elemento no layout.  Normalmente, o offsetWidth é uma medida que inclui as bordas do elemento, seu padding horizontal e o vertical scrollbar (se presente e renderizado) e também a largura CSS do elemento.

+ +

Sintaxe 

+ +
var offsetWidth =element.offsetWidth;
+
+ +

offsetWidth é uma propriedade somente leitura.

+ +
+

Esta propriedade irá arredondar o valor para um inteiro. se você precisa um valor fracionado, use {{ domxref("element.getBoundingClientRect()") }}.

+
+ +

 

+ +

Exemplo

+ +

 

+ +

             Image:Dimensions-offset.png

+ + +

Especificação

+ + + + + + + + + + + + + + + + +
EspecificaçãoSituaçãoComentário
{{SpecName('CSSOM View', '#dom-htmlelement-offsetwidth', 'offsetWidth')}}{{Spec2('CSSOM View')}} 
+ +

Notas

+ +

offsetWidth é uma propriedade do modelo de objeto DHTML que foi primeiro apresentado pelo MSIE. Algumas vezes referenciado como as dimensões físicas/gráficas do elemento, ou a largura do border-box.

+ +

Compatibilidade de Browsers

+ +

{{Compat("api.HTMLElement.offsetWidth")}}

+ +

Veja também

+ + + +
 
diff --git a/files/pt-br/web/api/htmlinputelement/index.html b/files/pt-br/web/api/htmlinputelement/index.html new file mode 100644 index 0000000000..2537ee7395 --- /dev/null +++ b/files/pt-br/web/api/htmlinputelement/index.html @@ -0,0 +1,643 @@ +--- +title: HTMLInputElement +slug: Web/API/HTMLInputElement +tags: + - API + - HTML DOM + - Interface + - NeedsNewLayout + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/API/HTMLInputElement +--- +
{{ APIRef("HTML DOM") }}
+ +
+ +

A interface HTMLInputElement fornece propriedades e métodos especiais (além da interface regular {{domxref ("HTMLElement")}}) que também tem disponível por herança) para manipular o layout e a apresentação dos elementos de entrada.

+ +

Propriedades

+ +

Inherits propriedades dos parentes, {{domxref("HTMLElement")}}.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
accept{{domxref("DOMString")}}Reflete o {{ htmlattrxref("accept", "input") }} atributo HTML, contendo uma lista separada por vírgula de tipos de arquivos aceitos pelo servidor quando {{htmlattrxref("type","input")}} é file.
accessKey{{domxref("DOMString")}}Um único caractere que alterna o foco de entrada para o controle.
align {{obsolete_inline}}{{domxref("DOMString")}}Alinhamento do elemento.
alt{{domxref("DOMString")}}Reflete o {{ htmlattrxref("alt", "input") }} atributo HTML, contendo texto alternativo para usar quando {{htmlattrxref("type","input")}} é image.
autocapitalize {{experimental_inline}}{{domxref("DOMString")}}Define o comportamento de capitalização para entrada do usuário. Valores válidos são none, off, characters, words, ou sentences.
autocomplete{{domxref("DOMString")}}Reflects the {{htmlattrxref("autocomplete", "input")}} HTML attribute, indicating whether the value of the control can be automatically completed by the browser. Ignored if the value of the {{htmlattrxref("type","input")}} attribute is hidden, checkbox, radio, file, or a button type (button, submit, reset, image). Possible values are: +
    +
  • off: The user must explicitly enter a value into this field for every use, or the document provides its own auto-completion method; the browser does not automatically complete the entry.
  • +
  • on: The browser can automatically complete the value based on values that the user has entered during previous uses.
  • +
+
autofocus{{jsxref("Boolean")}}Reflects the {{ htmlattrxref("autofocus", "input") }} HTML attribute, which specifies that a form control should have input focus when the page loads, unless the user overrides it, for example by typing in a different control. Only one form element in a document can have the {{htmlattrxref("autofocus","input")}} attribute. It cannot be applied if the {{htmlattrxref("type","input")}} attribute is set to hidden (that is, you cannot automatically set focus to a hidden control).
checked{{jsxref("Boolean")}}The current state of the element when {{htmlattrxref("type","input")}} is checkbox or radio.
defaultChecked{{jsxref("Boolean")}}The default state of a radio button or checkbox as originally specified in HTML that created this object.
defaultValue{{domxref("DOMString")}}The default value as originally specified in HTML that created this object.
dirName
disabled{{jsxref("Boolean")}}Reflects the {{ htmlattrxref("disabled", "input") }} HTML attribute, indicating that the control is not available for interaction. The input values will not be submitted with the form. See also {{ htmlattrxref("readOnly", "input") }} 
files {{readonlyInline}}{{domxref("FileList")}}A list of selected files.
form {{readonlyInline}}{{domxref("HTMLFormElement")}}The containing form element, if this element is in a form. If this element is not contained in a form element: +
    +
  • {{ HTMLVersionInline(5) }} this can be the {{ htmlattrxref("id", "form") }} attribute of any {{ HTMLElement("form") }} element in the same document. Even if the attribute is set on {{ HTMLElement("input") }}, this property will be null, if it isn't the id of a {{ HTMLElement("form") }} element.
  • +
  • {{ HTMLVersionInline(4) }} this must be null.
  • +
+
formAction{{domxref("DOMString")}}Reflects the {{ htmlattrxref("formaction", "input") }} HTML attribute, containing the URI of a program that processes information submitted by the element. If specified, this attribute overrides the {{ htmlattrxref("action", "form") }} attribute of the {{ HTMLElement("form") }} element that owns this element.
formEncType{{domxref("DOMString")}}Reflects the {{ htmlattrxref("formenctype", "input") }} HTML attribute, containing the type of content that is used to submit the form to the server. If specified, this attribute overrides the {{ htmlattrxref("enctype", "form") }} attribute of the {{ HTMLElement("form") }} element that owns this element.
formMethod{{domxref("DOMString")}}Reflects the {{ htmlattrxref("formmethod", "input") }} HTML attribute, containing the HTTP method that the browser uses to submit the form. If specified, this attribute overrides the {{ htmlattrxref("method", "form") }} attribute of the {{ HTMLElement("form") }} element that owns this element.
formNoValidate{{jsxref("Boolean")}}Reflects the {{ htmlattrxref("formnovalidate", "input") }} HTML attribute, indicating that the form is not to be validated when it is submitted. If specified, this attribute overrides the {{ htmlattrxref("novalidate", "form") }} attribute of the {{ HTMLElement("form") }} element that owns this element.
formTarget{{domxref("DOMString")}}Reflects the {{ htmlattrxref("formtarget", "input") }} HTML attribute, containing a name or keyword indicating where to display the response that is received after submitting the form. If specified, this attribute overrides the {{ htmlattrxref("target", "form") }} attribute of the {{ HTMLElement("form") }} element that owns this element.
height{{domxref("DOMString")}}Reflects the {{ htmlattrxref("height", "input") }} HTML attribute, which defines the height of the image displayed for the button, if the value of {{htmlattrxref("type","input")}} is image.
indeterminate{{jsxref("Boolean")}}Indicates that a checkbox is neither on nor off.
labels {{readonlyInline}}{{domxref("NodeList")}}A list of {{ HTMLElement("label") }} elements that are labels for this element.
list{{domxref("HTMLElement")}}Identifies a list of pre-defined options to suggest to the user. The value must be the id of a {{HTMLElement("datalist")}} element in the same document. The browser displays only options that are valid values for this input element. This attribute is ignored when the {{htmlattrxref("type","input")}} attribute's value is hidden, checkbox, radio, file, or a button type.
max{{domxref("DOMString")}}Reflects the {{ htmlattrxref("max", "input") }} HTML attribute, containing the maximum (numeric or date-time) value for this item, which must not be less than its minimum (min attribute) value.
maxLength longReflects the {{ htmlattrxref("maxlength", "input") }} HTML attribute, containing the maximum length of text (in Unicode code points) that the value can be changed to. The constraint is evaluated only when the value is changed +
Note: If you set maxLength to a negative value programmatically, an exception will be thrown.
+
min{{domxref("DOMString")}}Reflects the {{ htmlattrxref("min", "input") }} HTML attribute, containing the minimum (numeric or date-time) value for this item, which must not be greater than its maximum ({{htmlattrxref("max","input")}} attribute) value.
multipleReflects the {{ htmlattrxref("multiple", "input") }} HTML attribute, indicating whether more than one value is possible (e.g., multiple files).
name{{domxref("DOMString")}}Reflects the {{ htmlattrxref("name", "input") }} HTML attribute, containing a name that identifies the element when submitting the form.
pattern{{domxref("DOMString")}}Reflects the {{ htmlattrxref("pattern", "input") }} HTML attribute, containing a regular expression that the control's value is checked against. The pattern must match the entire value, not just some subset. Use the {{htmlattrxref("title","input")}} attribute to describe the pattern to help the user. This attribute applies when the value of the {{htmlattrxref("type","input")}} attribute is text, search, tel, url or email; otherwise it is ignored.
placeholder{{domxref("DOMString")}}Reflects the {{ htmlattrxref("placeholder", "input") }} HTML attribute, containing a hint to the user of what can be entered in the control. The placeholder text must not contain carriage returns or line-feeds. This attribute applies when the value of the {{htmlattrxref("type","input")}} attribute is text, search, tel, url or email; otherwise it is ignored.
readOnly{{jsxref("Boolean")}} +

Reflects the {{ htmlattrxref("readonly", "input") }} HTML attribute, indicating that the user cannot modify the value of the control.
+ {{HTMLVersionInline(5)}}This is ignored if the value of the {{htmlattrxref("type","input")}} attribute is hidden, range, color, checkbox, radio, file, or a button type.

+
required{{jsxref("Boolean")}}Reflects the {{ htmlattrxref("required", "input") }} HTML attribute, indicating that the user must fill in a value before submitting a form.
selectionDirection{{domxref("DOMString")}}The direction in which selection occurred. This is "forward" if selection was performed in the start-to-end direction of the current locale, or "backward" for the opposite direction. This can also be "none" if the direction is unknown."
selectionEndunsigned longThe index of the end of selected text.
selectionStartunsigned longThe index of the beginning of selected text. When nothing is selected, this is also the caret position inside of the <input> element.
sizeunsigned longReflects the {{ htmlattrxref("size", "input") }} HTML attribute, containing size of the control. This value is in pixels unless the value of {{htmlattrxref("type","input")}} is text or password, in which case, it is an integer number of characters. {{ HTMLVersionInline(5) }} Applies only when {{htmlattrxref("type","input")}} is set to text, search, tel, url, email, or password; otherwise it is ignored.
src{{domxref("DOMString")}}Reflects the {{ htmlattrxref("src", "input") }} HTML attribute, which specifies a URI for the location of an image to display on the graphical submit button, if the value of {{htmlattrxref("type","input")}} is image; otherwise it is ignored.
step{{domxref("DOMString")}}Reflects the {{ htmlattrxref("step", "input") }} HTML attribute, which works with {{htmlattrxref("min","input")}} and {{htmlattrxref("max","input")}} to limit the increments at which a numeric or date-time value can be set. It can be the string any or a positive floating point number. If this is not set to any, the control accepts only values at multiples of the step value greater than the minimum.
tabIndexlongThe position of the element in the tabbing navigation order for the current document.
type{{domxref("DOMString")}}Reflects the {{ htmlattrxref("type", "input") }} HTML attribute, indicating the type of control to display. See {{ htmlattrxref("type", "input") }} attribute of {{ HTMLElement("input") }} for possible values.
useMap {{ obsolete_inline }}{{domxref("DOMString")}}A client-side image map.
validationMessage {{readonlyInline}}{{domxref("DOMString")}}A localized message that describes the validation constraints that the control does not satisfy (if any). This is the empty string if the control is not a candidate for constraint validation ({{htmlattrxref("willValidate","input")}} is false), or it satisfies its constraints.
validity {{readonlyInline}}{{domxref("ValidityState")}}The validity state that this element is in. 
value{{domxref("DOMString")}} +

Current value in the control.

+ +
+

Note: for certain input types the returned value might not match the value the user has entered. For example, if the user enters a non-numeric value into an <input type="number">, the returned value might be an empty string instead.

+
+
valueAsDate{{jsxref("Date")}}The value of the element, interpreted as a date, or null if conversion is not possible.
valueAsNumberdoubleThe value of the element, interpreted as one of the following in order: +
    +
  1. a time value
  2. +
  3. a number
  4. +
  5. NaN if conversion is not possible
  6. +
+
width{{domxref("DOMString")}}Reflects the {{ htmlattrxref("width", "input") }} HTML attribute, which defines the width of the image displayed for the button, if the value of {{htmlattrxref("type","input")}} is image.
willValidate{{jsxref("Boolean")}}Indicates whether the element is a candidate for constraint validation. It is false if any conditions bar it from constraint validation.
+ +

Methods

+ +

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

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Name & ArgumentsReturnDescription
blur()voidRemoves focus from input; keystrokes will subsequently go nowhere.
checkValidity(){{jsxref("Boolean")}}Returns false if the element is a candidate for constraint validation, and it does not satisfy its constraints. In this case, it also fires an {{event("invalid")}} event at the element. It returns true if the element is not a candidate for constraint validation, or if it satisfies its constraints.
click()voidSimulates a click on the element.
focus()voidFocus on input; keystrokes will subsequently go to this element.
mozSetFileArray(files){{non-standard_inline}}voidSets the files selected on the input to the given array of File objects.  This is an alternative to mozSetFileNameArray which can be used in frame scripts: a chrome script can open files as File objects and send them via message manager.
mozGetFileNameArray(length, filenames){{non-standard_inline}}voidReturns an array of all the file names from the input.
mozSetFileNameArray(filenames, length){{non-standard_inline}}voidSets the filenames for the files selected on the input.  Not for use in frame scripts, because it accesses the filesystem.
select()voidSelects the input text in the element, and focuses it so the user can subsequently replace the whole entry.
setCustomValidity(error)voidSets a custom validity message for the element. If this message is not the empty string, then the element is suffering from a custom validity error, and does not validate.
setSelectionRange(selectionStart, selectionEnd, [optional] selectionDirection)voidSelects a range of text in the element (but does not focus it). The optional selectionDirection parameter may be "forward" or "backward" to establish the direction in which selection was set, or "none" if the direction is unknown or not relevant. The default is "none". Specifying a selectionDirection parameter sets the value of the selectionDirection property.
setRangeText(replacement, [optional] start, [optional] end, [optional] selectMode)voidReplaces a range of text with the new text. Supported input types: text, search, url, tel, password.
stepDown(n)voidDecrements the {{htmlattrxref("value","input")}} by ({{htmlattrxref("step","input")}} * n), where n defaults to 1 if not specified. Throws an INVALID_STATE_ERR exception: +
    +
  • if the method is not applicable to for the current {{htmlattrxref("type","input")}} value.
  • +
  • if the element has no {{htmlattrxref("step","input")}} value.
  • +
  • if the {{htmlattrxref("value","input")}} cannot be converted to a number.
  • +
  • if the resulting value is above the {{htmlattrxref("max","input")}} or below the {{htmlattrxref("min","input")}}. 
  • +
+
stepUp(n)voidIncrements the {{htmlattrxref("value","input")}} by ({{htmlattrxref("step","input")}} * n), where n defaults to 1 if not specified. Throws an INVALID_STATE_ERR exception: +
    +
  • if the method is not applicable to for the current {{htmlattrxref("type","input")}} value.
  • +
  • if the element has no {{htmlattrxref("step","input")}} value.
  • +
  • if the {{htmlattrxref("value","input")}} cannot be converted to a number.
  • +
  • if the resulting value is above the {{htmlattrxref("max","input")}} or below the {{htmlattrxref("min","input")}}.
  • +
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "tthe-input-element.html#the-input-element", "HTMLInputElement")}}{{Spec2('HTML WHATWG')}}No change from {{SpecName("HTML5 W3C")}}
{{SpecName('HTML5 W3C', "forms.html#the-input-element", "HTMLInputElement")}}{{Spec2('HTML5 W3C')}}Technically, the  tabindex and accesskey properties, as well as the blur(), click(), and focus() methods, are now defined on {{domxref("HTMLElement")}}.
+ The following properties are now obsolete: align and useMap.
+ The following properties have been added: autocomplete, autofocus, dirName, files, formAction, formEncType, formMethod, formNoValidate, formTarget, height, indeterminate, labels, list, max, min, multiple, pattern, placeholder, required, selectionDirection, selectionEnd, selectionStart, step, validationMessage, validity, valueAsDate, valueAsNumber, width, and willValidate.
+ The following methods have been added: checkValidity(), setCustomValidity(), setSelectionRange(), stepUp(), and stepDown().
{{SpecName('DOM2 HTML', 'html.html#ID-6043025', 'HTMLInputElement')}}{{Spec2('DOM2 HTML')}}The size property is now an unsigned long. The type property must be entirely given in lowercase characters.
{{SpecName('DOM1', 'level-one-html.html#ID-6043025', 'HTMLInputElement')}}{{Spec2('DOM1')}}Initial definition.
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop(1.0)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
autocomplete & autofocus properties{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
files property{{CompatVersionUnknown}}{{CompatGeckoDesktop(1.9)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
multiple property{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.2")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
indeterminate property{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
list property{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
formAction, formEncType, formMethod, formTarget properties{{CompatVersionUnknown}}{{CompatGeckoDesktop(2)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
formNoValidate, validationMessage, validity, willValidate properties and setCustomValidity() and checkValidity() methods.{{CompatVersionUnknown}}{{CompatGeckoDesktop(2)}}10{{CompatVersionUnknown}}{{CompatVersionUnknown}}
pattern, placeholder, required properties{{CompatVersionUnknown}}{{CompatGeckoDesktop(2)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
height and weight properties{{CompatVersionUnknown}}{{CompatGeckoDesktop(16)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
labels property{{CompatChrome(14.0)}}{{CompatNo}} ({{bug("556743")}}){{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
min, max, and step for <input type="number">{{CompatVersionUnknown}}Experimental, and without specific UI, since {{CompatGeckoDesktop(16)}}: behind the pref dom.experimental_forms{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
stepUp and stepDown methods{{CompatUnknown}}Experimental since {{CompatGeckoDesktop(16)}}: behind the pref dom.experimental_forms
+
+ There are still differences with the latest spec: {{bug(835773)}}
{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
min, max, and step properties for <input type="range">{{CompatVersionUnknown}}{{CompatGeckoDesktop(23)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
min, max, and step properties for <input type="date">{{CompatVersionUnknown}}Experimental, and without specific UI, since {{CompatGeckoDesktop(20)}}: behind the pref dom.experimental_forms{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
min, max, and step properties for other date-related type values{{CompatVersionUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
mozGetFileNameArray() and mozSetFileNameArray() methods {{non-standard_inline}}{{CompatNo}}{{CompatGeckoDesktop("1.9.2")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
mozSetFileArray() method {{non-standard_inline}}{{CompatNo}}{{CompatGeckoDesktop("38")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
autocapitalize{{CompatChrome(43.0)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile(1.0)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
autocapitalize{{CompatNo}}{{CompatChrome(43.0)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(43.0)}}
+
+ +

See also

+ + diff --git a/files/pt-br/web/api/htmlinputelement/select/index.html b/files/pt-br/web/api/htmlinputelement/select/index.html new file mode 100644 index 0000000000..c560161be4 --- /dev/null +++ b/files/pt-br/web/api/htmlinputelement/select/index.html @@ -0,0 +1,52 @@ +--- +title: HTMLInputElement.select() +slug: Web/API/HTMLInputElement/select +tags: + - API + - HTML DOM + - HTMLInputElement + - Referencia + - Selecionar + - Select + - metodo +translation_of: Web/API/HTMLInputElement/select +--- +
{{ APIRef("HTML DOM") }}
+ +

O método HTMLInputElement.select() seleciona todo o texto em um elemento {{HTMLElement("textarea")}} ou em um elemento {{HTMLElement("input")}} do tipo text.

+ +

Sintaxe

+ +
element.select()
+ +

Especificação

+ + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('HTML WHATWG', 'forms.html#dom-textarea/input-select', 'select')}}{{Spec2('HTML WHATWG')}} 
+ +

Notas

+ +

Executar element.select() não irá necessariamente focar o input, por isso é frequentemente usado em conjunto com {{domxref("HTMLElement.focus()")}}.

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/htmlinputelement/setselectionrange/index.html b/files/pt-br/web/api/htmlinputelement/setselectionrange/index.html new file mode 100644 index 0000000000..86631688fc --- /dev/null +++ b/files/pt-br/web/api/htmlinputelement/setselectionrange/index.html @@ -0,0 +1,173 @@ +--- +title: HTMLInputElement.setSelectionRange() +slug: Web/API/HTMLInputElement/setSelectionRange +translation_of: Web/API/HTMLInputElement/setSelectionRange +--- +
{{APIRef("HTML DOM")}}
+ +

O métodoHTMLInputElement.setSelectionRange() define as posições inicial e final da seleção atual do texto em um elemento {{HTMLElement("input")}}.

+ +

Opcionalmente, em navegadores mais novos, você pode especificar a direção na qual a seleção deve ser feita; isso permite a você indicar, por exemplo, que a seleção foi feita como se o usuário tivesse clicado no fim do texto selecionado e arrastado em direção ao início.

+ +

Esse método atualiza ao mesmo tempo HTMLInputElement.selectionStart, selectionEnd, and selectionDirection.

+ +

Syntax

+ +
inputElement.setSelectionRange(selectionStart, selectionEnd, [optional] selectionDirection);
+
+ +

Parameters

+ +
+
selectionStart
+
The 0-based index of the first selected character.
+
selectionEnd
+
The 0-based index of the character after the last selected character.
+
selectionDirection {{optional_inline}}
+
A string indicating the direction in which the selection is performed. This string can be "forward" or "backward", or "none" if the direction is unknown or irrelevant.
+
+ +

Example

+ +

The following code:

+ +
<!DOCTYPE html>
+<html>
+<head>
+<meta charset=utf-8>
+<title>JS Bin</title>
+<script>
+function SelectText () {
+        var input = document.getElementById("mytextbox");
+            input.focus();
+            input.setSelectionRange(2,5);
+}
+</script>
+</head>
+<body>
+  <p><input type="text" id="mytextbox" size="20" value="Mozilla"/></p>
+  <p><button onclick="SelectText()">Select text</button></p>
+</body>
+</html>
+
+ +

will produce the following:

+ +

example.png

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("HTML WHATWG", "forms.html#dom-textarea/input-setselectionrange", "HTMLInputElement.setSelectionRange()")}}{{Spec2("HTML WHATWG")}}No change
{{SpecName("HTML5.1", "forms.html#dom-textarea/input-setselectionrange", "HTMLInputElement.setSelectionRange()")}}{{Spec2("HTML5.1")}}No change
{{SpecName("HTML5 W3C", "forms.html#dom-textarea/input-setselectionrange", "HTMLInputElement.setSelectionRange()")}}{{Spec2("HTML5 W3C")}}Initial definition
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1.0{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.0")}}98.0{{CompatVersionUnknown}}
selectionDirection15[1]{{CompatVersionUnknown}}{{CompatGeckoDesktop("8.0")}}[2]{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}[3]
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome Mobile
Basic support{{CompatVersionUnknown}}Yes{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}No
selectionDirection{{CompatVersionUnknown}}{{CompatGeckoMobile("8.0")}}[2]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}} 
+
+ +

[1] The support for selectionDirection was added Blink in {{WebkitBug("60403")}}.

+ +

Note that accordingly to the WHATWG forms spec selectionStart, selectionEnd properties and setSelectionRange method apply only to inputs of types text, search, URL, tel and password. Chrome, starting from version 33, throws an exception while accessing those properties and method on the rest of input types. For example, on input of type number: "Failed to read the 'selectionStart' property from 'HTMLInputElement': The input element's type ('number') does not support selection." Related links: question on StackOverflow, whatwg bug, Chromium bug.

+ +

[2] The support for selectionDirection was added to Gecko in {{bug("674558")}}.

+ +

[3] The support for selectionDirection was added Webkit in {{WebKitBug("60403")}}.

+ +

See also

+ + diff --git a/files/pt-br/web/api/htmloptionelement/index.html b/files/pt-br/web/api/htmloptionelement/index.html new file mode 100644 index 0000000000..3ec8c7c27a --- /dev/null +++ b/files/pt-br/web/api/htmloptionelement/index.html @@ -0,0 +1,129 @@ +--- +title: HTMLOptionElement +slug: Web/API/HTMLOptionElement +tags: + - API + - HTML DOM + - Interface + - NeedsNewLayout + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/API/HTMLOptionElement +--- +
{{APIRef("HTML DOM")}}
+ +

The HTMLOptionElement interface represents {{HTMLElement("option")}} elements and inherits all classes and methods of the {{domxref("HTMLElement")}} interface.

+ +

{{InheritanceDiagram(600, 120)}}

+ +

Properties

+ +

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

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
defaultSelected{{domxref("Boolean")}}Contains the initial value of the {{htmlattrxref("selected", "option")}} HTML attribute, indicating whether the option is selected by default or not.
disabled{{domxref("Boolean")}}Reflects the value of the {{htmlattrxref("disabled", "option")}} HTML attribute, which indicates that the option is unavailable to be selected. An option can also be disabled if it is a child of an {{HTMLElement("optgroup")}} element that is disabled.
form{{readonlyInline}}{{domxref("HTMLFormElement")}}If the option is a descendent of a {{HTMLElement("select")}} element, then this property has the same value as the form property of the corresponding {{DomXref("HTMLSelectElement")}} object; otherwise, it is null.
index{{readonlyInline}}longThe position of the option within the list of options it belongs to, in tree-order. If the option is not part of a list of options, like when it is part of the {{HTMLElement("datalist")}} element, the value is 0.
label{{domxref("DOMString")}}Reflects the value of the {{htmlattrxref("label", "option")}} HTML attribute, which provides a label for the option. If this attribute isn't specifically set, reading it returns the element's text content.
selected{{domxref("Boolean")}}Indicates whether the option is currently selected.
text{{domxref("DOMString")}}Contains the text content of the element.
value{{domxref("DOMString")}}Reflects the value of the {{htmlattrxref("value", "option")}} HTML attribute, if it exists; otherwise reflects value of the {{domxref("Node.textContent")}} property.
+ +

Methods

+ +

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

+ +
+
Option()
+
Is a constructor creating an HTMLOptionElement object. It has four values: the text to display, text, the value associated, value, the value of defaultSelected, and the value of selected. The last three values are optional.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "#htmloptionelement", "HTMLOptionElement")}}{{Spec2('HTML WHATWG')}} 
{{SpecName('HTML5 W3C', "forms.html#the-option-element", "HTMLOptionElement")}}{{Spec2('HTML5 W3C')}}A constructor, Option(), has been added.
+ The form property can be the null value.
{{SpecName('DOM2 HTML', 'html.html#ID-70901257', 'HTMLOptionElement')}}{{Spec2('DOM2 HTML')}}The selected property changed its meaning: it now indicates if the option is currently selected and no longer if it was initally selected.
+ The defaultSelected property is no longer read-only.
{{SpecName('DOM1', 'level-one-html.html#ID-70901257', 'HTMLOptionElement')}}{{Spec2('DOM1')}}Initial definition
+ +

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/pt-br/web/api/htmloptionelement/option/index.html b/files/pt-br/web/api/htmloptionelement/option/index.html new file mode 100644 index 0000000000..9027e9b799 --- /dev/null +++ b/files/pt-br/web/api/htmloptionelement/option/index.html @@ -0,0 +1,101 @@ +--- +title: Option() +slug: Web/API/HTMLOptionElement/Option +translation_of: Web/API/HTMLOptionElement/Option +--- +
{{APIRef("HTML DOM")}}
+ +

O construtor Option() cria novos {{domxref("HTMLOptionElement")}}.

+ +

Sintaxe

+ +
var optionElementReference = new Option(text, value, defaultSelected, selected);
+ +

Parâmetros

+ +
+
text {{optional_inline}}
+
Um {{domxref("DOMString")}} representa o conteúdo do elemento, o texto mostrado na tela. Se  o texto não é especificado, o texto padrão "" (texto vazio) é  utilizado.
+
value {{optional_inline}}
+
Um {{domxref("DOMString")}} representa o valor do {{domxref("HTMLOptionElement")}}, i.e. o valor do elemento {{htmlelement("option")}}. Se não especificado, o texto é usado como valor, e.g. o elemento {{htmlelement("select")}} tem seu valor associado quando o formulário é submetido ao servidor.
+
defaultSelected {{optional_inline}}
+
Um {{domxref("Boolean")}} é usado para adicionar o atributo selected, para que este {{htmlelement("option")}} seja mostrado como selecionado no elemento {{htmlelement("select")}} quando a página for carregada. Se não especificado, o estado padrão é não selecionado. Observe que o defaultSelected = true não define a opção como o valor selecionado do elemento {{htmlelement("select")}}.
+
selected {{optional_inline}}
+
Um {{domxref("Boolean")}} é usado para colocar elemento {{htmlelement("option")}} no estado de selecionado; como padrão do elemento tem o estado de não selecionado. Se omitido, mesmo que o parâmetro defaultSelected for verdadeiro, o elemento {{htmlelement("option")}} não é selecionado. 
+
+ +

Examplos

+ +

Adicionando novas tags options

+ +
 /* assumindo que temos este HTML
+<select id='s'>
+
+</select>
+*/
+
+var s = document.getElementById('s');
+var options = [Quatro, Cinco, Seis];
+
+options.forEach(function(elemento, chave) {
+    s.appendChild(new Option(elemento, chave));
+});
+
+ /* Resultado
+<select id='s'>
+    <option value="0">Quatro</option>
+    <option value="1">Cinco</option>
+    <option value="2">Seis</option>
+</select> */
+
+ +

Adicionando options com diferentes parâmetros

+ +
/* assumindo que temos este HTML
+<select id="s">
+    <option>Primeiro</option>
+    <option>Segundo</option>
+    <option>Terceiro</option>
+</select>
+*/
+
+var s = document.getElementById('s');
+var options = [ 'zero', 'um', 'dois' ];
+
+options.forEach(function(elemento, chave) {
+  if (elemento == 'zero') {
+    s[s.options.length] = new Option(elemento, s.options.length, false, false);
+  }
+  if (elemento == 'um') {
+    s[s.options.length] = new Option(elemento, s.options.length, true, false); // Adicionando atributo "selected"
+  }
+  if (elemento == 'dois') {
+    s[s.options.length] = new Option(elemento, s.options.length, false, true); // Apenas irá selecionar a opção na visualização
+  }
+});
+
+/* Resultado
+<select id="s">
+  <option value="0">zero</option>
+  <option value="1" selected="">um</option>
+  <option value="2">dois</option> // O usuário verá esta opção selecionada
+</select>
+*/
+ +

Especificação

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
HTML5
+ The definition of 'Option' in that specification.
Recomendado
diff --git a/files/pt-br/web/api/htmlselectelement/checkvalidity/index.html b/files/pt-br/web/api/htmlselectelement/checkvalidity/index.html new file mode 100644 index 0000000000..11bfc0a7bf --- /dev/null +++ b/files/pt-br/web/api/htmlselectelement/checkvalidity/index.html @@ -0,0 +1,98 @@ +--- +title: HTMLSelectElement.checkValidity() +slug: Web/API/HTMLSelectElement/checkValidity +translation_of: Web/API/HTMLSelectElement/checkValidity +--- +
{{ APIRef("HTML DOM") }}
+ +

O HTMLSelectElement.checkValidity() método verifica se o elemento possui restrições e se as satisfaz. Se o elemento falhar suas restrições, o navegador dispara um evento {{event("invalid")}} no elemento e, em seguida, retorna false.

+ +

Sintaxe

+ +
var resultado = selectElt.checkValidity();
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG', '#dom-cva-checkvalidity', 'HTMLSelectElement.checkValidity()')}}{{Spec2('HTML WHATWG')}}No change since the latest snapshot, {{SpecName('HTML5 W3C')}}.
{{SpecName('HTML5 W3C', 'forms.html#dom-cva-checkvalidity', 'HTMLSelectElement.checkValidity()')}}{{Spec2('HTML5 W3C')}}Initial definition, snapshot of {{SpecName('HTML WHATWG')}}
+ +

Browser compatibilidade

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop(2.0)}}10{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChromeEdgeFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile(2.0)}}1.0{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/htmlselectelement/index.html b/files/pt-br/web/api/htmlselectelement/index.html new file mode 100644 index 0000000000..94c0f2edd9 --- /dev/null +++ b/files/pt-br/web/api/htmlselectelement/index.html @@ -0,0 +1,290 @@ +--- +title: HTMLSelectElement +slug: Web/API/HTMLSelectElement +tags: + - API + - HTML DOM + - Interface + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/API/HTMLSelectElement +--- +
{{APIRef("HTML DOM")}}
+ +

The HTMLSelectElement interface represents a {{HTMLElement("select")}} HTML Element. These elements also share all of the properties and methods of other HTML elements via the {{domxref("HTMLElement")}} interface.

+ +

{{InheritanceDiagram(600, 120)}}

+ +

Properties

+ +

This interface inherits the properties of {{domxref("HTMLElement")}}, and of {{domxref("Element")}} and {{domxref("Node")}}.

+ +
+
{{domxref("HTMLSelectElement.autofocus")}}
+
A {{jsxref("Boolean")}} reflecting the {{htmlattrxref("autofocus", "select")}} HTML attribute, which indicates whether the control should have input focus when the page loads, unless the user overrides it, for example by typing in a different control. Only one form-associated element in a document can have this attribute specified. {{gecko_minversion_inline("2.0")}}
+
{{domxref("HTMLSelectElement.disabled")}}
+
A {{jsxref("Boolean")}} reflecting the {{htmlattrxref("disabled", "select")}} HTML attribute, which indicates whether the control is disabled. If it is disabled, it does not accept clicks.
+
{{domxref("HTMLSelectElement.form")}}{{ReadOnlyInline}}
+
An {{domxref("HTMLFormElement")}} referencing the form that this element is associated with. If the element is not associated with of a {{HTMLElement("form")}} element, then it returns null.
+
{{domxref("HTMLSelectElement.labels")}}{{ReadOnlyInline}}
+
A {{domxref("NodeList")}} of {{HTMLElement("label")}} elements associated with the element.
+
{{domxref("HTMLSelectElement.length")}}
+
An unsigned long The number of {{HTMLElement("option")}} elements in this select element.
+
{{domxref("HTMLSelectElement.multiple")}}
+
A {{jsxref("Boolean")}} reflecting the {{htmlattrxref("multiple", "select")}} HTML attribute, which indicates whether multiple items can be selected.
+
{{domxref("HTMLSelectElement.name")}}
+
A {{domxref("DOMString")}} reflecting the {{htmlattrxref("name", "select")}} HTML attribute, containing the name of this control used by servers and DOM search functions.
+
{{domxref("HTMLSelectElement.options")}}{{ReadOnlyInline}}
+
An {{domxref("HTMLOptionsCollection")}} representing the set of {{HTMLElement("option")}} elements contained by this element.
+
{{domxref("HTMLSelectElement.required")}}
+
A {{jsxref("Boolean")}} reflecting the {{htmlattrxref("required", "select")}} HTML attribute, which indicates whether the user is required to select a value before submitting the form. {{gecko_minversion_inline("2.0")}}
+
{{domxref("HTMLSelectElement.selectedIndex")}}
+
A long reflecting the index of the first selected {{HTMLElement("option")}} element. The value -1 indicates no element is selected.
+
{{domxref("HTMLSelectElement.selectedOptions")}}{{ReadOnlyInline}}
+
An {{domxref("HTMLCollection")}} representing the set of {{HTMLElement("option")}} elements that are selected.
+
{{domxref("HTMLSelectElement.size")}}
+
A long reflecting the {{htmlattrxref("size", "select")}} HTML attribute, which contains the number of visible items in the control. The default is 1, unless multiple is true, in which case it is 4.
+
{{domxref("HTMLSelectElement.type")}}{{ReadOnlyInline}}
+
A {{domxref("DOMString")}} represeting the form control's type. When multiple is true, it returns "select-multiple"; otherwise, it returns "select-one".
+
{{domxref("HTMLSelectElement.validationMessage")}}{{ReadOnlyInline}}
+
A {{domxref("DOMString")}} representing a localized message that describes the validation constraints that the control does not satisfy (if any). This attribute is the empty string if the control is not a candidate for constraint validation (willValidate is false), or it satisfies its constraints.
+
{{domxref("HTMLSelectElement.validity")}}{{ReadOnlyInline}}
+
A {{domxref("ValidityState")}} reflecting the validity state that this control is in.
+
{{domxref("HTMLSelectElement.value")}}
+
A {{domxref("DOMString")}} reflecting the value of the form control (the first selected option). Returns the value attribute of the option element or if it is missing, the text attribute.
+
{{domxref("HTMLSelectElement.willValidate")}}{{ReadOnlyInline}}
+
A {{jsxref("Boolean")}} that indicates whether the button is a candidate for constraint validation. It is false if any conditions bar it from constraint validation.
+
+ +

Methods

+ +

This interface inherits the methods of {{domxref("HTMLElement")}}, and of {{domxref("Element")}} and {{domxref("Node")}}.

+ +
+
{{domxref("HTMLSelectElement.add()")}}
+
Adds an element to the collection of option elements for this select element.
+
{{domxref("HTMLSelectElement.blur()")}}{{obsolete_inline}}
+
Removes input focus from this element. This method is now implemented on {{domxref("HTMLElement")}}.
+
{{domxref("HTMLSelectElement.checkValidity()")}}
+
Checks whether the element has any constraints and whether it satisfies them. If the element fails its constraints, the browser fires a cancelable {{event("invalid")}} event at the element (and returns false).
+
{{domxref("HTMLSelectElement.focus()")}}{{obsolete_inline}}
+
Gives input focus to this element. This method is now implemented on {{domxref("HTMLElement")}}.
+
{{domxref("HTMLSelectElement.item()")}}
+
Gets an item from the options collection for this {{HTMLElement("select")}} element. You can also access an item by specifying the index in array-style brackets or parentheses, without calling this method explicitly.
+
{{domxref("HTMLSelectElement.namedItem()")}}
+
Gets the item in the options collection with the specified name. The name string can match either the id or the name attribute of an option node. You can also access an item by specifying the name in array-style brackets or parentheses, without calling this method explicitly.
+
{{domxref("HTMLSelectElement.remove()")}}
+
Removes the element at the specified index from the options collection for this select element.
+
{{domxref("HTMLSelectElement.setCustomValidity()")}}
+
Sets the custom validity message for the selection element to the specified message. Use the empty string to indicate that the element does not have a custom validity error.
+
+ +

Example

+ +

Get information about the selected option

+ +
/* assuming we have the following HTML
+<select id='s'>
+    <option>First</option>
+    <option selected>Second</option>
+    <option>Third</option>
+</select>
+*/
+
+var select = document.getElementById('s');
+
+// return the index of the selected option
+console.log(select.selectedIndex); // 1
+
+// return the value of the selected option
+console.log(select.options[select.selectedIndex].value) // Second
+
+ +

A better way to track changes to the user's selection is to watch for the {{event("change")}} event to occur on the <select>. This will tell you when the value changes, and you can then update anything you need to. See the example provided in the documentation for the change event for details.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#htmlselectelement', 'HTMLSelectElement')}}{{Spec2('HTML WHATWG')}}Since the latest snapshot, {{SpecName('HTML5 W3C')}}, it adds the autocomplete property and the reportValidity() method.
{{SpecName('HTML5 W3C', 'forms.html#htmlselectelement', 'HTMLSelectElement')}}{{Spec2('HTML5 W3C')}}Is a snapshot of {{SpecName("HTML WHATWG")}}.
+ It adds the autofocus, form, required, labels, selectedOptions, willValidate, validity and validationMessage properties.
+ The tabindex property and the blur() and focus() methods have been moved to {{domxref("HTMLElement")}}.
+ The methods item(), namedItem(), checkValidity() and setCustomValidity().
{{SpecName('DOM2 HTML', 'html.html#ID-94282980', 'HTMLSelectElement')}}{{Spec2('DOM2 HTML')}}options now returns an {{domxref("HTMLOptionsCollection")}}.
+ length now returns an unsigned long.
{{SpecName('DOM1', 'level-one-html.html#ID-94282980', 'HTMLSelectElement')}}{{Spec2('DOM1')}}Initial definition
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support1.0{{CompatVersionUnknown}}{{CompatGeckoDesktop(1.0)}} [2]1.01.01.0
item() and namedItem(){{CompatVersionUnknown}}{{CompatVersionUnknown}}[3]{{CompatGeckoDesktop(2.0)}}8[3]{{CompatVersionUnknown}}{{CompatVersionUnknown}}
setCustomValidity(), checkValidity(), willValidate, validationMessage, validity{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop(2.0)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
selectedOptions{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop(26)}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
labels{{CompatVersionUnknown}}{{CompatNo}}{{CompatGeckoDesktop(56)}}[1]{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChromeEdgeFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Basic support1.01.0{{CompatVersionUnknown}}{{CompatGeckoMobile(1)}}1.01.01.01.0
item() and namedItem(){{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile(2.0)}}1.0{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
setCustomValidity(), checkValidity(), willValidate, validationMessage, validity{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile(2.0)}}1.0{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
selectedOptions{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile(26)}}1.2{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
labels{{CompatUnknown}}{{CompatUnknown}}{{CompatNo}}{{CompatGeckoMobile(56)}}[1]{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
+
+ +

[1] Implemented in {{bug("556743")}}.

+ +

[2] Historically, Firefox has allowed keyboard and mouse events to bubble up from the <option> element to the parent {{HTMLElement("select")}} element. This doesn't happen in Chrome, however, although this behavior is inconsistent across many browsers. For better Web compatibility (and for technical reasons), when Firefox is in multi-process mode and the <select> element is displayed as a drop-down list. The behavior is unchanged if the <select> is presented inline and it has either the multiple attribute defined or a size attribute set to more than 1. Rather than watching <option> elements for events, you should watch for {event("change")}} events on {{HTMLElement("select")}}. See {{bug(1090602)}} for details.

+ +

[3] namedItem does not appear to take the name attribute into account (only the id attribute) on Internet Explorer and Edge. There is a bug report to Microsoft about this.

+ +

See also

+ + diff --git a/files/pt-br/web/api/htmlshadowelement/index.html b/files/pt-br/web/api/htmlshadowelement/index.html new file mode 100644 index 0000000000..fe52a8caf5 --- /dev/null +++ b/files/pt-br/web/api/htmlshadowelement/index.html @@ -0,0 +1,67 @@ +--- +title: HTMLShadowElement +slug: Web/API/HTMLShadowElement +tags: + - API + - HTML DOM + - HTMLShadowElement + - Web/Api + - shadow dom +translation_of: Web/API/HTMLShadowElement +--- +

{{obsolete_header}}

+ +

{{ APIRef("Web Components") }}

+ +

A interface HTMLShadowElement representa um  elemento HTML {{HTMLElement("shadow")}}, Ao qual é usado no Shadow DOM.

+ +

Propriedades

+ +

 Esta interface herda as propriedades do {{domxref("HTMLElement")}}.

+ +

Métodos

+ +

Esta interface herda os métodos do {{domxref("HTMLElement")}}.

+ +
+
{{domxref("HTMLShadowElement.getDistributedNodes()")}}
+
Retorna uma estática {{domxref("NodeList")}} do {{glossary("distributed nodes")}} associado com este elemento <shadow>.
+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('Shadow DOM', '#the-shadow-element', 'shadow')}}{{Spec2('Shadow DOM')}} 
+ +

Browser compatível

+ + + +

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

+ +

Se Shadow DOM não é habilitado no Firefox, os elementos <shadow> se comportarão como {{domxref("HTMLUnknownElement")}}. Shadow DOM foi implementado primeiro no Firefox 28 e está por trás de uma preferência, dom.webcomponents.enabled, ao qual é desabilitado por padrão. [1]

+ +

Veja também

+ + + +
+
 
+
diff --git a/files/pt-br/web/api/htmlspanelement/index.html b/files/pt-br/web/api/htmlspanelement/index.html new file mode 100644 index 0000000000..dd06fbd0b0 --- /dev/null +++ b/files/pt-br/web/api/htmlspanelement/index.html @@ -0,0 +1,72 @@ +--- +title: HTMLSpanElement +slug: Web/API/HTMLSpanElement +tags: + - API + - HTML DOM + - Interface + - span +translation_of: Web/API/HTMLSpanElement +--- +

{{APIRef("HTML DOM")}}

+ +

A interface HTMLSpanElement representa um elemento {{HTMLElement("span")}} e deriva de uma interface {{DOMxRef("HTMLElement")}}, mas sem implementar propriedades ou métodos adicionais.

+ +

{{InheritanceDiagram(600, 120)}}

+ +

Propriedades

+ +

Essa interface não possui propriedades, mas herda propriedades de: {{DOMxRef("HTMLElement")}}.

+ +

Métodos

+ +

Essa interface não possui métodos, mas herda métodos de: {{DOMxRef("HTMLElement")}}.

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG', "text-level-semantics.html#htmlspanelement", "HTMLSpanElement")}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5.3', "textlevel-semantics.html#htmlspanelement", "HTMLSpanElement")}}{{Spec2('HTML5.3')}}
{{SpecName('HTML5.2', "textlevel-semantics.html#htmlspanelement", "HTMLSpanElement")}}{{Spec2('HTML5.2')}}
{{SpecName('HTML5.1', "textlevel-semantics.html#htmlspanelement", "HTMLSpanElement")}}{{Spec2('HTML5.1')}}
{{SpecName('HTML5 W3C', "text-level-semantics.html#htmlspanelement", "HTMLSpanElement")}}{{Spec2('HTML5 W3C')}}A definição inicial, como {{HTMLElement("span")}} foi associada a um {{DOMxRef("HTMLElement")}}} antes disso.
+ +

Compatibilidade do navegador

+ + + +

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

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/idbcursor/index.html b/files/pt-br/web/api/idbcursor/index.html new file mode 100644 index 0000000000..ce9c02414b --- /dev/null +++ b/files/pt-br/web/api/idbcursor/index.html @@ -0,0 +1,181 @@ +--- +title: IDBCursor +slug: Web/API/IDBCursor +translation_of: Web/API/IDBCursor +--- +

{{APIRef("IndexedDB")}}

+ +

O IDBCursor é uma interface da API IndexedDB que representa o cursor para atravessar ou interagir sobre vários registros em um banco de dados.

+ +

O cursor tem uma fonte que indica qual índice ou armazenamento o objeto está sobre a iteração. Ele tem uma posição dentro do intervalo, e move-se numa direcção que é aumentar ou diminuir na ordem de chaves ficha. O cursor permite que um aplicativo para processar de forma assíncrona todos os registros na faixa do cursor.

+ +

Pode ter um número ilimitado de cursores ao mesmo tempo. Você sempre consegue o mesmo objeto IDBCursor representando um determinado cursor. As operações são realizadas na loja de índice ou objeto subjacente.

+ +

{{AvailableInWorkers}}

+ +

Methods

+ +
+
{{domxref("IDBCursor.advance()")}}
+
Define o número de vezes um cursor deve mover a sua posição para a frente.
+
{{domxref("IDBCursor.continue()")}}
+
Avança o cursor para a próxima posição ao longo de sua direção, para o item cuja chave corresponde ao parâmetro chave opcional.
+
{{domxref("IDBCursor.delete()")}}
+
Retorna um {{domxref("IDBRequest")}} objeto, e, em um segmento separado, exclui o registro na posição do cursor, sem alterar a posição do cursor. Isso pode ser usado para excluir registros específicos.
+
{{domxref("IDBCursor.update()")}}
+
Retorna um {{domxref("IDBRequest")}} objeto, e, em um segmento separado, atualiza o valor na posição atual do cursor em armazenar o objeto. Isso pode ser usado para atualizar registros específicos.
+
+ +

Propriedades

+ +
+
{{domxref("IDBCursor.source")}} {{readonlyInline}}
+
Retorna um {{domxref("IDBObjectStore")}} ou {{domxref("IDBIndex")}} que o cursor é a iteração. Esta função nunca retorna nulo ou gera uma exceção, mesmo se o cursor está actualmente a ser iterativo, tem iterated além de seu fim, ou a sua operação não está ativa.
+
{{domxref("IDBCursor.direction")}} {{readonlyInline}}
+
Retorna a direcção do percurso do cursor. Veja constantes para os possíveis valores.
+
{{domxref("IDBCursor.key")}} {{readonlyInline}}
+
Returns the key for the record at the cursor's position. If the cursor is outside its range, this is set to undefined. The cursor's key can be any data type.
+
{{domxref("IDBCursor.primaryKey")}} {{readonlyInline}}
+
Retorna a chave para o registro na posição do cursor. Se o cursor estiver fora do seu alcance, isso é definido como indefinido. A chave do cursor pode ser qualquer tipo de dados.
+
+ +

Constantes

+ +
{{ obsolete_header(25) }}
+ +
+

These constants are no longer available. You should use the string constants directly instead. ({{ bug(891944) }})

+
+ + + +

Example

+ +

In this simple fragment we create a transaction, retrieve an object store, then use a cursor to iterate through all the records in the object store. The cursor does not require us to select the data based on a key; we can just grab all of it. Also note that in each iteration of the loop, you can grab data from the current record under the cursor object using cursor.value.foo. For a complete working example, see our IDBCursor example (view example live.)

+ +
function displayData() {
+  var transaction = db.transaction(['rushAlbumList'], "readonly");
+  var objectStore = transaction.objectStore('rushAlbumList');
+
+  objectStore.openCursor().onsuccess = function(event) {
+    var cursor = event.target.result;
+    if(cursor) {
+      var listItem = document.createElement('li');
+      listItem.innerHTML = cursor.value.albumTitle + ', ' + cursor.value.year;
+      list.appendChild(listItem);
+
+      cursor.continue();
+    } else {
+      console.log('Entries all displayed.');
+    }
+  };
+};
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('IndexedDB', '#idl-def-IDBCursor', 'cursor')}}{{Spec2('IndexedDB')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support23{{property_prefix("webkit")}}
+ 24
10 {{property_prefix("moz")}}
+ {{CompatGeckoDesktop("16.0")}}
10, partial157.1
Available in workers{{CompatVersionUnknown}}{{CompatGeckoMobile("37.0")}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Basic support4.4{{CompatGeckoMobile("22.0")}}1.0.110228
Available in workers{{CompatVersionUnknown}}{{CompatGeckoMobile("37.0")}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
+
+ +
+

Be careful in Chrome as it still implements the old specification along with the new one. Similarly it still has the prefixed webkitIndexedDB property even if the unprefixed indexedDB is present.

+
+ +

See also

+ + diff --git a/files/pt-br/web/api/idbfactory/index.html b/files/pt-br/web/api/idbfactory/index.html new file mode 100644 index 0000000000..e422763fd2 --- /dev/null +++ b/files/pt-br/web/api/idbfactory/index.html @@ -0,0 +1,210 @@ +--- +title: IDBFactory +slug: Web/API/IDBFactory +translation_of: Web/API/IDBFactory +--- +

{{APIRef("IndexedDB")}}

+ +
+

A interface IDBFactory, pertencente a IndexedDB API , permite que aplicativos acessem de forma assíncrona os bancos de dados indexados. O objeto que implementa a interface é o window.indexedDB, com este objeto é possível criar, acessar, modificar e excluir informações de um banco de dados. 

+ +

{{AvailableInWorkers}}

+
+ +

Métodos

+ +
+
{{domxref("IDBFactory.open")}}
+
Realizar a abertura de uma conexão com uma base de dados.
+
{{domxref("IDBFactory.deleteDatabase")}}
+
Remove uma base de dados.
+
{{domxref("IDBFactory.cmp")}}
+
Compara dois valores chaves e determina se elas são iguais e se não, quem é a maior.
+
+ +

Métodos Obsoletos

+ +
+
IDBFactory.open, a versão original {{ obsolete_inline }}
+
Este método realizava conexão com uma base de dados, ele ainda é usado em alguns navegadores.
+
+ +

Exemplo

+ +

No código abaixo, realizamos uma conexão com um banco de dados e incluímos manipuladores para os casos de sucesso e erro. Você pode obter o To-do Notifications app como exemplo (Visualizar exemplo.)

+ +
var note = document.querySelector("ul");
+
+// In the following line, you should include the prefixes of implementations you want to test.
+window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
+// DON'T use "var indexedDB = ..." if you're not in a function.
+// Moreover, you may need references to some window.IDB* objects:
+window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction;
+window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange;
+// (Mozilla has never prefixed these objects, so we don't need window.mozIDB*)
+
+// Let us open version 4 of our database
+var DBOpenRequest = window.indexedDB.open("toDoList", 4);
+
+// these two event handlers act on the database being opened successfully, or not
+DBOpenRequest.onerror = function(event) {
+  note.innerHTML += '<li>Error loading database.</li>';
+};
+
+DBOpenRequest.onsuccess = function(event) {
+  note.innerHTML += '<li>Database initialised.</li>';
+
+  // store the result of opening the database in the db variable. This is used a lot later on, for opening transactions and suchlike.
+  db = DBOpenRequest.result;
+};
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('IndexedDB', '#idl-def-IDBFactory', 'IDBFactory')}}{{Spec2('IndexedDB')}} 
{{SpecName("IndexedDB 2", "#factory-interface", "IDBFactory")}}{{Spec2("IndexedDB 2")}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(23)}} {{property_prefix("webkit")}}
+ {{CompatChrome(24)}} (unprefixed)
+ {{CompatChrome(38)}} (prefixes deprecated)
+ {{CompatChrome(57)}} (prefixes removed)
{{CompatVersionUnknown}}10 {{property_prefix("moz")}}
+ {{CompatGeckoDesktop("16.0")}}
10, partial15
+ {{CompatOpera(44)}} (prefixes removed)
7.1
Available in workers{{CompatVersionUnknown}} (unprefixed)
+ {{CompatChrome(38)}} (prefixes deprecated)
+ {{CompatChrome(57)}} (prefixes removed)
{{CompatVersionUnknown}}{{CompatGeckoMobile("37.0")}}{{CompatUnknown}}{{CompatVersionUnknown}}
+ {{CompatOpera(44)}} (prefixes removed)
{{CompatUnknown}}
Indexed Database 2.0{{CompatChrome(58)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOpera(45)}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidEdgeFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}
+ {{CompatChrome(38)}} (prefixes deprecated)
+ {{CompatChrome(57)}} (prefixes removed)
{{CompatVersionUnknown}}
+ {{CompatChrome(38)}} (prefixes deprecated)
+ {{CompatChrome(57)}} (prefixes removed)
{{CompatVersionUnknown}}{{CompatGeckoMobile("22.0")}}1.0.11022
+ {{CompatOperaMobile(44)}} (prefixes removed)
8
Available in workers{{CompatVersionUnknown}} (unprefixed)
+ {{CompatChrome(38)}} (prefixes deprecated)
+ {{CompatChrome(57)}} (prefixes removed)
{{CompatVersionUnknown}} (unprefixed)
+ {{CompatChrome(38)}} (prefixes deprecated)
+ {{CompatChrome(57)}} (prefixes removed)
{{CompatVersionUnknown}}{{CompatGeckoMobile("37.0")}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
+ {{CompatOperaMobile(44)}} (prefixes removed)
{{CompatUnknown}}
Indexed Database 2.0{{CompatChrome(58)}}{{CompatChrome(58)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOperaMobile(45)}}{{CompatUnknown}}
+
+ +

See also

+ + diff --git a/files/pt-br/web/api/imagecapture/index.html b/files/pt-br/web/api/imagecapture/index.html new file mode 100644 index 0000000000..242ec1ac22 --- /dev/null +++ b/files/pt-br/web/api/imagecapture/index.html @@ -0,0 +1,116 @@ +--- +title: ImageCapture +slug: Web/API/ImageCapture +translation_of: Web/API/ImageCapture +--- +
{{APIRef("MediaStream Image")}}
+ +

A interface ImageCapture da MediaStream Image Capture API fornece métodos para permitir a captura de images ou fotos de uma câmera ou de um dispositivo fotográfico. É fornecido uma interface para capturar images de um dispositive fotográfico referenciado por meio de um {{domxref("MediaStreamTrack")}} válido.

+ +

Construtor

+ +
+
{{domxref("ImageCapture.ImageCapture()", "ImageCapture()")}}
+
Cria um novo objeto ImageCapture que pode ser usado para capturar quadros estáticos (fotos) de um determinado {{domxref ("MediaStreamTrack")}} que representa um fluxo de vídeo.
+
+ +

Propriedades

+ +
+
{{domxref("ImageCapture.track")}} {{readonlyinline}}
+
Retorna uma referência ao {{domxref ("MediaStreamTrack")}} passado ao construtor.
+
+ +

Métodos

+ +

A interface do ImageCapture é baseada em {{domxref ("EventTarget")}}}, portanto inclui os métodos definidos por essa interface e os listados abaixo.

+ +
+
{{domxref("ImageCapture.takePhoto()")}}
+
Faz uma única exposição usando o dispositivo de captura de vídeo que busca um {{domxref ("MediaStreamTrack")}} e retorna um {{jsxref ("Promise")}} que resolve com um {{domxref ("Blob")}} que contém o dados.
+
{{domxref("ImageCapture.getPhotoCapabilities()")}}
+
Retorna um {{jsxref ("Promise")}} que resolve com um objeto {{domxref ("PhotoCapabilities")}} que contém os intervalos de opções de configuração disponíveis.
+
{{domxref("ImageCapture.getPhotoSettings()")}}
+
Retorna um {{jsxref ("Promise")}} que é resolvido com um objeto {{domxref ("PhotoSettings")}} que contém as definições de configuração de foto atuais.
+
{{domxref("ImageCapture.grabFrame()")}}
+
Tira uma captura instantânea do vídeo ao vivo em um {{domxref ("MediaStreamTrack")}}, retornando um {{domxref ("ImageBitmap")}}, se for bem-sucedido.
+
+ +

Exemplo

+ +

O código a seguir foi retirado do Chrome's Grab Frame - Take Photo Sample. Como o ImageCapture requer algum lugar para capturar uma imagem, o exemplo abaixo começa com o dispositivo de mídia de um dispositivo (em outras palavras, uma câmera).

+ +

Este exemplo mostra, aproximadamente, um {{domxref ("MediaStreamTrack")}} extraído do {{domxref ("MediaStream")}} de um dispositivo. A faixa é usada para criar um objeto ImageCapture, para que seja possível chamar takePhoto() e grabFrame(). Por fim, mostra como aplicar os resultados dessas chamadas a um objeto de tela.

+ +
var imageCapture;
+
+function onGetUserMediaButtonClick() {
+  navigator.mediaDevices.getUserMedia({video: true})
+  .then(mediaStream => {
+    document.querySelector('video').srcObject = mediaStream;
+
+    const track = mediaStream.getVideoTracks()[0];
+    imageCapture = new ImageCapture(track);
+  })
+  .catch(error => console.log(error));
+}
+
+function onGrabFrameButtonClick() {
+  imageCapture.grabFrame()
+  .then(imageBitmap => {
+    const canvas = document.querySelector('#grabFrameCanvas');
+    drawCanvas(canvas, imageBitmap);
+  })
+  .catch(error => console.log(error));
+}
+
+function onTakePhotoButtonClick() {
+  imageCapture.takePhoto()
+  .then(blob => createImageBitmap(blob))
+  .then(imageBitmap => {
+    const canvas = document.querySelector('#takePhotoCanvas');
+    drawCanvas(canvas, imageBitmap);
+  })
+  .catch(error => console.log(error));
+}
+
+/* Utils */
+
+function drawCanvas(canvas, img) {
+  canvas.width = getComputedStyle(canvas).width.split('px')[0];
+  canvas.height = getComputedStyle(canvas).height.split('px')[0];
+  let ratio  = Math.min(canvas.width / img.width, canvas.height / img.height);
+  let x = (canvas.width - img.width * ratio) / 2;
+  let y = (canvas.height - img.height * ratio) / 2;
+  canvas.getContext('2d').clearRect(0, 0, canvas.width, canvas.height);
+  canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height,
+      x, y, img.width * ratio, img.height * ratio);
+}
+
+document.querySelector('video').addEventListener('play', function() {
+  document.querySelector('#grabFrameButton').disabled = false;
+  document.querySelector('#takePhotoButton').disabled = false;
+});
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('MediaStream Image','#imagecaptureapi','ImageCapture')}}{{Spec2('MediaStream Image')}}Initial definition.
+ +

Compatibilidade do navegador

+ + + +

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

diff --git a/files/pt-br/web/api/index.html b/files/pt-br/web/api/index.html new file mode 100644 index 0000000000..4537f1f179 --- /dev/null +++ b/files/pt-br/web/api/index.html @@ -0,0 +1,32 @@ +--- +title: APIs da Web +slug: Web/API +tags: + - API + - DOM + - JavaScript + - Referencia + - Web +translation_of: Web/API +--- +

Ao escrever código para a Web, há muitas APIs da Web disponíveis. Abaixo está uma lista de todas as APIs e interfaces (tipos de objeto) que você pode usar ao desenvolver seu aplicativo ou site da Web.

+ +

As APIs da Web são normalmente usadas com JavaScript, embora isso nem sempre tenha que ser o caso.

+ +

Especificações

+ +

Esta é uma lista de todas as APIs disponíveis.

+ +

{{ListGroups}}

+ +

Interfaces

+ +

Esta é uma lista de todas as interfaces (isto é, tipos de objetos) disponíveis.

+ +
{{APIListAlpha}}
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html b/files/pt-br/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html new file mode 100644 index 0000000000..c83b48750e --- /dev/null +++ b/files/pt-br/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html @@ -0,0 +1,249 @@ +--- +title: Conceitos Básicos sobre IndexedDb +slug: Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB +tags: + - Avançado + - IndexedDB + - conceitos +translation_of: Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB +--- +

{{DefaultAPISidebar("IndexedDB")}}

+ +
+

IndexedDB é uma forma de você armazenar dados no browser do usuário. Permite criar aplicativos da Web com habilidades de consulta ricas, independentemente da disponibilidade da rede, esses aplicativos podem trabalhar on-line e off-line. IndexedDB é útil para aplicativos que armazenam uma grande quantidade de dados (por exemplo, um catálogo de DVDs em uma biblioteca de empréstimos) e aplicativos que não precisam de conectividade persistente à Internet para trabalhar (por exemplo, clientes de e-mail, listas de tarefas e Blocos de notas).

+
+ +

Sobre esse documento

+ +

Essa introdução discute conceitos essenciais e a terminologia do IndexedDB. Ele vai ter dar um visão geral e explicar conceitos chaves.

+ +

Você vai achar útil:

+ + + +

Visão geral do IndexedDB

+ +

IndexedDB permite você armazenar e consultar objetos que são indexados com uma chave. Todas as mudanças na base dados são feitas por transações. Como a maioria soluções de armazenamento web, IndexedDB segue a política de mesma origem. Então enquanto você pode acessar dados armazenados em um domínio, você não pode acessar em diferentes domínios.

+ +

IndexedDB é uma API assíncrona que pode ser usada em diversos contextos, incluindo WebWorkers. Isso permite o uso de uma versão síncrona também, para o uso em web workers, mas isso foi removido da especificação por falta de interesse da comunidade web.

+ +


+ IndexedDB foi pensado para ser uma especificação concorrente ao banco de dados WebSQL, mas o W3C depreciou o WebSQL em 18 de novembro de 2010. Embora IndexedDB e WebSQL sejam soluções para armazenamento, eles não oferecem as mesmas funcionalidades. WebSQL Database é um sistema de acesso a banco de dados relacional, enquanto que IndexedDB é um sistema de tabelas indexadas.

+ +

Principais conceitos

+ +

 Se você já trabalhou com outros tipos de banco de dados, você pode esquecer enquanto trabalha com IndexedDB. E tenha esses importantes conceitos em mente:

+ + + +

 

+ + + +

Definições

+ +

Essa seção define e explica os termos usado na API IndexedDB.

+ +

Base de dados

+ +
+
Base de dados
+
Um repositório de informação, normalmente é composto por um ou mais object stores. cada base de dados deve possuir: +
    +
  • Name. This identifies the database within a specific origin and stays constant throughout its lifetime. The name can be any string value (including an empty string).
  • +
  • +

    Current version. When a database is first created, its version is the integer 1 if not specified otherwise. Each database can have only one version at any given time.

    +
  • +
+
+
durable
+
+

In Firefox, IndexedDB used to be durable, meaning that in a readwrite transaction {{domxref("IDBTransaction.oncomplete")}} was fired only when all data was guaranteed to have been flushed to disk.

+ +

As of Firefox 40, IndexedDB transactions have relaxed durability guarantees to increase performance (see {{Bug("1112702")}}), which is the same behaviour as other IndexedDB-supporting browsers. In this case the {{Event("complete")}} event is fired after the OS has been told to write the data but potentially before that data has actually been flushed to disk. The event may thus be delivered quicker than before, however, there exists a small chance that the entire transaction will be lost if the OS crashes or there is a loss of system power before the data is flushed to disk. Since such catastrophic events are rare, most consumers should not need to concern themselves further.

+ +
+

Note: In Firefox, if you wish to ensure durability for some reason (e.g. you're storing critical data that cannot be recomputed later) you can force a transaction to flush to disk before delivering the complete event by creating a transaction using the experimental (non-standard) readwriteflush mode (see {{domxref("IDBDatabase.transaction")}}.) This is currently experimental, and can only be used if the dom.indexedDB.experimental pref is set to true in about:config.

+
+
+
object store
+
+

The mechanism by which data is stored in the database. The object store persistently holds records, which are key-value pairs. Records within an object store are sorted according to the keys in an ascending order.

+ +

Every object store must have a name that is unique within its database. The object store can optionally have a key generator and a key path. If the object store has a key path, it is using in-line keys; otherwise, it is using out-of-line keys.

+ +

For the reference documentation on object store, see IDBObjectStore or IDBObjectStoreSync.

+
+
version
+
When a database is first created, its version is the integer 1. Each database has one version at a time; a database can't exist in multiple versions at once. The only way to change the version is by opening it with a greater version than the current one. This will start a versionchange transaction and fire an upgradeneeded event. The only place where the schema of the database can be updated is inside the handler of that event.
+
Note: This definition describes the most recent specification, which is only implemented in up-to-date browsers. Old browsers implemented the now deprecated and removed IDBDatabase.setVersion() method.
+
database connection
+
An operation created by opening a database. A given database can have multiple connections at the same time.
+
transaction
+
+

An atomic set of data-access and data-modification operations on a particular database. It is how you interact with the data in a database. In fact, any reading or changing of data in the database must happen in a transaction.

+ +

A database connection can have several active transaction associated with it at a time, so long as the writing transactions do not have overlapping scopes. The scope of transactions, which is defined at creation, determines which object stores the transaction can interact with and remains constant for the lifetime of the transaction. So, for example, if a database connection already has a writing transaction with a scope that just covers the flyingMonkey object store, you can start a second transaction with a scope of the unicornCentaur and unicornPegasus object stores. As for reading transactions, you can have several of them — even overlapping ones.

+ +

Transactions are expected to be short-lived, so the browser can terminate a transaction that takes too long, in order to free up storage resources that the long-running transaction has locked. You can abort the transaction, which rolls back the changes made to the database in the transaction. And you don't even have to wait for the transaction to start or be active to abort it.

+ +

The three modes of transactions are: readwrite, readonly, and versionchange. The only way to create and delete object stores and indexes is by using a versionchange transaction. To learn more about transaction types, see the reference article for IndexedDB.

+ +

Because everything happens within a transaction, it is a very important concept in IndexedDB. To learn more about transactions, especially on how they relate to versioning, see IDBTransaction, which also has reference documentation. For the documentation on the synchronous API, see IDBTransactionSync.

+
+
request
+
The operation by which reading and writing on a database is done. Every request represents one read or write operation.
+
index
+
+

An index is a specialized object store for looking up records in another object store, called the referenced object store. The index is a persistent key-value storage where the value part of its records is the key part of a record in the referenced object store. The records in an index are automatically populated whenever records in the referenced object store are inserted, updated, or deleted. Each record in an index can point to only one record in its referenced object store, but several indexes can reference the same object store. When the object store changes, all indexes that refer to the object store are automatically updated.

+ +

Alternatively, you can also look up records in an object store using the key.

+ +

To learn more on using indexes, see Using IndexedDB. For the reference documentation on index, see IDBKeyRange.

+
+
+ +

Chave e valor

+ +
+
key
+
+

A data value by which stored values are organized and retrieved in the object store. The object store can derive the key from one of three sources: a key generator, a key path, or an explicitly specified value. The key must be of a data type that has a number that is greater than the one before it. Each record in an object store must have a key that is unique within the same store, so you cannot have multiple records with the same key in a given object store.

+ +

A key can be one of the following types: string, date, float, a binary blob, and array. For arrays, the key can range from an empty value to infinity. And you can include an array within an array.

+ +

Alternatively, you can also look up records in an object store using the index.

+
+
key generator
+
A mechanism for producing new keys in an ordered sequence. If an object store does not have a key generator, then the application must provide keys for records being stored. Generators are not shared between stores. This is more a browser implementation detail, because in web development, you don't really create or access key generators.
+
in-line key
+
A key that is stored as part of the stored value. It is found using a key path. An in-line key can be generated using a generator. After the key has been generated, it can then be stored in the value using the key path or it can also be used as a key.
+
out-of-line key
+
A key that is stored separately from the value being stored.
+
key path
+
Defines where the browser should extract the key from in the object store or index. A valid key path can include one of the following: an empty string, a JavaScript identifier, or multiple JavaScript identifiers separated by periods or an array containing any of those. It cannot include spaces.
+
value
+
+

Each record has a value, which could include anything that can be expressed in JavaScript, including boolean, number, string, date, object, array, regexp, undefined, and null.

+ +

When an object or array is stored, the properties and values in that object or array can also be anything that is a valid value.

+ +

Blobs and files can be stored, cf. specification {{ fx_minversion_inline("11") }}.

+
+
+ +

Intervalo e escopo

+ +
+
scope
+
The set of object stores and indexes to which a transaction applies. The scopes of read-only transactions can overlap and execute at the same time. On the other hand, the scopes of writing transactions cannot overlap. You can still start several transactions with the same scope at the same time, but they just queue up and execute one after another.
+
cursor
+
A mechanism for iterating over multiple records with a key range. The cursor has a source that indicates which index or object store it is iterating. It has a position within the range, and moves in a direction that is increasing or decreasing in the order of record keys. For the reference documentation on cursors, see IDBCursor or IDBCursorSync.
+
key range
+
+

A continuous interval over some data type used for keys. Records can be retrieved from object stores and indexes using keys or a range of keys. You can limit or filter the range using lower and upper bounds. For example, you can iterate over all values of a key between x and y.

+ +

For the reference documentation on key range, see IDBKeyRange.

+
+
+ +

Limitações

+ +

IndexedDB is designed to cover most cases that need client-side storage. However, it is not designed for a few cases like the following:

+ + + +

In addition, be aware that browsers can wipe out the database, such as in the following conditions:

+ + + +

The exact circumstances and browser capabilities change over time, but the general philosophy of the browser vendors is to make the best effort to keep the data when possible.

+ +

Próximos passos

+ +

With these big concepts under our belts, we can get to more concrete stuff. For a tutorial on how to use the API, see Using IndexedDB.

+ +

See also

+ +

Especificação

+ + + +

Referência

+ + + +

Tutoriais

+ + + +

Artigo relacionado

+ + diff --git a/files/pt-br/web/api/indexeddb_api/index.html b/files/pt-br/web/api/indexeddb_api/index.html new file mode 100644 index 0000000000..06e84254f2 --- /dev/null +++ b/files/pt-br/web/api/indexeddb_api/index.html @@ -0,0 +1,167 @@ +--- +title: IndexedDB +slug: Web/API/IndexedDB_API +translation_of: Web/API/IndexedDB_API +--- +
+

IndexedDB é uma API para armazenamento client-side de quantidades significantes de informações e buscas com alta performance por índices. Enquanto DOM Storage é útil para armazenamento de pequenas quantidade de dados, IndexedDB é a solução para grande porção de dados estruturados.

+
+ +

Esta página basicamente é o ponto de entrada para uma descrição técnica dos objetos da API. Precisando de suporte ainda mais inicial consulte os Conceitos Básicos sobre IndexedDb. Para mais detalhes sobre a implementação, veja Usando IndexedDB.
+
+ IndexedDB provém APIs separadas para acesso tanto síncrono quanto assíncrono. As APIs síncronas devem ser utilizadas apenas dentro de Web Workers, apesar de não ser implementada por nenhum navegador atualmente. A API assíncrona funciona tanto com ou sem Web Workers, sendo que o Firefox ainda não implementou este.

+ +

API Assíncrona

+ +

Os métodos da API assíncrona são chamados sem bloquear a thread que os chama. Para obter acesso assíncrono à database, chame open() no atributo indexedDB do objeto window, que retornará um objeto {{domxref("IDBRequest")}}. Operações assíncronas comunicam-se com a aplicação que os chamam executando eventos nos objetos {{domxref("IDBRequest")}}.

+ +
+

Nota: O objeto indexedDB é prefixado em navegadores mais antigos (propriedade mozIndexedDB em Gecko < 16, webkitIndexedDb em Chrome e msIndexedDB no IE 10).

+
+ +

As interfaces da API assíncrona do IndexedDB são:

+ +
+
{{domxref("IDBFactory")}}
+
Provém acesso ao banco de dados. É a interface implementado pelo objeto global indexedDB e é, portanto, o ponto de entrada para API.
+
{{domxref("IDBCursor")}}
+
Itera sobre objectStores e índices
+
{{domxref("IDBCursorWithValue")}}
+
Itera sobre objectStores e índices e retorna o atual valor do cursor
+
{{domxref("IDBDatabase")}}
+
Represents a connection to a database. It's the only way to get a transaction on the database.
+
{{domxref("IDBEnvironment")}}
+
Provides access to a client-side database. It is implemented by the {{ domxref("window") }} and {{ domxref("worker") }} objects.
+
{{domxref("IDBIndex")}}
+
Provides access to the metadata of an index.
+
{{domxref("IDBKeyRange")}}
+
Define um alcance das chaves.
+
{{domxref("IDBObjectStore")}}
+
Representa um ObjectStore
+
{{domxref("IDBOpenDBRequest")}}
+
Representa uma requisição para abrir o banco de dados.
+
{{domxref("IDBRequest")}}
+
Provém acesso a resultados de requisições assíncronas ao banco de dados e a objetos do banco de dados. É o que você obtém quando chama um método assíncrono.
+
{{domxref("IDBTransaction")}}
+
Representa uma transação. Você cria a transação no banco de dados, especifíca o escopo (tal como qual objectStore você deseja acessar), e determina que tipo de acesso (apenas leitura ou também escrita) daquilo que você deseja.
+
+ + + +

Uma versão anterior da especificação também define estas interfaces agora removidas. Elas ainda estão documentadas caso você precise atualizar códigos escritos anteriormente:

+ +
+
{{domxref("IDBVersionChangeRequest")}}
+
Representa uma requisição para alterar a versão do banco de dados. O modo de alterar a versão do banco de dados mudou então (chamando IDBFactory.open sem também chamar IDBDatabase.setVersion) e a interface IDBOpenDBRequest agora tem a funcionalidade do removido IDBVersionChangeRequest.
+
{{domxref("IDBDatabaseException")}}  {{ obsolete_inline() }}
+
Representa condições de erro que podem ser encontradas enquanto performando operações no banco de dados.
+
+ + + +
+

 Nota: há também a versão síncrona da API. A versão síncrona não tem implementação em qualquer navegador. É feita para ser utilizada com WebWorkers.

+
+ +

Limites de Armazenamento

+ +

Não há qualquer limite em um único elemento da database. Entretanto podem haver limites quanto ao tamanho de cada banco de dados. Este limite (e a maneira com qual o usuário chega a ele) pode variar de um navegador para outro:

+ + + +

Exemplos

+ + + +

Compatibilidade dos navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
API Assíncrona +

11.0 {{ property_prefix("webkit") }}
+ 24

+
{{ CompatGeckoDesktop("2.0") }} {{ property_prefix("moz") }}
+ {{ CompatGeckoDesktop("16.0") }}
101711.1
API Síncrona (com WebWorkers){{ CompatNo() }}{{ CompatNo() }}
+ See {{ bug(701634) }}
{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
API Assíncrona4.4{{ CompatGeckoDesktop("6.0") }} {{ property_prefix("moz") }}
+ {{ CompatGeckoDesktop("16.0") }}
101710.3
+
+ +
+

Nota: alguns browsers ainda não suportam IndexedDB mas suportam WebSQL, mais especificamente Safari/Webkit no desktop e iOS. Uma maneira de driblar este problema é utilizar IndexedDB Polyfill ou Shim, que recorre ao WebSQL para navegadores que não suportam.

+
+ +

Veja Também

+ + diff --git a/files/pt-br/web/api/indexeddb_api/usando_indexeddb/index.html b/files/pt-br/web/api/indexeddb_api/usando_indexeddb/index.html new file mode 100644 index 0000000000..da14879b31 --- /dev/null +++ b/files/pt-br/web/api/indexeddb_api/usando_indexeddb/index.html @@ -0,0 +1,1281 @@ +--- +title: Usando IndexedDB +slug: Web/API/IndexedDB_API/Usando_IndexedDB +tags: + - API IndexedDB Tutorial Avançado +translation_of: Web/API/IndexedDB_API/Using_IndexedDB +--- +
+

IndexedDB é uma forma de armazenar dados no navegador do usuário. Com ele você pode criar aplicações web com possibilidade de fazer query sem necessidade de conexão, suas aplicações podem funcionar tanto online quanto offline. 

+
+ +

Sobre esse documento

+ +

Esse tutorial utiliza a API assíncrona do IndexedDB. Se você não está familiarizado com IndexedDB, você pode ler Conceitos básicos sobre IndexedDB.

+ +

Para a documentação de referência, veja o artigo sobre API IndexedDB, pois nele contém os tipos de objetos utilizados no IndexedDB,  como também métodos da API, tanto síncrona como assíncrona. 

+ +

Padrão básico

+ +

O IndexedDB encoraja o uso do seguinte padrão:

+ +
    +
  1. Abrir um banco de dados.
  2. +
  3. Criar um ObjectStore ao atualizar o banco. 
  4. +
  5. Iniciar uma transação e e faz um request para fazer alguma operação no banco, como adicionar ou obter dados.
  6. +
  7. +
    Esperar a operação ser completada ouvindo algum evento DOM.
    +
  8. +
  9. +
    Fazer algo com o resultado da query (que pode ser obtida pelo objeto request).
    +
  10. +
+ +

OK, então, agora com esses conceitos em mente, nós podemos fazer coisas mais concretas.

+ +

Criando e estruturando o banco

+ +

Pelo fato  da especificação ainda estar evoluindo, as implementações do IndexedDB tem prefixos de navegadores. Os navegadores podem ter implementações diferentes da API IndexedDB até a especificação ser consolidada. Mas uma vez que tudo chegar a um consenso, os navegadores tirarão seus prefixos. Atualmente, algumas implementações removeram o prefixo: Internet Explorer 10, Firefox 16, Chrome 24. Quando eles usam prefixo, navegadores baseados no Gecko usam o prefixo moz, enquanto os navegadores baseados no WebKit usam o prefixo webkit.

+ +

Usando uma versão experimental do IndexedDB

+ +

Se você quiser testar seu código em navegadores que usam prefixo, você pode usar o código abaixo:  

+ +
// Na linha abaixo, você deve incluir os prefixos do navegador que você vai testar.
+window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
+// Não use "var indexedDB = ..." se você não está numa function.
+// Posteriormente, você pode precisar de referências de algum objeto window.IDB*:
+window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction;
+window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange;
+// (Mozilla nunca usou prefixo nesses objetos, então não precisamos window.mozIDB*)
+ +

Tome cuidado, implementações prefixadas podem estar com bugs ou implementando especificações antigas. Portanto, não é recomendado usar em produção. É preferível não usar IndexedDB em navegadores antigos:

+ +
if (!window.indexedDB) {
+    window.alert("Seu navegador não suporta uma versão estável do IndexedDB. Alguns recursos não estarão disponíveis.");
+}
+
+ +

Abrindo um banco

+ +

Começamos todo o processo assim:

+ +
// Abrindo o banco de dados
+var request = window.indexedDB.open("DBteste", 3);
+
+ +

Abrir um banco é como qualquer outra operação — Você tem que "requerer (request)".

+ +

A requisição de abertura não abre o banco ou inicia a transação. A chamada da função open() retorna um objeto IDBOpenDBRequest com o resultado (success) ou um erro que você terá que tratar. Muitas outras funções assíncronas no IndexedDB fazem a mesma coisa - retornam um objeto IDBRequest com o resultado ou erro. O resultado para a função open é uma instância de IDBDatabase.

+ +

O segundo parâmetro para o método open é a versão do banco. A versão do banco determina seu schema — os registros no banco e sua estrutura. Se o banco não existe ainda, ele é criado pela operação open, então o evento onupgradeneeded é chamado e você cria o schema do banco nesse evento. Se o banco existe mas você está fornecendo um novo número de versão, o evento onupgradeneeded é chamado imediatamente, permitindo você tratar a atualização do schema. Para mais informações sobre isso veja Updating the version of the database.

+ +
+

O número de versão é um unsigned long long, o que significa que ele pode ver um inteiro muito grande. Isso também significa que você não pode usar float, pois ele será convertido em um inteiro pequeno e a transação pode não acontecer, ou o evento upgradeneeded pode não ser chamado. Então se você usar 2.4 como versão:

+ +
var request = indexedDB.open("DBteste", 2.4); // não faça isso, pois a versão será convertida para 2.
+
+ +

Gerenciando handlers

+ +

A primeira coisa que você vai querer fazer em quase todos os requests é tratar os casos de success e error:

+ +
request.onerror = function(event) {
+  // Fazer algo com request.errorCode!
+};
+request.onsuccess = function(event) {
+  // Fazer algo com request.result!
+};
+ +

Qual das duas funções, onsuccess() ou onerror(),  será chamada? Se tudo correr bem, o evento de sucesso (que é um evento DOM event com propriedade type setada "success") é chamado com request como seu target. Uma vez chamado, a função onsuccess() no request é chamada com o evento de sucesso em seu contexto. Por outro lado, se acontecer algum problema, um evento de erro (que é um evento DOM com a propriedade type setada para "error") é chamado no request. Então a função onerror()  com o evento erro em seu contexto.

+ +

A API IndexedDB é feita para minimizar a necessidade de manipular erros, então você não fará muitos eventos de erro (ao menos, se você usar a API!) No  caso de abrir um banco, portanto, existe algumas condições comuns para eventos de erro. O problema mais comum é o usuário não dar permissão para criar o banco. Um dos principais objetivos do IndexedDB é permitir muitos dados serem armazenados para uso offline. (Para aprender mais sobre o quanto cada navegador pode armazenar, veja Storage limits).  

+ +

Obviamente, navegadores não querem armazenar dados que poluem seu computador, então o navegador mostra uma mensagem ao usuário na primeira vez que um aplicativo tenta abrir o IndexedDB. O usuário pode escolher permitir ou negar acesso. O IndexedDB também é desabilitado no modo privado dos navegadores (ctrl+shift+N no Chrome e ctrl+shift+P no Firefox). Isso acontece porque o intuito do modo privado é não deixar rastros na navegação.

+ +

Agora, assumindo que o usuário aprovou seu request para criar o banco, e você recebeu success; Qual é o próximo passo? O request foi gerado com a chamada de indexedDB.open(), e request.result é uma instância de IDBDatabase, e você definitivamente vai querer armazenar isso para usar depois. Veja abaixo:

+ +
var db;
+var request = indexedDB.open("DBteste");
+request.onerror = function(event) {
+  alert("Você não habilitou minha web app para usar IndexedDB?!");
+};
+request.onsuccess = function(event) {
+  db = request.result;
+};
+
+ +

Tratando Erros

+ +

Como mencionado acima, o evento de erro é chamado quando o request dá erro. Se você quer evitar manipuladores de erro a cada request, você pode adicionar um único manipulador de erro no objeto db, como abaixo:

+ +
db.onerror = function(event) {
+  // Função genérica para tratar os erros de todos os requests desse banco!
+  alert("Database error: " + event.target.errorCode);
+};
+
+ +

Um dos erros mais comuns ao abrir o banco é VER_ERR. Ele indica que a versão do banco existente é maior que a versão que você quer abrir.

+ +

Criando ou atualizando a versão do banco

+ +

Quando você cria um novo banco ou aumenta sua versão, o evento onupgradeneeded será chamado. No manipulador deste evento, você deve criar o objectStore necessário para a versão do banco:

+ +
// Este evento é implementado somente em navegadores mais recentes
+request.onupgradeneeded = function(event) {
+  var db = event.target.result;
+
+  // cria um objectStore para esse banco
+  var objectStore = db.createObjectStore("nome", { keyPath: "minhaChave" });
+};
+ +

Neste caso, o banco já terá objectStores de suas versões anteriores, então você não terá que criar esses objectStores de novo. Você somente precisará criar um novo objectStore qualquer, ou deletar objectStores da versão anterior que não serão utilizados. Se você precisa mudar um objectStore existente (mudar o keyPath, por exemplo),  então você precisa deletar o objectStore antigo e criá-lo novamente com as novas opções. (Note que isso irá deletar a informação no objectStore! Se você precisa salvar a informação, você deve ler isso e salvá-lo em algum lugar antes de atualizar o banco.)

+ +

Blink/Webkit suporta a versão atual da especificação, nas versões do Chrome 23+ e Opera 17+; IE10+ também suporta. Outros motores e versões antigas não implementam a versão atual da especificação e não suportam a assinatura indexedDB.open(name, version).onupgradeneeded ainda.  Para mais informação sobre como atualizar a versão do banco em Webkit/Blink, veja IDBDatabase reference article.

+ +

Estruturando o banco

+ +

Agora a estrutura do banco. IndexedDB usa "armazens de objetos" em vez de tabelas, e um único banco de dados pode conter qualquer número de "armazem de objetos". Sempre que um valor é armazenado num objectStore, ele é associado a uma chave. Existe várias maneiras diferentes de uma chave ser mostrada, dependendo do que o objectStore usa, um key path ou key generator.

+ +

A tabela abaixo mostra as direfentes chaves suportadas:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Key Path (keyPath)Key Generator (autoIncrement)Description
NãoNãoEste objectStore pode ter qualquer tipo de valor primitivo como número ou string. Você deve suprir uma chave separada sempre que adicionar um novo valor.
SimNãoEste objectStore pode simplesmente armazenar objetos JavaScript. O objeto deve ter uma propriedade com o mesmo nome do key path.
NãoSimEste objectStore pode possuir qualquer tipo de valor. A chave é gerada para você, automaticamente, ou você pode suprir uma chave separada, caso utilize uma chave específica.
SimSimEste objectStore suporta somente objetos JavaScript. Normalmente uma chave é gerada e o valor dela é armazenado no objeto em uma propriedade com o mesmo nome da key path. Portanto, se a propriedade já existe, o valor dela será usado como chave, em vez do valor gerado.
+ +

Você também pode criar índices em qualquer objectStore. Um indice deixa você olhar os valores armazenados no objectStore usando o valor de uma propriedade do objectStore, em vez de sua chave.

+ +

Adicionalmente, indices tem a habilidade de forçar restrições simples nos dados armazenados. Setando uma flag única quando criar o índice, reforça que dois objetos são armazenados contendo o mesmo valor para o key path do índice. Então, por exemplo, se você tem um objeto armazenado que tem um conjunto de pessoas, e você quer ter certeza que ninguém tera o mesmo e-mail, você pode usar um índice com flag única para forçar isso.

+ +

Isso soa meio confuso, mas este exemplo pode iluminar o conceito. Primeiro, vamos definir alguns dados a serem usados no exemplo:

+ +
// Isso é o que os dados de nossos clientes será.
+const DadosClientes = [
+  { ssn: "444-44-4444", nome: "Bill", idade: 35, email: "bill@company.com" },
+  { ssn: "555-55-5555", nome: "Donna", idade: 32, email: "donna@home.org" }
+];
+
+ +

Agora  vamos ver  ccomo criar um IndexedDB para armazenar nossos dados:

+ +
const dbName = "clientes";
+
+var request = indexedDB.open(dbName, 2);
+
+request.onerror = function(event) {
+  // Tratar erros.
+};
+request.onupgradeneeded = function(event) {
+  var db = event.target.result;
+
+  // Cria um objectStore para conter a informação sobre nossos clientes. Nós vamos
+  // usar "ssn" como key path porque sabemos que é único;
+  var objectStore = db.createObjectStore("clientes", { keyPath: "ssn" });
+
+  // Cria um índice para buscar clientes pelo nome. Podemos ter nomes
+  // duplicados, então não podemos usar como índice único.
+  objectStore.createIndex("nome", "nome", { unique: false });
+
+  // Cria um índice para buscar clientes por email. Queremos ter certeza
+  // que não teremos 2 clientes com o mesmo e-mail;
+  objectStore.createIndex("email", "email", { unique: true });
+
+  // Usando transação oncomplete para afirmar que a criação do objectStore
+  // é terminada antes de adicionar algum dado nele.
+  objectStore.transaction.oncomplete = function(event) {
+    // Armazenando valores no novo objectStore.
+    var clientesObjectStore = db.transaction("clientes", "readwrite").objectStore("clientes");
+    for (var i in DadosClientes) {
+      clientesObjectStore.add(DadosClientes[i]);
+    }
+  }
+};
+
+ +

Como falamos antes, onupgradeneeded é o único lugar onde você pode alterar a estrutura do banco. Nele você pode criar e deletar objectStores e construir ou remover índices.

+ +
Armazens de objetos são criados com uma única chamada de createObjectStore(). O método pega o nome do armazem e um objeto parâmetro. Mesmo que o objeto parâmetro seja opcional, ele é muito importante porque ele deixa você definir propriedades importantes e ajustar tipos de dados que você quer criar. No nosso caso, nós obtemos um objectStore chamado "clientes" e definimos um keyPath, que é a propriedade que faz um objeto individual ser único no banco. Essa propriedade, nesse exemplo, é "ssn", que simboliza o cpf (social security number), que é único. O "ssn" deve ser apresentado em cada objeto armazenado no objectStore
+ +

Nós também criamos um índice chamado "nome" ligado à propriedade nome. Assim como o createObjectStore(), o createIndex() tem um parâmetro opcional options que cuida do tipo de índice que você quer criar. Adicionando objetos que não tem a propriedade nome terá sucesso, porém esses objetos não aparecerão no índice "nome".

+ +

Nós podemos obter os objetos de clientes armazenados usando os ssn da objectStore diretamente, ou usando os nomes usados no índice. Para aprender como isso é feito, veja a seção usando um índice.

+ +

Usando um key generator

+ +

Setando uma flag autoIncrement ao criar o objectStore habilitará o key generator. Por padrão ele não é setado.

+ +

Com o key generator, a chave será gerada automaticamente quando você adicionar algum valor no objectStore. O atual número do key generator é sempre setado 1 quando a primeira key generator do objectStore é criada. Basicamente a próxima chave recebe o incremento de 1. O número atual da key generator nunca decresce,  a não ser se alguma operação do banco for revertida, como numa transação abortada, por exemplo. No entanto, deletar um registro ou limpar todos os registros nunca afeta o key generator dos objectStores.

+ +

Nós podemos criar outro objectStore com o key generator como abaixo:

+ +
// Abrindo o indexedDB.
+var request = indexedDB.open(dbName, 3);
+
+request.onupgradeneeded = function (event) {
+
+    var db = event.target.result;
+
+    // Criando outro objeto chamado "names" com o autoIncrement setado.
+    var objStore = db.createObjectStore("names", { autoIncrement : true });
+
+    // Porque "names" tem o the key generator, a chave para o nome é gerada automaticamente.
+    // Os registros adicionados serão assim:
+    // key : 1 => value : "Bill"
+    // key : 2 => value : "Donna"
+    for (var i in DadosClientes) {
+        objStore.add(DadosClientes[i].nome);
+    }
+}
+ +

Para mais detalhes veja "W3C Key Generators".

+ +

Adicionando, obtendo e removendo dados

+ +

Antes de fazer qualquer coisa em um novo banco, você precisa iniciar uma transação. Transações estão no objeto database, e você tem que especificar qual objectStore você quer na transaction. Uma vez que você está dentro da transação, você pode acessar os objectStores  com seus dados e fazer os requests. Depois, você precisa decidir se você vai fazer mudanças no banco ou se você simplesmente quer ler esses dados. Transações tem três modos disponíveis: readonly, readwrite, and versionchange.

+ +

Para mudar o "schema" ou estrutura do banco — o que envolve criar ou deletar objectStores ou índices — a transação deve ser em modo versionchange. Esta transação é aberta chamando o método {{domxref("IDBFactory.open")}} especificando a  version. (Em navegadores com WebKit que não tem a ultima especificação implementada, o método {{domxref("IDBFactory.open")}} tem apenas um parâmetro, o nome do banco; então você deve chamar {{domxref("IDBVersionChangeRequest.setVersion")}} para estabelecer uma transação versionchange.)

+ +

Para ler os registros de um objectStore existente, a transação pode ser tanto readonly quanto readwrite. Para fazer mudanças em um objectStore existente, a transação deve ser em modo readwrite. Você abre essas transações usando {{domxref("IDBDatabase.transaction")}}. O método aceita dois parâmetros: o storeNames (o escopo, definido como um array de objectStores que você quer acessar) e o modo (readonly or readwrite) da transação. O método retorna o objeto detransação contendo o método {{domxref("IDBIndex.objectStore")}}, que você pode usar para acessar seu objectStore. Por padrão, quando nenhum modo é especificado, a transação é aberta no modo readonly.

+ +

Você pode deixar o acesso aos dados mais rápido usando o escopo correto e o modo correto de transação. Aqui vai algumas dicas:

+ + + +

Adicionando dados no banco

+ +

Se você acabou de criar o banco, então você provavelmente quer escrever algo nele. Veja abaixo:

+ +
var transaction = db.transaction(["clientes"], "readwrite");
+// Nota: Implementações mais antigas usam uma versão IDBTransaction.READ_WRITE antiga em vez de "readwrite".
+// Então, para suportar versões antigas, escreva:
+// var transaction = db.transaction(["clientes"], IDBTransaction.READ_WRITE);
+ +

A função transaction() tem dois argumentos (opcionais) e retorna um objeto de transação. O primeiro argumento é uma lista de objectStores que serão trabalhados na transação. Você pode passar um array vazio se você quer uma transação com todos os objectStores, mas não faça isso pois a especificação diz que um array vazio pode gerar um erro InvalidAccessError. Se você não especificar nada no segundo parâmetro, você tem uma transação read-only. Se você quer escrever no banco, use "readwrite".

+ +

Agora que você tem uma transação, você precisa entender seu tempo de uso. Transações são amarradas a um evento. Se você faz uma transação fora de um evento, ela ficará inativa. A única maneira de manter uma transação ativa é fazer um request nela. Quando o request acabar você terá a oportunidade de extender a transação durante o callback. Se você tentar extender uma transação dentro de um evento, então ela tornará inativa. Se existir requests pendentes, a transação continua ativa. O tempo de vida de uma transação é realmente simples mas deve ser usada em um curto espaço de tempo. Outros exemplos poderão ajudá-lo. Se você começar a ver TRANSACTION_INACTIVE_ERR error então você está fazendo algo errado.

+ +

Transações podem receber eventos DOM de três tipos diferentes: error, abort, e complete. Nós falamos sobre o error, ou seja, a transação recebe um error sempre que o request gerar erro. Um ponto mais sutil é que o comportamento padrão de um erro é abortar a transação na qual ele estava. A menos que você manipule o erro chamando preventDefault() e fazendo algo depois, a transaçaõ inteira será desfeita. Este design força você a pensar sobre manipulação de erros, mas você pode sempre adicionar um manipulador de todos os erros se a manipulação separada estiver complicada. Se você não tratar o erro ou chamar abort() na transação, então a transação é desfeita (roll back) e o evento abort é chamado. Por outro lado, depois de todo request completado, você tem um evento complete. Se você fazer várias operações no banco, então seguir as operações de transações pode ser um caminho a seguir.

+ +

Agora que você tem uma transação, você precisará obter um objectStore dela. Transações somente deixam você obter um objectStore citado na transação. Então você pode adicionar os dados que precisa.

+ +
// Faz algo após a inserção dos dados.
+transaction.oncomplete = function(event) {
+  alert("Pronto!");
+};
+
+transaction.onerror = function(event) {
+  // Não esquecer de tratar os erros!
+};
+
+var objectStore = transaction.objectStore("clientes");
+for (var i in DadosClientes) {
+  var request = objectStore.add(DadosClientes[i]);
+  request.onsuccess = function(event) {
+    // event.target.result == DadosClientes[i].ssn;
+  };
+}
+ +

O result de um request gerado de uma chamada de add() é a chave do valor  que foi adicionado. Então neste caso, ele deve ser igual ao valor do ssn do objeto que foi adicionado, desde que o objeto use o ssn como key path. Note que a função add() não deixa nenhum objeto ser adicionado com a mesma chave. Se você está tentando modificar um registro existente, você deve usar o put(), como explica a seção  {{ anch("Updating an entry in the database") }}.

+ +

Removendo dados do banco

+ +

Para remoção o código é parecido:

+ +
var request = db.transaction(["clientes"], "readwrite")
+                .objectStore("clientes")
+                .delete("444-44-4444");
+request.onsuccess = function(event) {
+  // Pronto!
+};
+ +

Obtendo dados do banco

+ +

Agora que o banco tem algumas informações nele, você pode obtê-las de diferentes maneiras. Primeiro, um get() simples. Você precisa informar a chave do valor a ser obtido:

+ +
var transaction = db.transaction(["clientes"]);
+var objectStore = transaction.objectStore("clientes");
+var request = objectStore.get("444-44-4444");
+request.onerror = function(event) {
+  // Tratar erro!
+};
+request.onsuccess = function(event) {
+  // Fazer algo com request.result!
+  alert("O nome do SSN 444-44-4444 é " + request.result.name);
+};
+ +

Veja agora de maneira resumida:

+ +
db.transaction("clientes").objectStore("clientes").get("444-44-4444").onsuccess = function(event) {
+  alert("O nome do SSN 444-44-4444 é " + request.result.name);
+};
+ +

Viu como funciona? Desde que exista um objectStore, você pode evitar passar uma lista de objectStores que precisa na transação e passar apenas o nome como string. Você também pode ler do banco, apenas, então não precisará de uma transação "readwrite". Chamando transaction() com nenhum modo especificado, você terá uma transação "readonly". Outra consideração é que você não necessita salvar o request em uma variável. Desde que o evento DOM tenha o target que você precisará para obter a propriedade result.

+ +
+

Note: Você pode deixar o acesso aos dados mais rápido limitando o escopo e o modo de transação. Veja algumas dicas:

+ + +
+ +

Atualizando um registro no banco

+ +

Agora que obtemos algum dado, atualizá-ls é inserí-los novamente no IndexedDB é bem simples. Vamos atualizar o exemplo anterior:

+ +
var objectStore = db.transaction(["clientes"], "readwrite").objectStore("clientes");
+var request = objectStore.get("444-44-4444");
+request.onerror = function(event) {
+  // Tratar erro
+};
+request.onsuccess = function(event) {
+  // Obter os valores antigos
+  var data = request.result;
+
+  // atualizar algum dado
+  data.age = 42;
+
+  // Atulizar esse dado no banco
+  var requestUpdate = objectStore.put(data);
+   requestUpdate.onerror = function(event) {
+     // Tratar erro
+   };
+   requestUpdate.onsuccess = function(event) {
+     // Sucesso na atualização \o/
+   };
+};
+ +

Criamos uma objectStore e obtemos um cliente dele, identificado pelo ssn (444-44-4444). Nós atualizamos o objeto, passando-o como parâmetro de um método put de outro request (requestUpdate) sobrescrevendo o valor antigo.

+ +
+

Note que neste caso nós temos que especificar a transação readwrite porque nós queremos escrever no banco, não somente ler os dados dele.

+
+ +

Usando um cursor

+ +

Ao usar o método get() você precisa saber a chave do objeto que deseja obter. Se você quer passear entre todos os valores do seu objectStore, então você pode usar um cursor. Veja:

+ +
var objectStore = db.transaction("cliente").objectStore("cliente");
+
+objectStore.openCursor().onsuccess = function(event) {
+  var cursor = event.target.result;
+  if (cursor) {
+    alert("O nome do SSN " + cursor.key + " é " + cursor.value.name);
+    cursor.continue();
+  }
+  else {
+    alert("Não existe mais registros!");
+  }
+};
+ +

A função openCursor() tem vários argumentos. Primeiro, você pode limitar o número de itens obtidos usando uma chave que veremos logo abaixo. Segundo, você pode especificar a direção que deseja iterar. No exemplo acima, nós estamos iterando em todos os objetos em ordem ascendente. O callback de sucesso para cursor é um pouco especial. O objeto cursor já é o result do request (acima nós usamos event.target.result). Então a chave atual e o valor pode ser encontrado na propriedade key e value do objeto cursor. Se você quer manter adiante, então você usa o método continue(). Quando você chegar ao fim dos dados (ou se não existem registros encontrados no openCursor()) você ainda tem um callback de sucesso, mas a propriedade result fica undefined.

+ +

Um padrão comum para cursores é obter todos os objetos em um objectStore e adicioná-los a um array como este:

+ +
var clientes = [];
+
+objectStore.openCursor().onsuccess = function(event) {
+  var cursor = event.target.result;
+  if (cursor) {
+    clientes.push(cursor.value);
+    cursor.continue();
+  }
+  else {
+    alert("Todos os clientes: " + clientes);
+  }
+};
+ +
+

Note: Mozilla também implementou o método getAll() para ser usado nesse caso (e getAllKeys(), que está atualmente dentro da preferência do dom.indexedDB.experimental em about:config). Estes métodos não são parte do padrão IndexedDB, então eles podem desaparecer no futuro. Nós adicionamos porque achamos útil. O código abaixo faz o mesmo que o código acima:

+ +
objectStore.getAll().onsuccess = function(event) {
+  alert("Todos os clientes: " + event.target.result);
+};
+ +

Existe um custo de performance associado com a propriedade value do cursor, porque o objeto é criado de forma lenta. Quando você usa getAll() por exemplo, Gecko deve criar todos os objetos de uma vez. Se você está somente interessado em cada chave, é muito melhor usar o cursor do que usar o getAll(). Se você está tentando obter um array de todos os objetos, então é melhor usar o getAll().

+
+ +

Usando um índice

+ +

Armazenar dados de um cliente usando o SSN como chave é lógico pois o SSN identifica o cliente de forma única. Se você precisa obter um cliente pelo seu nome, portanto, você precisará iterar todos os registros no banco e comparar os nomes até achar o que você procura. Buscar dessa maneira é algo lento, então criamos um índice.

+ +
var index = objectStore.index("nome");
+index.get("John").onsuccess = function(event) {
+  alert("O SSN de John é " + event.target.result.ssn);
+};
+ +

O cursor "nome" não é único, então pode existir mais de um registro com o nome igual a "John". Neste caso você sempre obtem o registro com a chave de menor valor.

+ +

Se você precisa acessar todos os registros retornados, você pode usar um cursor. Você pode abrir dois tipos de cursores. Um cursor normal mapeia o índice ao objeto na objectStore. Uma cursor-chave mapeia o a propriedade índice à chave usada para armazenar o objeto. As diferenças são ilustradas abaixo:

+ +
// Usando um cursor normal para obter todos os objetos
+index.openCursor().onsuccess = function(event) {
+  var cursor = event.target.result;
+  if (cursor) {
+    // cursor.key é um nome, como "Bill", e cursor.value é o objeto inteiro.
+    alert("Nome: " + cursor.key + ", SSN: " + cursor.value.ssn + ", email: " + cursor.value.email);
+    cursor.continue();
+  }
+};
+
+// Usando um cursor-chave para obter todos os objetos
+index.openKeyCursor().onsuccess = function(event) {
+  var cursor = event.target.result;
+  if (cursor) {
+    // cursor.key é o nome, como "Bill", e cursor.value é o SSN (chave).
+    // Não tem como obter o resto do objeto
+    alert("Nome: " + cursor.key + ", SSN: " + cursor.value);
+    cursor.continue();
+  }
+};
+ +

Especificando o número e a direção dos cursores

+ +

Se você gostaria de limitar o número de valores retornados pelo cursor, você pode usar um objeto IDBKeyRange e passar isso como o primeiro argumento ao openCursor() ou openKeyCursor(). Você pode fazer um key range que permite um único valor, ou valores acima ou abaixo do especificado. O limite pode ser fechado (o key range inclui os valores dados) ou aberto (o key range não inclue os valores dados). Veja como funciona:

+ +
// Somente se for igual "Donna"
+var singleKeyRange = IDBKeyRange.only("Donna");
+
+// Combinações menores que "Bill", incluindo "Bill"
+var lowerBoundKeyRange = IDBKeyRange.lowerBound("Bill");
+
+// Combinações menores que "Bill", sem incluir "Bill"
+var lowerBoundOpenKeyRange = IDBKeyRange.lowerBound("Bill", true);
+
+// Combinações maiores que Donna, não incluindo "Donna"
+var upperBoundOpenKeyRange = IDBKeyRange.upperBound("Donna", true);
+
+// Combinações entre "Bill" e "Donna", sem incluir "Donna"
+var boundKeyRange = IDBKeyRange.bound("Bill", "Donna", false, true);
+
+// Para usar qualquer um desses key ranges, basta passar como primeiro parâmetro de openCursor()/openKeyCursor()
+index.openCursor(boundKeyRange).onsuccess = function(event) {
+  var cursor = event.target.result;
+  if (cursor) {
+    // Faz algo com o que encontrar
+    cursor.continue();
+  }
+};
+ +

As vezes você pode querer iterar em ordem decrescente, em vez de crescente, alterando o segundo parâmetro de openCursor():

+ +
objectStore.openCursor(boundKeyRange, "prev").onsuccess = function(event) {
+  var cursor = event.target.result;
+  if (cursor) {
+    // Prev indica ordem decrescente
+    cursor.continue();
+  }
+};
+ +

Se você apenas quer especificar a ordem sem key range, é só passar null no primeiro parâmetro:

+ +
objectStore.openCursor(null, "prev").onsuccess = function(event) {
+  var cursor = event.target.result;
+  if (cursor) {
+    // Faça algo com os resultados.
+    cursor.continue();
+  }
+};
+ +

Uma vez que o índice "nome" não é único, pode existir várias entradas onde o nome é o mesmo. Isso não acontece com objectStores porque a chave deve ser sempre única. Se você deseja filtrar valores duplicados numa iteração do cursor, você pode passar nextunique (ou prevunique se quiser decrescer) como parâmetro de direção. Quando nextunique ou prevunique é usado, o registro com menor chave é retornado.

+ +
index.openKeyCursor(null, "nextunique").onsuccess = function(event) {
+  var cursor = event.target.result;
+  if (cursor) {
+    // Faça algo com os registros.
+    cursor.continue();
+  }
+};
+ +

Veja "IDBCursor Constants" para parâmetros válidos.

+ +

Mudança de versão quando a web app está aberta em outra aba.

+ +

Quando sua web app muda a versão você precisa considerar o que vai acontecer se o usuário está na versão antiga em uma aba, e carrega a versão nova na outra. Quando você chamar o open() com a versão mais nova, um evento onblocked  é chamado até que a aba da versão antiga seja fechada ou recarregada. Veja abaixo:

+ +
var openReq = mozIndexedDB.open("DBteste", 2);
+
+openReq.onblocked = function(event) {
+  // Se existe outra aba com a versão antiga
+  alert("Existe uma versão antiga da web app aberta em outra aba, feche-a por favor!");
+};
+
+openReq.onupgradeneeded = function(event) {
+  // Se estiver tudo fechado, então faça as devidas alterações
+  db.createObjectStore(/* ... */);
+  useDatabase(db);
+}
+
+openReq.onsuccess = function(event) {
+  var db = event.target.result;
+  useDatabase(db);
+  return;
+}
+
+function useDatabase(db) {
+  // Esteja certo de que adicionou um evento para notificar se a página muda a versão
+  // Nós devemos fechar o banco. Isso permite à outra página ser atualizada
+  // Se você não fizer isso a atualização não acontecerá até fechar as abas.
+  db.onversionchange = function(event) {
+    db.close();
+    alert("Uma nova versão desta web app está pronta. Atualiza, por favor!");
+  };
+
+  // Fazer algo com os bancos
+}
+
+ +

Segurança

+ +

IndexedDB usa o princípio de mesma origem, o que significa que o banco só será acessado pelo site que o criou.

+ +

É importante notar que o IndexedDB não funciona para conteúdo carregado em um frame de outro site (seja {{ HTMLElement("frame") }} ou {{ HTMLElement("iframe") }}. Esta é uma política de segurança e privacidade análoga ao bloqueio de cookies de terceiros. Para mais detalhes, veja {{ bug(595307) }}.

+ +

Alerta sobre fechar o navegador

+ +

Quando o navegador é fechado, qualquer transação pendente no IndexedDB será abortada (silenciosamente) — ele não vai completar, nem chamar o evento de erro.  Uma vez que o usuário pode sair do navegador, em qualquer momento, isto significa que você não pode confiar em qualquer transação específica para completar ou para saber que ela não foi concluída. Existem várias implicações nesse comportamento.

+ +

Primeiro, você deve ter o cuidado de sempre deixar seu banco de dados em um estado consistente, no final de cada transação. Por exemplo, suponha que você está usando IndexedDB para armazenar uma lista de itens que permitem ao usuário editar. Você salvar a lista após a edição, limpando o armazenamento de objetos e, em seguida, escrever a nova lista. Se você limpar o armazenamento de objetos em uma transação e escrever a nova lista em outra transação, há um perigo de que o navegador irá fechar após a limpeza de dados e antes da gravação, deixando-o com um banco de dados vazio. Para evitar isso, você deve combinar tanto a limpeza quanto a gravação em uma única transação.

+ +

Em segundo lugar, você nunca deve amarrar as operações de banco de dados ao evento unload. Se o evento unload é acionado pelo fechamento do navegador, todas as transações criadas no unload nunca serão concluídas. Uma abordagem intuitiva para manter algumas informações em sessões do navegador é lê-la a partir do banco de dados quando o navegador (ou uma determinada página) é aberta, atualizá-la assim que o usuário interagir com o navegador, e depois salvá-lo para o banco de dados quando o navegador (ou página) será fechada. No entanto, isso não vai funcionar. As transações de banco de dados será criado no unload, mas como elas são assíncronasserão abortadas antes que eles possam executar.

+ +

De fato, não existe uma maneira de garantir que as transações no IndexedDBserão completadas, mesmo com o fechamento padrão do navegador. Ver {{ bug(870645) }}.

+ +

Exemplo de IndexedDB

+ +

HTML

+ +
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
+
+    <h1>IndexedDB Demo: storing blobs, e-publication example</h1>
+    <div class="note">
+      <p>
+        Works and tested with:
+      </p>
+      <div id="compat">
+      </div>
+    </div>
+
+    <div id="msg">
+    </div>
+
+    <form id="register-form">
+      <table>
+        <tbody>
+          <tr>
+            <td>
+              <label for="pub-title" class="required">
+                Title:
+              </label>
+            </td>
+            <td>
+              <input type="text" id="pub-title" name="pub-title" />
+            </td>
+          </tr>
+          <tr>
+            <td>
+              <label for="pub-biblioid" class="required">
+                Bibliographic ID:<br/>
+                <span class="note">(ISBN, ISSN, etc.)</span>
+              </label>
+            </td>
+            <td>
+              <input type="text" id="pub-biblioid" name="pub-biblioid"/>
+            </td>
+          </tr>
+          <tr>
+            <td>
+              <label for="pub-year">
+                Year:
+              </label>
+            </td>
+            <td>
+              <input type="number" id="pub-year" name="pub-year" />
+            </td>
+          </tr>
+        </tbody>
+        <tbody>
+          <tr>
+            <td>
+              <label for="pub-file">
+                File image:
+              </label>
+            </td>
+            <td>
+              <input type="file" id="pub-file"/>
+            </td>
+          </tr>
+          <tr>
+            <td>
+              <label for="pub-file-url">
+                Online-file image URL:<br/>
+                <span class="note">(same origin URL)</span>
+              </label>
+            </td>
+            <td>
+              <input type="text" id="pub-file-url" name="pub-file-url"/>
+            </td>
+          </tr>
+        </tbody>
+      </table>
+
+      <div class="button-pane">
+        <input type="button" id="add-button" value="Add Publication" />
+        <input type="reset" id="register-form-reset"/>
+      </div>
+    </form>
+
+    <form id="delete-form">
+      <table>
+        <tbody>
+          <tr>
+            <td>
+              <label for="pub-biblioid-to-delete">
+                Bibliographic ID:<br/>
+                <span class="note">(ISBN, ISSN, etc.)</span>
+              </label>
+            </td>
+            <td>
+              <input type="text" id="pub-biblioid-to-delete"
+                     name="pub-biblioid-to-delete" />
+            </td>
+          </tr>
+          <tr>
+            <td>
+              <label for="key-to-delete">
+                Key:<br/>
+                <span class="note">(for example 1, 2, 3, etc.)</span>
+              </label>
+            </td>
+            <td>
+              <input type="text" id="key-to-delete"
+                     name="key-to-delete" />
+            </td>
+          </tr>
+        </tbody>
+      </table>
+      <div class="button-pane">
+        <input type="button" id="delete-button" value="Delete Publication" />
+        <input type="button" id="clear-store-button"
+               value="Clear the whole store" class="destructive" />
+      </div>
+    </form>
+
+    <form id="search-form">
+      <div class="button-pane">
+        <input type="button" id="search-list-button"
+               value="List database content" />
+      </div>
+    </form>
+
+    <div>
+      <div id="pub-msg">
+      </div>
+      <div id="pub-viewer">
+      </div>
+      <ul id="pub-list">
+      </ul>
+    </div>
+
+ +

CSS Content

+ +
body {
+  font-size: 0.8em;
+  font-family: Sans-Serif;
+}
+
+form {
+  background-color: #cccccc;
+  border-radius: 0.3em;
+  display: inline-block;
+  margin-bottom: 0.5em;
+  padding: 1em;
+}
+
+table {
+  border-collapse: collapse;
+}
+
+input {
+  padding: 0.3em;
+  border-color: #cccccc;
+  border-radius: 0.3em;
+}
+
+.required:after {
+  content: "*";
+  color: red;
+}
+
+.button-pane {
+  margin-top: 1em;
+}
+
+#pub-viewer {
+  float: right;
+  width: 48%;
+  height: 20em;
+  border: solid #d092ff 0.1em;
+}
+#pub-viewer iframe {
+  width: 100%;
+  height: 100%;
+}
+
+#pub-list {
+  width: 46%;
+  background-color: #eeeeee;
+  border-radius: 0.3em;
+}
+#pub-list li {
+  padding-top: 0.5em;
+  padding-bottom: 0.5em;
+  padding-right: 0.5em;
+}
+
+#msg {
+  margin-bottom: 1em;
+}
+
+.action-success {
+  padding: 0.5em;
+  color: #00d21e;
+  background-color: #eeeeee;
+  border-radius: 0.2em;
+}
+
+.action-failure {
+  padding: 0.5em;
+  color: #ff1408;
+  background-color: #eeeeee;
+  border-radius: 0.2em;
+}
+
+.note {
+  font-size: smaller;
+}
+
+.destructive {
+  background-color: orange;
+}
+.destructive:hover {
+  background-color: #ff8000;
+}
+.destructive:active {
+  background-color: red;
+}
+
+ +

 

+ +

JavaScript Content

+ +
(function () {
+  var COMPAT_ENVS = [
+    ['Firefox', ">= 16.0"],
+    ['Google Chrome',
+     ">= 24.0 (you may need to get Google Chrome Canary), NO Blob storage support"]
+  ];
+  var compat = $('#compat');
+  compat.empty();
+  compat.append('<ul id="compat-list"></ul>');
+  COMPAT_ENVS.forEach(function(val, idx, array) {
+    $('#compat-list').append('<li>' + val[0] + ': ' + val[1] + '</li>');
+  });
+
+  const DB_NAME = 'mdn-demo-indexeddb-epublications';
+  const DB_VERSION = 1; // Use a long long for this value (don't use a float)
+  const DB_STORE_NAME = 'publications';
+
+  var db;
+
+  // Used to keep track of which view is displayed to avoid uselessly reloading it
+  var current_view_pub_key;
+
+  function openDb() {
+    console.log("openDb ...");
+    var req = indexedDB.open(DB_NAME, DB_VERSION);
+    req.onsuccess = function (evt) {
+      // Better use "this" than "req" to get the result to avoid problems with
+      // garbage collection.
+      // db = req.result;
+      db = this.result;
+      console.log("openDb DONE");
+    };
+    req.onerror = function (evt) {
+      console.error("openDb:", evt.target.errorCode);
+    };
+
+    req.onupgradeneeded = function (evt) {
+      console.log("openDb.onupgradeneeded");
+      var store = evt.currentTarget.result.createObjectStore(
+        DB_STORE_NAME, { keyPath: 'id', autoIncrement: true });
+
+      store.createIndex('biblioid', 'biblioid', { unique: true });
+      store.createIndex('title', 'title', { unique: false });
+      store.createIndex('year', 'year', { unique: false });
+    };
+  }
+
+  /**
+   * @param {string} store_name
+   * @param {string} mode either "readonly" or "readwrite"
+   */
+  function getObjectStore(store_name, mode) {
+    var tx = db.transaction(store_name, mode);
+    return tx.objectStore(store_name);
+  }
+
+  function clearObjectStore(store_name) {
+    var store = getObjectStore(DB_STORE_NAME, 'readwrite');
+    var req = store.clear();
+    req.onsuccess = function(evt) {
+      displayActionSuccess("Store cleared");
+      displayPubList(store);
+    };
+    req.onerror = function (evt) {
+      console.error("clearObjectStore:", evt.target.errorCode);
+      displayActionFailure(this.error);
+    };
+  }
+
+  function getBlob(key, store, success_callback) {
+    var req = store.get(key);
+    req.onsuccess = function(evt) {
+      var value = evt.target.result;
+      if (value)
+        success_callback(value.blob);
+    };
+  }
+
+  /**
+   * @param {IDBObjectStore=} store
+   */
+  function displayPubList(store) {
+    console.log("displayPubList");
+
+    if (typeof store == 'undefined')
+      store = getObjectStore(DB_STORE_NAME, 'readonly');
+
+    var pub_msg = $('#pub-msg');
+    pub_msg.empty();
+    var pub_list = $('#pub-list');
+    pub_list.empty();
+    // Resetting the iframe so that it doesn't display previous content
+    newViewerFrame();
+
+    var req;
+    req = store.count();
+    // Requests are executed in the order in which they were made against the
+    // transaction, and their results are returned in the same order.
+    // Thus the count text below will be displayed before the actual pub list
+    // (not that it is algorithmically important in this case).
+    req.onsuccess = function(evt) {
+      pub_msg.append('<p>There are <strong>' + evt.target.result +
+                     '</strong> record(s) in the object store.</p>');
+    };
+    req.onerror = function(evt) {
+      console.error("add error", this.error);
+      displayActionFailure(this.error);
+    };
+
+    var i = 0;
+    req = store.openCursor();
+    req.onsuccess = function(evt) {
+      var cursor = evt.target.result;
+
+      // If the cursor is pointing at something, ask for the data
+      if (cursor) {
+        console.log("displayPubList cursor:", cursor);
+        req = store.get(cursor.key);
+        req.onsuccess = function (evt) {
+          var value = evt.target.result;
+          var list_item = $('<li>' +
+                            '[' + cursor.key + '] ' +
+                            '(biblioid: ' + value.biblioid + ') ' +
+                            value.title +
+                            '</li>');
+          if (value.year != null)
+            list_item.append(' - ' + value.year);
+
+          if (value.hasOwnProperty('blob') &&
+              typeof value.blob != 'undefined') {
+            var link = $('<a href="' + cursor.key + '">File</a>');
+            link.on('click', function() { return false; });
+            link.on('mouseenter', function(evt) {
+                      setInViewer(evt.target.getAttribute('href')); });
+            list_item.append(' / ');
+            list_item.append(link);
+          } else {
+            list_item.append(" / No attached file");
+          }
+          pub_list.append(list_item);
+        };
+
+        // Move on to the next object in store
+        cursor.continue();
+
+        // This counter serves only to create distinct ids
+        i++;
+      } else {
+        console.log("No more entries");
+      }
+    };
+  }
+
+  function newViewerFrame() {
+    var viewer = $('#pub-viewer');
+    viewer.empty();
+    var iframe = $('<iframe />');
+    viewer.append(iframe);
+    return iframe;
+  }
+
+  function setInViewer(key) {
+    console.log("setInViewer:", arguments);
+    key = Number(key);
+    if (key == current_view_pub_key)
+      return;
+
+    current_view_pub_key = key;
+
+    var store = getObjectStore(DB_STORE_NAME, 'readonly');
+    getBlob(key, store, function(blob) {
+      console.log("setInViewer blob:", blob);
+      var iframe = newViewerFrame();
+
+      // It is not possible to set a direct link to the
+      // blob to provide a mean to directly download it.
+      if (blob.type == 'text/html') {
+        var reader = new FileReader();
+        reader.onload = (function(evt) {
+          var html = evt.target.result;
+          iframe.load(function() {
+            $(this).contents().find('html').html(html);
+          });
+        });
+        reader.readAsText(blob);
+      } else if (blob.type.indexOf('image/') == 0) {
+        iframe.load(function() {
+          var img_id = 'image-' + key;
+          var img = $('<img id="' + img_id + '"/>');
+          $(this).contents().find('body').html(img);
+          var obj_url = window.URL.createObjectURL(blob);
+          $(this).contents().find('#' + img_id).attr('src', obj_url);
+          window.URL.revokeObjectURL(obj_url);
+        });
+      } else if (blob.type == 'application/pdf') {
+        $('*').css('cursor', 'wait');
+        var obj_url = window.URL.createObjectURL(blob);
+        iframe.load(function() {
+          $('*').css('cursor', 'auto');
+        });
+        iframe.attr('src', obj_url);
+        window.URL.revokeObjectURL(obj_url);
+      } else {
+        iframe.load(function() {
+          $(this).contents().find('body').html("No view available");
+        });
+      }
+
+    });
+  }
+
+  /**
+   * @param {string} biblioid
+   * @param {string} title
+   * @param {number} year
+   * @param {string} url the URL of the image to download and store in the local
+   *   IndexedDB database. The resource behind this URL is subjected to the
+   *   "Same origin policy", thus for this method to work, the URL must come from
+   *   the same origin as the web site/app this code is deployed on.
+   */
+  function addPublicationFromUrl(biblioid, title, year, url) {
+    console.log("addPublicationFromUrl:", arguments);
+
+    var xhr = new XMLHttpRequest();
+    xhr.open('GET', url, true);
+    // Setting the wanted responseType to "blob"
+    // http://www.w3.org/TR/XMLHttpRequest2/#the-response-attribute
+    xhr.responseType = 'blob';
+    xhr.onload = function (evt) {
+                           if (xhr.status == 200) {
+                             console.log("Blob retrieved");
+                             var blob = xhr.response;
+                             console.log("Blob:", blob);
+                             addPublication(biblioid, title, year, blob);
+                           } else {
+                             console.error("addPublicationFromUrl error:",
+                                           xhr.responseText, xhr.status);
+                           }
+                         };
+    xhr.send();
+
+    // We can't use jQuery here because as of jQuery 1.8.3 the new "blob"
+    // responseType is not handled.
+    // http://bugs.jquery.com/ticket/11461
+    // http://bugs.jquery.com/ticket/7248
+    // $.ajax({
+    //   url: url,
+    //   type: 'GET',
+    //   xhrFields: { responseType: 'blob' },
+    //   success: function(data, textStatus, jqXHR) {
+    //     console.log("Blob retrieved");
+    //     console.log("Blob:", data);
+    //     // addPublication(biblioid, title, year, data);
+    //   },
+    //   error: function(jqXHR, textStatus, errorThrown) {
+    //     console.error(errorThrown);
+    //     displayActionFailure("Error during blob retrieval");
+    //   }
+    // });
+  }
+
+  /**
+   * @param {string} biblioid
+   * @param {string} title
+   * @param {number} year
+   * @param {Blob=} blob
+   */
+  function addPublication(biblioid, title, year, blob) {
+    console.log("addPublication arguments:", arguments);
+    var obj = { biblioid: biblioid, title: title, year: year };
+    if (typeof blob != 'undefined')
+      obj.blob = blob;
+
+    var store = getObjectStore(DB_STORE_NAME, 'readwrite');
+    var req;
+    try {
+      req = store.add(obj);
+    } catch (e) {
+      if (e.name == 'DataCloneError')
+        displayActionFailure("This engine doesn't know how to clone a Blob, " +
+                             "use Firefox");
+      throw e;
+    }
+    req.onsuccess = function (evt) {
+      console.log("Insertion in DB successful");
+      displayActionSuccess();
+      displayPubList(store);
+    };
+    req.onerror = function() {
+      console.error("addPublication error", this.error);
+      displayActionFailure(this.error);
+    };
+  }
+
+  /**
+   * @param {string} biblioid
+   */
+  function deletePublicationFromBib(biblioid) {
+    console.log("deletePublication:", arguments);
+    var store = getObjectStore(DB_STORE_NAME, 'readwrite');
+    var req = store.index('biblioid');
+    req.get(biblioid).onsuccess = function(evt) {
+      if (typeof evt.target.result == 'undefined') {
+        displayActionFailure("No matching record found");
+        return;
+      }
+      deletePublication(evt.target.result.id, store);
+    };
+    req.onerror = function (evt) {
+      console.error("deletePublicationFromBib:", evt.target.errorCode);
+    };
+  }
+
+  /**
+   * @param {number} key
+   * @param {IDBObjectStore=} store
+   */
+  function deletePublication(key, store) {
+    console.log("deletePublication:", arguments);
+
+    if (typeof store == 'undefined')
+      store = getObjectStore(DB_STORE_NAME, 'readwrite');
+
+    // As per spec http://www.w3.org/TR/IndexedDB/#object-store-deletion-operation
+    // the result of the Object Store Deletion Operation algorithm is
+    // undefined, so it's not possible to know if some records were actually
+    // deleted by looking at the request result.
+    var req = store.get(key);
+    req.onsuccess = function(evt) {
+      var record = evt.target.result;
+      console.log("record:", record);
+      if (typeof record == 'undefined') {
+        displayActionFailure("No matching record found");
+        return;
+      }
+      // Warning: The exact same key used for creation needs to be passed for
+      // the deletion. If the key was a Number for creation, then it needs to
+      // be a Number for deletion.
+      req = store.delete(key);
+      req.onsuccess = function(evt) {
+        console.log("evt:", evt);
+        console.log("evt.target:", evt.target);
+        console.log("evt.target.result:", evt.target.result);
+        console.log("delete successful");
+        displayActionSuccess("Deletion successful");
+        displayPubList(store);
+      };
+      req.onerror = function (evt) {
+        console.error("deletePublication:", evt.target.errorCode);
+      };
+    };
+    req.onerror = function (evt) {
+      console.error("deletePublication:", evt.target.errorCode);
+      };
+  }
+
+  function displayActionSuccess(msg) {
+    msg = typeof msg != 'undefined' ? "Success: " + msg : "Success";
+    $('#msg').html('<span class="action-success">' + msg + '</span>');
+  }
+  function displayActionFailure(msg) {
+    msg = typeof msg != 'undefined' ? "Failure: " + msg : "Failure";
+    $('#msg').html('<span class="action-failure">' + msg + '</span>');
+  }
+  function resetActionStatus() {
+    console.log("resetActionStatus ...");
+    $('#msg').empty();
+    console.log("resetActionStatus DONE");
+  }
+
+  function addEventListeners() {
+    console.log("addEventListeners");
+
+    $('#register-form-reset').click(function(evt) {
+      resetActionStatus();
+    });
+
+    $('#add-button').click(function(evt) {
+      console.log("add ...");
+      var title = $('#pub-title').val();
+      var biblioid = $('#pub-biblioid').val();
+      if (!title || !biblioid) {
+        displayActionFailure("Required field(s) missing");
+        return;
+      }
+      var year = $('#pub-year').val();
+      if (year != '') {
+        // Better use Number.isInteger if the engine has EcmaScript 6
+        if (isNaN(year))  {
+          displayActionFailure("Invalid year");
+          return;
+        }
+        year = Number(year);
+      } else {
+        year = null;
+      }
+
+      var file_input = $('#pub-file');
+      var selected_file = file_input.get(0).files[0];
+      console.log("selected_file:", selected_file);
+      // Keeping a reference on how to reset the file input in the UI once we
+      // have its value, but instead of doing that we rather use a "reset" type
+      // input in the HTML form.
+      //file_input.val(null);
+      var file_url = $('#pub-file-url').val();
+      if (selected_file) {
+        addPublication(biblioid, title, year, selected_file);
+      } else if (file_url) {
+        addPublicationFromUrl(biblioid, title, year, file_url);
+      } else {
+        addPublication(biblioid, title, year);
+      }
+
+    });
+
+    $('#delete-button').click(function(evt) {
+      console.log("delete ...");
+      var biblioid = $('#pub-biblioid-to-delete').val();
+      var key = $('#key-to-delete').val();
+
+      if (biblioid != '') {
+        deletePublicationFromBib(biblioid);
+      } else if (key != '') {
+        // Better use Number.isInteger if the engine has EcmaScript 6
+        if (key == '' || isNaN(key))  {
+          displayActionFailure("Invalid key");
+          return;
+        }
+        key = Number(key);
+        deletePublication(key);
+      }
+    });
+
+    $('#clear-store-button').click(function(evt) {
+      clearObjectStore();
+    });
+
+    var search_button = $('#search-list-button');
+    search_button.click(function(evt) {
+      displayPubList();
+    });
+
+  }
+
+  openDb();
+  addEventListeners();
+
+})(); // Immediately-Invoked Function Expression (IIFE)
+
+ +

{{ LiveSampleLink('Full_IndexedDB_example', "Test the online live demo") }}

+ +

Ver também

+ +

Uma leitura adicional para você encontrar mais informações.

+ +

Refências

+ + + +

Guias e tutoriais

+ + diff --git a/files/pt-br/web/api/keyboardevent/index.html b/files/pt-br/web/api/keyboardevent/index.html new file mode 100644 index 0000000000..d552857d3f --- /dev/null +++ b/files/pt-br/web/api/keyboardevent/index.html @@ -0,0 +1,439 @@ +--- +title: KeyboardEvent +slug: Web/API/KeyboardEvent +tags: + - API + - DOM + - Evento + - Inteface + - Referencia +translation_of: Web/API/KeyboardEvent +--- +

{{APIRef("DOM Events")}}

+ +

Objetos do tipo KeyboardEvent descrevem a interação do usuário com o teclado. Cada evento descreve uma tecla; o tipo de evento (keydown, keypress, ou keyup) identifica qual tipo de ação foi executada.

+ +
Note: O KeyboardEvent indica o que está havendo com a tecla. Quando você precisar lidar com entrada de texto, use o evento input do HTML5  . Por exemplo, se o usuário envia texto por meio de um sistema manuscrito como um tablet PC, eventos das teclas podem não ser disparados.
+ +

Construtor

+ +
+
{{domxref("KeyboardEvent.KeyboardEvent", "KeyboardEvent()")}}
+
Cria um objeto do tipo KeyboardEvent.
+
+ +

Métodos

+ +

Essa interface também herda métodos dos seus pais, {{domxref("UIEvent")}} e {{domxref("Event")}}.

+ +
+
{{domxref("KeyboardEvent.getModifierState()")}}
+
Retorna um {{jsxref("Boolean")}} indicando se uma tecla, como AltShiftCtrl, ou Meta, foi pressionada quando o evento foi criado.
+
{{domxref("KeyboardEvent.initKeyEvent()")}}{{deprecated_inline}}
+
Inicializa um objeto do tipo KeyboardEvent . isso foi apenas implementado por Gecko (outros usaram {{domxref("KeyboardEvent.initKeyboardEvent()")}}) e não deve mais ser usado. A forma moderna padrão é usar o construtor {{domxref("KeyboardEvent.KeyboardEvent", "KeyboardEvent()")}}.
+
{{domxref("KeyboardEvent.initKeyboardEvent()")}}{{deprecated_inline}}
+
Inicializa um objeto do tipo KeyboardEvent . Isso nunca foi implementado por Gecko (que usou {{domxref("KeyboardEvent.initKeyEvent()")}}) e não deve mais ser usado. A forma moderna padrão é usar o construtor  {{domxref("KeyboardEvent.KeyboardEvent", "KeyboardEvent()")}}.
+
+ +

Propriedades

+ +

Essa interface também herda métodos dos seus pais, {{domxref("UIEvent")}} e {{domxref("Event")}}.

+ +
+
{{domxref("KeyboardEvent.altKey")}} {{Readonlyinline}}
+
Retorna um {{jsxref("Boolean")}} que é true se a tecla Alt ( Option ou  no OS X) estava ativa quando o evento foi acionado.
+
{{domxref("KeyboardEvent.char")}} {{Non-standard_inline}}{{Deprecated_inline}}{{Readonlyinline}}
+
Retorna um {{domxref("DOMString")}} representando o valor da tecla em caractere. Se a tecla corresponde a um caractere exibível, esse valor é uma string Unicode não-vazia contendo aquele caractere. Se a tecla não possui uma representação exibível, ela é uma string vazia. +
Nota: Se a tecla é usada como um macro que insere caracteres múltiplos, o valor desse atributo é a string inteira, não apenas o primeiro caractere.
+ +
Aviso: Isso foi removido dos Eventos DOM de nível 3. Isso é apenas suportado no IE.
+
+
{{domxref("KeyboardEvent.charCode")}} {{Deprecated_inline}}{{Readonlyinline}}
+
Returns a {{jsxref("Number")}} representing the Unicode reference number of the key; this attribute is used only by the keypress event. For keys whose char attribute contains multiple characters, this is the Unicode value of the first character in that attribute. In Firefox 26 this returns codes for printable characters. +
Aviso: Este atributo esta depreciado; você deve usar key no lugar, se disponivel.
+
+
{{domxref("KeyboardEvent.code")}} {{Readonlyinline}}
+
Returns a {{domxref("DOMString")}} with the code value of the key represented by the event.
+
{{domxref("KeyboardEvent.ctrlKey")}} {{Readonlyinline}}
+
Returns a {{jsxref("Boolean")}} that is true if the Ctrl key was active when the key event was generated.
+
{{domxref("KeyboardEvent.isComposing")}} {{Readonlyinline}}
+
Returns a {{jsxref("Boolean")}} that is true if the event is fired between after compositionstart and before compositionend.
+
{{domxref("KeyboardEvent.key")}} {{Readonlyinline}}
+
Returns a {{domxref("DOMString")}} representing the key value of the key represented by the event.
+
{{domxref("KeyboardEvent.keyCode")}} {{deprecated_inline}}{{Readonlyinline}}
+
Returns a {{jsxref("Number")}} representing a system and implementation dependent numerical code identifying the unmodified value of the pressed key. +
Aviso: Este atributo esta depreciado; você deve usar key no lugar, se disponivel.
+
+
{{domxref("KeyboardEvent.locale")}} {{Readonlyinline}}
+
Returns a {{domxref("DOMString")}} representing a locale string indicating the locale the keyboard is configured for. This may be the empty string if the browser or device doesn't know the keyboard's locale. +
Note: This does not describe the locale of the data being entered. A user may be using one keyboard layout while typing text in a different language.
+
+
{{domxref("KeyboardEvent.location")}} {{Readonlyinline}}
+
Returns a {{jsxref("Number")}} representing the location of the key on the keyboard or other input device.
+
{{domxref("KeyboardEvent.metaKey")}} {{Readonlyinline}}
+
Returns a {{jsxref("Boolean")}} that is true if the Meta (or Command on OS X) key was active when the key event was generated.
+
{{domxref("KeyboardEvent.repeat")}} {{Readonlyinline}}
+
Returns a {{jsxref("Boolean")}} that is true if the key is being held down such that it is automatically repeating.
+
{{domxref("KeyboardEvent.shiftKey")}} {{Readonlyinline}}
+
Returns a {{jsxref("Boolean")}} that is true if the Shift key was active when the key event was generated.
+
{{domxref("KeyboardEvent.which")}} {{deprecated_inline}}{{Readonlyinline}}
+
Returns a {{jsxref("Number")}} representing a system and implementation dependent numeric code identifying the unmodified value of the pressed key; this is usually the same as keyCode. +
Aviso: Este atributo esta depreciado; você deve usar key no lugar, se disponivel.
+
+
+ +

Notes

+ +

There are keydown, keypress, and keyup events. For most keys, Gecko dispatches a sequence of key events like this:

+ +
    +
  1. When the key is first depressed, the keydown event is sent.
  2. +
  3. If the key is not a modifier key, the keypress event is sent.
  4. +
  5. When the user releases the key, the keyup event is sent.
  6. +
+ +

Special cases

+ +

Certain keys toggle the state of an LED indicator, such as Caps Lock, Num Lock, and Scroll Lock. On Windows and Linux, these keys dispatch only the keydown and keyup events. Note that on Linux, Firefox 12 and earlier also dispatched the keypress event for these keys.

+ +

On Mac, however, Caps Lock dispatches only the keydown event due to a platform event model limitation. Num Lock had been supported on old MacBook (2007 model and older) but Mac hasn't supported Num Lock feature even on external keyboards in these days. On the old MacBook which has Num Lock key, Num Lock doesn't cause any key events. And Gecko supports Scroll Lock key if an external keyboard which has F14 is connected. However, it generates keypress event. This inconsistent behavior is a bug; see {{bug(602812)}}.

+ +

Auto-repeat handling

+ +

When a key is pressed and held down, it begins to auto-repeat. This results in a sequence of events similar to the following being dispatched:

+ +
    +
  1. keydown
  2. +
  3. keypress
  4. +
  5. <<repeating until the user releases the key>>
  6. +
  7. keyup
  8. +
+ +

This is what the DOM Level 3 specification says should happen. There are some caveats, however, as described below.

+ +

Auto-repeat on some GTK environments such as Ubuntu 9.4

+ +

In some GTK-based environments, auto-repeat dispatches a native key-up event automatically during auto-repeat, and there's no way for Gecko to know the difference between a repeated series of keypresses and an auto-repeat. On those platforms, then, an auto-repeat key will generate the following sequence of events:

+ +
    +
  1. keydown
  2. +
  3. keypress
  4. +
  5. <<repeating until the user releases the key>>
  6. +
  7. keyup
  8. +
+ +

In these environments, unfortunately, there's no way for web content to tell the difference between auto-repeating keys and keys that are just being pressed repeatedly.

+ +

Auto-repeat handling prior to Gecko 4.0

+ +

Before Gecko 4.0 {{geckoRelease('4.0')}}, keyboard handling was less consistent across platforms.

+ +
+
Windows
+
Auto-repeat behavior is the same as in Gecko 4.0 and later.
+
Mac
+
After the initial keydown event, only keypress events are sent until the keyup event occurs; the inter-spaced keydown events are not sent.
+
Linux
+
The event behavior depends on the specific platform. It will either behave like Windows or Mac depending on what the native event model does.
+
+ +

Example

+ +
<!DOCTYPE html>
+<html>
+<head>
+<script>
+var metaChar = false;
+var exampleKey = 16;
+
+function keyEvent(event) {
+  var key = event.keyCode || event.which;
+  var keychar = String.fromCharCode(key);
+  if (key == exampleKey) {
+    metaChar = true;
+  }
+  if (key != exampleKey) {
+    if (metaChar) {
+      alert("Combination of metaKey + " + keychar);
+      metaChar = false;
+    } else {
+      alert("Key pressed " + key);
+    }
+  }
+}
+
+function metaKeyUp (event) {
+  var key = event.keyCode || event.which;
+
+  if (key == exampleKey) {
+    metaChar = false;
+  }
+}
+</script>
+</head>
+
+<body onkeydown="keyEvent(event)" onkeyup="metaKeyUp(event)">
+</body>
+</html>
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM3 Events', '#interface-KeyboardEvent', 'KeyboardEvent')}}{{Spec2('DOM3 Events')}}Initial definition.
+ +

The KeyboardEvent interface specification went through numerous draft versions, first under DOM Events Level 2 where it was dropped as no consensus arose, then under DOM Events Level 3. This led to the implementation of non-standard initialization methods, the early DOM Events Level 2 version, {{domxref("KeyboardEvent.initKeyEvent()")}} by Gecko browsers and the early DOM Events Level 3 version, {{domxref("KeyboardEvent.initKeyboardEvent()")}} by others. Both have been superseded by the modern usage of a constructor: {{domxref("KeyboardEvent.KeyboardEvent", "KeyboardEvent()")}}.

+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
constructor{{CompatVersionUnknown}}{{CompatGeckoDesktop("31.0")}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatUnknown}}
.char{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}
.charCode{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
.codeSee Browser compatibility of {{domxref("KeyboardEvent.code")}}.
.isComposing{{CompatNo}}{{CompatGeckoDesktop("31.0")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
.keySee Browser compatibility of {{domxref("KeyboardEvent.key")}}.
.keyCode{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
.locale{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}
.location{{CompatVersionUnknown}}{{CompatGeckoDesktop("15.0")}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}
.repeat{{CompatVersionUnknown}}{{CompatGeckoDesktop("28.0")}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}
.which{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
.getModifierState()See Browser compatibility of {{domxref("KeyboardEvent.getModifierState")}}
.initKeyboardEvent(){{CompatVersionUnknown}}[1]{{CompatNo}}[2]{{CompatIE("9.0")}}[3]{{CompatUnknown}}{{CompatVersionUnknown}}[1]
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
constructor{{CompatUnknown}}{{CompatGeckoMobile("31.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
.char{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
.charCode{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
.codeSee Browser compatibility of {{domxref("KeyboardEvent.code")}}.
.isComposing{{CompatNo}}{{CompatGeckoMobile("31.0")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
.keySee Browser compatibility table of {{domxref("KeyboardEvent.key")}}.
.keyCode{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
.locale{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
.location{{CompatUnknown}}{{CompatGeckoMobile("15.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
.repeat{{CompatUnknown}}{{CompatGeckoMobile("28.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
.which{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
.getModifierState()See Browser compatibility of {{domxref("KeyboardEvent.getModifierState")}}
.initKeyboardEvent(){{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] The arguments of initKeyboardEvent() of WebKit and Blink's are different from the definition in DOM Level 3 Events. The method is: initKeyboardEvent(in DOMString typeArg, in boolean canBubbleArg, in boolean cancelableArg, in views::AbstractView viewArg, in DOMString keyIndentifierArg, in number locationArg, in boolean ctrlKeyArg, in boolean altKeyArg, in boolean shiftKeyArg, in boolean metaKeyArg, in boolean altGraphKeyArg)

+ +

[2] Gecko won't support initKeyboardEvent() because supporting it completely breaks feature detection of web applications. See {{Bug(999645)}}.

+ +

[3] The argument of initKeyboardEvent() of IE is different from the definition in DOM Level 3 Events. The method is: initKeyboardEvent(in DOMString typeArg, in boolean canBubbleArg, in boolean cancelableArg, in views::AbstractView viewArg, in DOMString keyArg, in number locationArg, in DOMString modifierListArg, in boolean repeatArt, in DOMString locationArg). See document of initKeyboardEvent() in MSDN.

+ +

[4] Note that manually firing an event does not generate the default action associated with that event. For example, manually firing a key event does not cause that letter to appear in a focused text input. In the case of UI events, this is important for security reasons, as it prevents scripts from simulating user actions that interact with the browser itself.

diff --git a/files/pt-br/web/api/location/assign/index.html b/files/pt-br/web/api/location/assign/index.html new file mode 100644 index 0000000000..e1a1cf8609 --- /dev/null +++ b/files/pt-br/web/api/location/assign/index.html @@ -0,0 +1,120 @@ +--- +title: Location.assign() +slug: Web/API/Location/assign +tags: + - API + - HTML-DOM + - Location + - Referencia + - metodo +translation_of: Web/API/Location/assign +--- +

{{ APIRef("HTML DOM") }}

+ +

O método Location.assign() faz com que o navegador carregue o documento na URL especificada e a exiba na janela atual.

+ +

Se a tatefa não poder ser executada por alguma violação de segurança, uma {{domxref("DOMException")}} do tipo SECURITY_ERROR será lançada. Isso acontece se a origem do script chamador do método for diferente da origem da página originalmente descrita no objeto {{domxref("Location")}}, geralmente quando o script está hospedado em um dominio diferente.

+ +

Se a URL especificada for inválida, uma {{domxref("DOMException")}} do tipo SYNTAX_ERROR será lançada.

+ +

Sintaxe

+ +
location.assign(url);
+
+ +

Parâmetros

+ +
+
url
+
É uma {{domxref("DOMString")}} contendo a URL da página destino.
+
+ +

Exemplos

+ +
// Navega para a página do artigo Location.reload
+document.location.assign('https://developer.mozilla.org/en-US/docs/Web/API/Location.reload');
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentários
{{SpecName('HTML WHATWG', "history.html#dom-location-assign", "Location.assign()")}}{{Spec2('HTML WHATWG')}}Sem alterações  no {{SpecName("HTML5 W3C")}}.
{{SpecName('HTML5 W3C', "browsers.html#dom-location-assign", "Location.assign()")}}{{Spec2('HTML5 W3C')}}Definição inicial.
+ +

Compatibilidade com Navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte Básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte Básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/location/index.html b/files/pt-br/web/api/location/index.html new file mode 100644 index 0000000000..027a8564ec --- /dev/null +++ b/files/pt-br/web/api/location/index.html @@ -0,0 +1,184 @@ +--- +title: Location +slug: Web/API/Location +tags: + - API + - Interface + - Location +translation_of: Web/API/Location +--- +

{{APIRef("HTML DOM")}}

+ +

Resumo

+ +

A interface Location representa a localização do objeto a qual ele está associado. Mudanças feitas na interface serão refletidas nos objetos relacionados a ela. Tanto a interface {{domxref("Document")}}, como a interface {{domxref("Window")}} , têm este vínculo com a inteface Location, acessível via {{domxref("Document.location")}} e {{domxref("Window.location")}} respectivamente.

+ +

Propriedades

+ +

A inteface Location não herda nenhuma propriedade, mas implementa as propriedades de {{domxref("URLUtils")}}.

+ +
+
{{domxref("URLUtils.href")}}
+
É uma {{domxref("DOMString")}} que contém toda URL.
+
{{domxref("URLUtils.protocol")}}
+
É uma {{domxref("DOMString")}} que contém o esquema de protocolo da URL, incluindo o final ':'.
+
{{domxref("URLUtils.host")}}
+
É uma {{domxref("DOMString")}} que contém o host, que é o hostname seguido de ':' e a port da URL.
+
{{domxref("URLUtils.hostname")}}
+
É uma {{domxref("DOMString")}} que contém o domínio da URL.
+
{{domxref("URLUtils.port")}}
+
É uma {{domxref("DOMString")}} que contém o número da porta da URL.
+
{{domxref("URLUtils.pathname")}}
+
É uma {{domxref("DOMString")}} que contém '/', como caractere inicial, seguido do caminho da URL.
+
{{domxref("URLUtils.search")}}
+
É uma {{domxref("DOMString")}} que contém um '?' seguido dos parâmetros da URL.
+
{{domxref("URLUtils.hash")}}
+
É uma {{domxref("DOMString")}} que contém um '#' seguido do identificador de fragmento da URL.
+
{{domxref("URLUtils.username")}}
+
É uma {{domxref("DOMString")}} que contém o nome de usuário especificado antes do nome de domínio.
+
{{domxref("URLUtils.password")}}
+
É uma {{domxref("DOMString")}} que contém a senha especificada antes do nome de domínio.
+
{{domxref("URLUtils.origin")}} {{readOnlyInline}}
+
Retorna uma {{domxref("DOMString")}} que contém a forma canônica da origem do local especificado.
+
+ +

Métodos

+ +

A inteface Location não herda nenhum método, mas implementa os métodos de {{domxref("URLUtils")}}.

+ +
+
{{domxref("Location.assign()")}}
+
Carrega o recurso na URL fornecida como parâmetro.
+
{{domxref("Location.reload()")}}
+
Recarrega o recurso a partir da URL atual. Seu único parâmetro opcional é um {{domxref("Boolean")}}, que, quando verdadeiro (true), faz com que a página sempre seja recarregada a partir do servidor. Se for falso (false) ou não especificado,  o navegador pode recarregar a página a partir de seu cache.
+
{{domxref("Location.replace()")}}
+
Substitui o recurso atual pelo recurso presente na URL fornecida. A diferença entre o método assign() é que após usar replace() a página atual não será salva na sessão  {{domxref("History")}}, ou seja, o usuário não será capaz de usar o botão voltar para navegar até a página.
+
{{domxref("URLUtils.toString()")}}
+
Retorna uma {{domxref("DOMString")}} que contém toda URL. O método é um sinônimo para {{domxref("URLUtils.href")}}, embora não possa ser usado para modificar o valor.
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG', "history.html#the-location-interface", "Location")}}{{Spec2('HTML WHATWG')}}Nenhuma mudança a partir {{SpecName("HTML5 W3C")}}.
{{SpecName('HTML5 W3C', "browsers.html#the-location-interface", "Location")}}{{Spec2('HTML5 W3C')}}Definição inicial.
+ +

Compatibilidade entre Navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte Básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
origin em Windows.location{{CompatUnknown}}{{CompatGeckoDesktop("21")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
origin em todos objetos location (mas nos objetos Workers, que usam {{domxref("WorkerLocation")}}){{CompatUnknown}}{{CompatGeckoDesktop("26")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
username e password{{CompatUnknown}}{{CompatGeckoDesktop("26")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Suporte Básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
origin on Windows.location{{CompatUnknown}}{{CompatGeckoMobile("21")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
origin on all location objects (mas nos objetos Workers, que usam {{domxref("WorkerLocation")}}){{CompatUnknown}}{{CompatGeckoMobile("26")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
username e password{{CompatUnknown}}{{CompatGeckoMobile("26")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/location/reload/index.html b/files/pt-br/web/api/location/reload/index.html new file mode 100644 index 0000000000..24d990bbe8 --- /dev/null +++ b/files/pt-br/web/api/location/reload/index.html @@ -0,0 +1,114 @@ +--- +title: Location.reload() +slug: Web/API/Location/reload +tags: + - API + - HTML-DOM + - Localização + - Referencia + - metodo +translation_of: Web/API/Location/reload +--- +

{{ APIRef("HTML DOM") }}

+ +

O método Location.reload() recarrega a URL atual. Seu unico parâmetro opcional é um {{domxref("Boolean")}}, que, quando true, faz com que a página sempre seja recarregada do servidor. Se ele é false ou não estiver especificado, o navegador pode carregar ela do cache.

+ +

Caso não seja possível recarregar por questões de violação de segurança, uma {{domxref("DOMException")}} do tipo SECURITY_ERROR é jogada. Isso acontece se a origem do script que chama o método é diferente da origem da página originalmente descrita pelo objeto {{domxref("Location")}}, usualmente quando o script é hosteado em um domínio diferente.

+ +

Sintaxe

+ +
object.reload(forcedReload);
+
+ +

Parametros

+ +
+
forcedReload {{optional_inline}}
+
É uma flag {{domxref("Boolean")}}, que quando true, faz com que a página sempre seja recarregada do servidor, se é false ou não for definido, o navegador pode recarregar a página do cache.
+
+ +

Exemplos

+ +
// Recarrega a página atual sem usar o cache
+document.location.reload(true);
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "history.html#dom-location-reload", "Location.reload()")}}{{Spec2('HTML WHATWG')}}Nenhuma mudança do  {{SpecName("HTML5 W3C")}}.
{{SpecName('HTML5 W3C', "browsers.html#dom-location-reload", "Location.reload()")}}{{Spec2('HTML5 W3C')}}Definição inicial.
+ +

Compatibilidade de Navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/location/search/index.html b/files/pt-br/web/api/location/search/index.html new file mode 100644 index 0000000000..6cc17724d5 --- /dev/null +++ b/files/pt-br/web/api/location/search/index.html @@ -0,0 +1,55 @@ +--- +title: 'Location: search' +slug: Web/API/Location/search +tags: + - API + - Location + - Propriedade + - Search +translation_of: Web/API/Location/search +--- +
{{ApiRef("Location")}}
+ +

A propriedade search da interface {{domxref("Location")}} é um texto de busca, também chamado de query string ou querystring; isso é, uma {{domxref("USVString")}} contendo um '?' seguido pelos parâmetros da URL.

+ +

Os navegadores modernos fornecem o URLSearchParams e o URL.searchParams para facilitar a análise dos parâmetros da querystring.

+ +

Sintaxe

+ +
string = object.search;
+object.search = string;
+
+ +

Exemplos

+ +
// Seleciona o elemento <a id="myAnchor" href="https://developer.mozilla.org/en-US/docs/Location.search?q=123">
+var anchor = document.getElementById("myAnchor");
+var queryString = anchor.search; // Retorna:'?q=123'
+
+// Análise adicional:
+let params = new URLSearchParams(queryString);
+let q = parseInt(params.get("q")); // é o número 123
+
+ +

Especificação

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG', '#dom-location-search', 'search')}}{{Spec2('HTML WHATWG')}}Definição inicial.
+ +

Compatibilidade do navegador

+ + + +

{{Compat("api.Location.search")}}

diff --git a/files/pt-br/web/api/mediadevices/index.html b/files/pt-br/web/api/mediadevices/index.html new file mode 100644 index 0000000000..83e3452f58 --- /dev/null +++ b/files/pt-br/web/api/mediadevices/index.html @@ -0,0 +1,251 @@ +--- +title: MediaDevices +slug: Web/API/MediaDevices +translation_of: Web/API/MediaDevices +--- +
{{APIRef("Media Capture and Streams")}}{{SeeCompatTable}}
+ +

As interfaces MediaDevices proporcionam accesso aos dispositivos de entrada de midia conectados, como câmeras e microfones, bem como compartilhamento de tela. Essencialmente, isso te permite obter acesso a qualquer mídia gerada pelo hardware.

+ +

Propriedades

+ +

As mesmas propriedades de {{domxref("EventTarget")}}.

+ +

Manipuladores de Evento

+ +
+
{{ domxref("MediaDevices.ondevicechange") }}
+
O manipulador de evento para o evento {{event("devicechange")}}. Esse evento é entregue ao objeto MediaDevices quando uma entrada de mídia ou dispositivo de saída é conectado ou removido do computador do usuário.
+
+ +

Métodos

+ +

Mesmos métodos de {{domxref("EventTarget")}}.

+ +
+
{{ domxref("EventTarget.addEventListener()") }}
+
Registra um manipulador de eventos para um tipo específico de evento.
+
{{ domxref("MediaDevices.enumerateDevices()") }}
+
Obtém um array de informações sobre a entrada de midia e dispositivos de saída disponíveis no sistema.
+
{{domxref("MediaDevices.getSupportedConstraints()")}}
+
Retorna um objeto consoante com {{domxref("MediaTrackSupportedConstraints")}} indicando quais propriedades restritivas são suportadas na interface {{domxref("MediaStreamTrack")}}. Veja {{SectionOnPage("/en-US/docs/Web/API/Media_Streams_API", "Capabilities and constraints")}} para aprender mais sobre restrições e como usá-las.
+
{{ domxref("MediaDevices.getUserMedia()") }}
+
Após a permissão do usuário (pedida através de um prompt), liga a câmera, microfone e/ou a tramissão de tela no sistema e fornece uma {{domxref("MediaStream")}} contendo uma faixa de vídeo e/ou áudio com a entrada.
+
{{ domxref("EventTarget.removeEventListener()") }}
+
Remove um escutador de evento.
+
+ +

Exemplo

+ +
'use strict';
+
+// Coloca as variáveis no escopo global para torná-las disponível para o Console do navegador.
+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; // torna as variáveis disponíveis para o Console do navegador
+  video.srcObject = stream;
+})
+.catch(function(error) {
+  if (error.name === 'ConstraintNotSatisfiedError') {
+    errorMsg('A resolução ' + constraints.video.width.exact + 'x' +
+        constraints.video.width.exact + ' px não é suportada pelo seu dispositivo.');
+  } else if (error.name === 'PermissionDeniedError') {
+    errorMsg('As permissões para usar sua câmera e microfone não foram fornecidas. ' +
+      'Você precisa permitir o acesso da página aos seus dispositivos para ' +
+      'que a demo funcione.');
+  }
+  errorMsg('getUserMedia error: ' + error.name, error);
+});
+
+function errorMsg(msg, error) {
+  errorElement.innerHTML += '<p>' + msg + '</p>';
+  if (typeof error !== 'undefined') {
+    console.error(error);
+  }
+}
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('Media Capture', '#mediadevices', 'MediaDevices')}}{{Spec2('Media Capture')}}Definição inicial
+ +

Compatibilidade

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
RecursoChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte Básico{{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}}
Eventos ondevicechange e devicechange{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop(51)}}[1]{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}
Captura de áudio estéreo{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop(55)}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
RecursoAndroid WebviewChrome para AndroidEdgeFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome para Android
Suporte Básico{{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}}
Eventos ondevicechange e devicechange{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(51)}}[1]{{CompatUnknown}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}
Captura de áudio estéreo{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatNo}}
+ +

[1] O suporte para o evento devicechange e para {{domxref("MediaDevices.ondevicechange")}} começou no Firefox 51, mas somente pra Mac, e desabilitado por padrão. Ele pode ser habilitado configurando a preferência media.ondevicechange.enabled para true. O suporte para esse evendo foi adicionado para Linux e Windows — ativado por padrão — a partir do Firefox 52.

+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/mediastreamtrack/index.html b/files/pt-br/web/api/mediastreamtrack/index.html new file mode 100644 index 0000000000..33f62732dc --- /dev/null +++ b/files/pt-br/web/api/mediastreamtrack/index.html @@ -0,0 +1,181 @@ +--- +title: MediaStreamTrack +slug: Web/API/MediaStreamTrack +translation_of: Web/API/MediaStreamTrack +--- +
{{APIRef("Media Capture and Streams")}}
+ +

Resumo

+ +

A interface MediaStream representa uma stream de conteúdo de mídia. Uma stream consiste em várias tracks, como faixas de áudio e vídeo.

+ +

Properties

+ +
+
{{domxref("MediaStreamTrack.enabled")}}
+
Is a Boolean value with a value of true if the track is enabled, that is allowed to render the media source stream; or false if it is disabled, that is not rendering the media source stream but silence and blackness. If the track has been disconnected, this value can be changed but has no more effect.
+
{{domxref("MediaStreamTrack.id")}} {{readonlyInline}}
+
Returns a {{domxref("DOMString")}} containing a unique identifier (GUID) for the track; it is generated by the browser.
+
{{domxref("MediaStreamTrack.kind")}} {{readonlyInline}}
+
Returns a {{domxref("DOMString")}} set to "audio" if the track is an audio track and to "video", if it is a video track. It doesn't change if the track is deassociated from its source.
+
{{domxref("MediaStreamTrack.label")}} {{readonlyInline}}
+
Returns a {{domxref("DOMString")}} containing a user agent-assigned label that identifies the track source, as in "internal microphone". The string may be left empty and is empty as long as no source has been connected. When the track is deassociated from its source, the label is not changed.
+
{{domxref("MediaStreamTrack.muted")}} {{readonlyInline}}
+
Returns a Boolean value with a value of true if the track is muted, false otherwise.
+
{{domxref("MediaStreamTrack.readonly")}} {{readonlyInline}}
+
Returns a Boolean value with a value of true if the track is readonly (such a video file source or a camera that settings can't be modified),false otherwise.
+
{{domxref("MediaStreamTrack.readyState")}} {{readonlyInline}}
+
Returns an enumerated value giving the status of the track.It takes one of the following values: +
    +
  • "live" which indicates that an input is connected and does its best-effort in providing real-time data. In that case, the output of data can be switched on or off using the MediaStreamTrack.enabled attribute.
  • +
  • "ended" which indicates that the input is not giving any more data and will never provide new data.
  • +
+
+
{{domxref("MediaStreamTrack.remote")}} {{readonlyInline}}
+
Returns a boolean value with a value of true if the track is sourced by a {{domxref("RTCPeerConnection")}}, false otherwise.
+
+ +

Event handlers

+ +
+
{{domxref("MediaStreamTrack.onstarted")}}
+
Is a {{domxref("EventHandler")}} containing the action to perform when an {{event("started")}} event is fired on the object, that is when a new {{domxref("MediaStreamTrack")}} object is added.
+
{{domxref("MediaStreamTrack.onmute")}}
+
Is a {{domxref("EventHandler")}} containing the action to perform when an {{event("mute")}} event is fired on the object, that is when the streaming is terminating.
+
{{domxref("MediaStreamTrack.onunmute")}}
+
Is a {{domxref("EventHandler")}} containing the action to perform when an {{event("unmute")}} event is fired on the object, that is when a  {{domxref("MediaStreamTrack")}} object is removed from it.
+
{{domxref("MediaStreamTrack.onoverconstrained")}}
+
Is a {{domxref("EventHandler")}} containing the action to perform when an {{event("overconstrained")}} event is fired on the object, that is when a  {{domxref("MediaStreamTrack")}} object is removed from it.
+
{{domxref("MediaStreamTrack.oneended")}}
+
Is a {{domxref("EventHandler")}} containing the action to perform when an {{event("ended_(MediaStream)", "ended")}} event is fired on the object, that is when a  {{domxref("MediaStreamTrack")}} object is removed from it.
+
+ +

Methods

+ +
+
{{domxref("MediaStreamTrack.getConstraints()")}}
+
 
+
{{domxref("MediaStreamTrack.applyConstraints()")}}
+
 
+
{{domxref("MediaStreamTrack.getSettings()")}}
+
 
+
{{domxref("MediaStreamTrack.getCapabilities()")}}
+
 
+
{{domxref("MediaStreamTrack.clone()")}}
+
 
+
{{domxref("MediaStreamTrack.stop()")}}
+
Stops playing the source associated to the track, both the source and the track are deassociated. The track state is set to ended.
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Media Capture', '#mediastreamtrack', 'MediaStreamTrack')}}{{Spec2('Media Capture')}}Initial definition
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatUnknown}}
stop(){{CompatUnknown}}{{CompatGeckoDesktop(34)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
muted, onmuted, onunmuted, readonly, readyState, remote, onstarted, onended, onoverconstrained, appendConstraint(), applyConstraints(), constraints(), getConstraints(){{CompatUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatUnknown}}
+ + + + + + +
stop()
+
{{CompatUnknown}}{{CompatGeckoDesktop(34)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
muted, onmuted, onunmuted, readonly, readyState, remote, onstarted, onended, onoverconstrained, appendConstraint(), applyConstraints(), constraints(), getConstraints(){{CompatUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatUnknown}}
+
+ +

See also

+ + diff --git a/files/pt-br/web/api/messagechannel/index.html b/files/pt-br/web/api/messagechannel/index.html new file mode 100644 index 0000000000..225416121f --- /dev/null +++ b/files/pt-br/web/api/messagechannel/index.html @@ -0,0 +1,152 @@ +--- +title: MessageChannel +slug: Web/API/MessageChannel +translation_of: Web/API/MessageChannel +--- +

{{APIRef("HTML DOM")}}

+ +

A interface MessageChannel da API Channel Messaging nos permite criar um novo canal de mensagem e enviar os dados através de suas duas propriedades {{domxref("MessagePort")}}.

+ +

{{AvailableInWorkers}}

+ +

Propriedades

+ +
+
{{domxref("MessageChannel.port1")}} {{readonlyInline}}
+
Retorna port1 do canal.
+
{{domxref("MessageChannel.port2")}} {{readonlyInline}}
+
Retorna port2 do canal.
+
+ +

Construtor

+ +
+
{{domxref("MessageChannel.MessageChannel", "MessageChannel()")}}
+
+

Retorna um novo objeto MessageChannel com dois novos objetos {{domxref("MessagePort")}}.

+
+
+ +

Exemplo

+ +

No seguinte bloco de codigo, você pode ver um novo canal sendo criado usando o construtor {{domxref("MessageChannel.MessageChannel", "MessageChannel()")}}. Quando o {{HTMLElement("iframe")}} tiver carregado, nos passamos o {{domxref("MessageChannel.port2")}} para o {{HTMLElement("iframe")}} usando {{domxref("MessagePort.postMessage")}} juntamente com uma mensagem. O manipulador handleMessage então reponde à mensagem que foi enviada de volta do {{HTMLElement("iframe")}} (using {{domxref("MessagePort.onmessage")}}), colocando-o em um parágrafo.

+ +
var channel = new MessageChannel();
+var para = document.querySelector('p');
+
+var ifr = document.querySelector('iframe');
+var otherWindow = ifr.contentWindow;
+
+ifr.addEventListener("load", iframeLoaded, false);
+
+function iframeLoaded() {
+  otherWindow.postMessage('Hello from the main page!', '*', [channel.port2]);
+}
+
+channel.port1.onmessage = handleMessage;
+function handleMessage(e) {
+  para.innerHTML = e.data;
+}   
+ +

Para um exemplo completo, veja nosso  channel messaging basic demo no Github (rode online também ).

+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçõesStatusComentário
{{SpecName('HTML WHATWG', 'web-messaging.html#message-channels','Message channels')}}{{Spec2('HTML WHATWG')}} 
+ +

Compatibilidade entre os navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte Básico4{{CompatVersionUnknown}}{{CompatGeckoDesktop(41)}}10.010.65
Disponivel em workers{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop(41)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari Mobile
Suporte Básico4.44{{CompatVersionUnknown}}{{CompatGeckoMobile(41)}}{{CompatVersionUnknown}}10.011.55.1
Disponivel em workers{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(41)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/messageport/index.html b/files/pt-br/web/api/messageport/index.html new file mode 100644 index 0000000000..ae82cc0a79 --- /dev/null +++ b/files/pt-br/web/api/messageport/index.html @@ -0,0 +1,117 @@ +--- +title: MessagePort +slug: Web/API/MessagePort +tags: + - API + - Channel messaging + - HTML5 + - Interface + - MessagePort + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/API/MessagePort +--- +

{{APIRef("HTML DOM")}}

+ +

The MessagePort interface of the Channel Messaging API represents one of the two ports of a {{domxref("MessageChannel")}}, allowing messages to be sent from one port and listening out for them arriving at the other.

+ +

{{AvailableInWorkers}}

+ +

Methods

+ +

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

+ +
+
{{domxref("MessagePort.postMessage","postMessage()")}}
+
Sends a message from the port, and optionally, transfers ownership of objects to other browsing contexts.
+
{{domxref("MessagePort.start","start()")}}
+
Starts the sending of messages queued on the port (only needed when using {{domxref("EventTarget.addEventListener")}}; it is implied when using {{domxref("MessagePort.onmessage")}}.)
+
{{domxref("MessagePort.close","close()")}}
+
Disconnects the port, so it is no longer active.
+
+ +

Event handlers

+ +

Inherits event handlers from its parent, {{domxref("EventTarget")}}

+ +
+
{{domxref("MessagePort.onmessage","onmessage")}}
+
An {{domxref("EventListener")}} called when {{domxref("MessageEvent")}} of type message is fired on the port—that is, when the port receives a message.
+
{{domxref("MessagePort.onmessageerror","onmessageerror")}}
+
An {{domxref("EventListener")}} called when a {{domxref("MessageEvent")}} of type {{domxref("MessageError")}} is fired—that is, when it receives a message that cannot be deserialized.
+
+ +

Events

+ +
+
{{domxref("MessagePort.message_event","message")}}
+
Fired when a MessagePort object receives a message.
+ Also available via the {{domxref("MessagePort.onmessage","onmessage")}} property.
+
{{domxref("MessagePort.messageerror_event","messageerror")}}
+
Fired when a MessagePort object receives a message that can't be deserialized.
+ Also available via the {{domxref("MessagePort.onmessageerror","onmessageerror")}} property.
+
+ +

Example

+ +

In the following example, you can see a new channel being created using the {{domxref("MessageChannel.MessageChannel","MessageChannel()")}} constructor.

+ +

When the IFrame has loaded, we register an {{domxref("MessagePort.onmessage","onmessage")}} handler for {{domxref("MessageChannel.port1")}} and transfer {{domxref("MessageChannel.port2")}} to the IFrame using the {{domxref("window.postMessage")}} method along with a message.

+ +

When a message is received back from the IFrame, the onMessage function simply outputs the message to a paragraph.

+ +
var channel = new MessageChannel();
+var output = document.querySelector('.output');
+var iframe = document.querySelector('iframe');
+
+// Wait for the iframe to load
+iframe.addEventListener("load", onLoad);
+
+function onLoad() {
+  // Listen for messages on port1
+  channel.port1.onmessage = onMessage;
+
+  // Transfer port2 to the iframe
+  iframe.contentWindow.postMessage('Hello from the main page!', '*', [channel.port2]);
+}
+
+
+// Handle messages received on port1
+function onMessage(e) {
+  output.innerHTML = e.data;
+}
+
+ +

For a full working example, see our channel messaging basic demo on Github (run it live too).

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'web-messaging.html#message-ports','Message ports')}}{{Spec2('HTML WHATWG')}}
+ +

Browser compatibility

+ +
+ + +

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

+
+ +

See also

+ + diff --git a/files/pt-br/web/api/messageport/postmessage/index.html b/files/pt-br/web/api/messageport/postmessage/index.html new file mode 100644 index 0000000000..26e9ffbbc1 --- /dev/null +++ b/files/pt-br/web/api/messageport/postmessage/index.html @@ -0,0 +1,81 @@ +--- +title: MessagePort.postMessage() +slug: Web/API/MessagePort/postMessage +translation_of: Web/API/MessagePort/postMessage +--- +

{{APIRef("HTML DOM")}}

+ +

O método postMessage() da interface {{domxref("MessagePort")}} envia uma mensagem da porta e opcionalmente transfere a propriedade do objeto para outros contexto de navegação.

+ +

{{AvailableInWorkers}}

+ +

Syntax

+ +
port.postMessage(message, transferList);
+ +

Returns

+ +

Vazio.

+ +

Parameters

+ +
+
message
+
A mensagem que você quer enviar atravéz do canal. Esta mensagem pode ser de qualquer tipo de dados basico. Multiplos items podem ser enviados com diferentestes tipos de dados como em um Array.
+
transferList {{optional_inline}}
+
{{domxref("Transferable")}} objects to be transferred — these objects have their ownership transferred to the receiving browsing context, so are no longer usable by the sending browsing context.
+
+ +

Example

+ +

In the following code block, you can see a new channel being created using the {{domxref("MessageChannel()", "MessageChannel.MessageChannel")}} constructor. When the IFrame has loaded, we pass {{domxref("MessageChannel.port2")}} to the IFrame using {{domxref("window.postMessage")}} along with a message. The handleMessage handler then responds to a message being sent back from the IFrame using onmessage, putting it into a paragraph — {{domxref("MessageChannel.port1")}} is listened to, to check when the message arrives.

+ +
var channel = new MessageChannel();
+var para = document.querySelector('p');
+
+var ifr = document.querySelector('iframe');
+var otherWindow = ifr.contentWindow;
+
+ifr.addEventListener("load", iframeLoaded, false);
+
+function iframeLoaded() {
+  otherWindow.postMessage('Hello from the main page!', '*', [channel.port2]);
+}
+
+channel.port1.onmessage = handleMessage;
+function handleMessage(e) {
+  para.innerHTML = e.data;
+}   
+ +

For a full working example, see our channel messaging basic demo on Github (run it live too).

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'web-messaging.html#dom-messageport-postmessage', 'postMessage()')}}{{Spec2('HTML WHATWG')}}
+ +

Browser compatibility

+ +
+ + +

{{Compat("api.MessagePort.postMessage")}}

+
+ +

See also

+ + diff --git a/files/pt-br/web/api/mouseevent/clientx/index.html b/files/pt-br/web/api/mouseevent/clientx/index.html new file mode 100644 index 0000000000..efeb585203 --- /dev/null +++ b/files/pt-br/web/api/mouseevent/clientx/index.html @@ -0,0 +1,149 @@ +--- +title: MouseEvent.clientX +slug: Web/API/MouseEvent/clientX +translation_of: Web/API/MouseEvent/clientX +--- +

{{APIRef("DOM Events")}}

+ +

clientX é uma propriedade somente de leitura da interface {{domxref("MouseEvent")}} que fornece as coordenadas horizontais dentro da área do aplicativo do cliente em que o evento ocorreu (diferente das coordenadas dentro da página). Por exemplo, clicando no canto superior esquerdo da área do cliente sempre irá resultar em um evento de mouse com um valor clientX de 0, independentemente se a página foi rolada horizontalmente. Originalmente, essa propriedade era definida como o número inteiro long. O Módulo de Visualização CSSOM o redefiniu como a fraçãodouble. Veja a seção de compatibilidade do Navegador para detalhes.

+ +

Sintaxe

+ +
var x = instanceOfMouseEvent.clientX
+
+ +

Valor de retorno

+ +

Um número

+ +

Exemplo

+ +
<!DOCTYPE html>
+<html>
+  <head>
+    <title>clientX/clientY example</title>
+
+    <script>
+      function showCoords(evt){
+        alert(
+          "clientX value: " + evt.clientX + "\n" +
+          "clientY value: " + evt.clientY + "\n"
+        );
+      }
+    </script>
+  </head>
+  <body onmousedown="showCoords(event)">
+    <p>Para mostrar as coordenadas do mouse em qualquer lugar da página.</p>
+  </body>
+</html>
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('CSSOM View','#dom-mouseevent-clientx', 'clientX')}}{{Spec2('CSSOM View')}}Redefine {{domxref("MouseEvent")}} delong para double
{{SpecName('DOM3 Events','#widl-MouseEvent-clientX','MouseEvent.clientX')}}{{Spec2('DOM3 Events')}}Nenhuma mudança de {{SpecName('DOM2 Events')}}.
{{SpecName('DOM2 Events','#Events-MouseEvent','MouseEvent.clientX')}}{{Spec2('DOM2 Events')}}Definição inicial.
+ +

Compatibilidade com Navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown()}}6{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}
Redefinido de long para double{{CompatChrome(56)}}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroid WebviewChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
Redefinido de long para double{{CompatChrome(56)}}{{CompatChrome(56)}}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/mouseevent/clienty/index.html b/files/pt-br/web/api/mouseevent/clienty/index.html new file mode 100644 index 0000000000..6333ab631c --- /dev/null +++ b/files/pt-br/web/api/mouseevent/clienty/index.html @@ -0,0 +1,91 @@ +--- +title: MouseEvent.clientY +slug: Web/API/MouseEvent/clientY +tags: + - API + - CSSOM View + - Eventos de DOM + - Eventos de mouse + - Propriedade + - Somente Leitura +translation_of: Web/API/MouseEvent/clientY +--- +
{{APIRef("DOM Events")}}
+ +

A propriedade clientY  da interface {{domxref("MouseEvent")}} fornece a coordenada vertical do cliente dentro da aplicacão em que o evento ocorreu (ao contrário da coordenada que pertence a página).

+ +

Por exemplo, clicando no topo da área do cliente sempre resultará num evento de mouse com um valor 0 de clientY, independente se a página está "escrollada" verticalmente.

+ +

Sintaxe

+ +
var y = instanciaDeEventoDoMouse.clientY
+
+ +

Valor de retorno

+ +

O valor retornado por essa propriedade é um valor flutuante double como foi redefinida pelo "CSSOM View Module". Originalmente esta propriedade era definida como um inteiro long. Veja a seção de compatibilidade de browsers para mais detalhes.

+ +

Exemplo

+ +

Este exemplo mostra as coordenadas do mouse quando você ativar o evento {{Event("mousemove")}}.

+ +

HTML

+ +
<p>Mova seu mouse para ver sua posicão.</p>
+<p id="screen-log"></p>
+ +

JavaScript

+ +
let screenLog = document.querySelector('#screen-log');
+document.addEventListener('mousemove', logKey);
+
+function logKey(e) {
+  screenLog.innerText = `
+    Screen X/Y: ${e.screenX}, ${e.screenY}
+    Client X/Y: ${e.clientX}, ${e.clientY}`;
+}
+ +

Resultado

+ +

{{EmbedLiveSample("Example")}}

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('CSSOM View','#dom-mouseevent-clienty', 'clientY')}}{{Spec2('CSSOM View')}}Redefine {{domxref("MouseEvent")}} de long para double.
{{SpecName('DOM3 Events','#widl-MouseEvent-clientY','MouseEvent.clientY')}}{{Spec2('DOM3 Events')}}Sem mudanças vindas de {{SpecName('DOM2 Events')}}.
{{SpecName('DOM2 Events','#Events-MouseEvent','MouseEvent.clientY')}}{{Spec2('DOM2 Events')}}Definição inicial.
+ +

Compatibilidade de browser

+ + + +

{{Compat("api.MouseEvent.clientY")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/mouseevent/index.html b/files/pt-br/web/api/mouseevent/index.html new file mode 100644 index 0000000000..cce575dec6 --- /dev/null +++ b/files/pt-br/web/api/mouseevent/index.html @@ -0,0 +1,336 @@ +--- +title: MouseEvent +slug: Web/API/MouseEvent +tags: + - API + - DOM + - DOM Events + - Interface + - Precisa de Tradução + - Referencia + - TopicStub +translation_of: Web/API/MouseEvent +--- +

A interface MouseEvent representa eventos que ocorrem devido à interação do usuário com um dispositivo apontador (como um mouse). Eventos comuns usando esta interface incluem click, dblclick, mouseup, mousedown.

+ +

MouseEvent deriva de UIEvent, que por sua vez deriva de Event. Embora o método MouseEvent.initMouseEvent() seja mantido para compatibilidade com versões anteriores, a criação de um objeto MouseEvent deve ser feita usando o construtor MouseEvent().

+ +

Vários eventos mais específicos derivam de MouseEvent como: WheelEvent e DragEvent.
+  

+ +

{{InheritanceDiagram}}

+ +

Construtor

+ +
+
MouseEvent()
+
Cria um objeto MouseEvent.
+
+ +

Propriedades

+ +

Essa interface também herda propriedades de seus pais, UIEvent  e Event.

+ +
+
+

MouseEvent.altKey Read only

+
+
Retorna truese a tecla alt estava pressionada quando o evento do mouse foi disparado.
+
+

MouseEvent.button Read only

+
+
O número do botão que foi pressionado (se aplicável) quando o evento do mouse foi disparado.
+
MouseEvent.buttonsRead only 
+
+

Os botões sendo pressionados (se houver) quando o evento do mouse foi disparado.

+
+
MouseEvent.clientX Read only
+
A coordenada X do ponteiro do mouse em coordenadas locais (conteúdo DOM).
+
MouseEvent.clientYRead only
+
A coordenada Y do ponteiro do mouse em coordenadas locais (conteúdo DOM).
+
MouseEvent.ctrlKey Read only
+
Retorna true se a tecla control estava pressionada quando o evento do mouse foi disparado.
+
MouseEvent.metaKey Read only
+
Retorna true se a tecla meta estava pressionada quando o evento do mouse foi disparado.
+
MouseEvent.movementXRead only
+
A coordenada X do ponteiro do mouse em relação à posição do último evento mousemove .
+
MouseEvent.movementY Read only
+
A coordenada Y do ponteiro do mouse em relação à posição do último  evento mousemove.
+
MouseEvent.offsetX Read only     
+
A coordenada X do ponteiro do mouse em relação à posição da borda de preenchimento do nó de destino.
+
MouseEvent.offsetY Read only   
+
A coordenada Y do ponteiro do mouse em relação à posição da borda de preenchimento do nó de destino.
+
MouseEvent.pageX Read only
+
A coordenada X do ponteiro do mouse em relação a todo o documento.
+
MouseEvent.pageY Read only
+
A coordenada Y do ponteiro do mouse em relação a todo o documento.
+
MouseEvent.region Read only
+
Retorna o id da região afetada pelo evento. Se nenhuma região atingida for afetada, null será retornado.
+
MouseEvent.relatedTarget Read only
+
+

O destino secundário do evento, se houver.

+
+
MouseEvent.screenX Read only
+
A coordenada X do ponteiro do mouse em coordenadas globais (tela).
+
MouseEvent.screenY Read only
+
A coordenada Y do ponteiro do mouse em coordenadas globais (tela).
+
MouseEvent.shiftKey Read only
+
Retorna true se a tecla shift estava pressionada quando o evento do mouse foi disparado.
+
MouseEvent.which Read only
+
O botão sendo pressionado quando o evento do mouse foi disparado.
+
MouseEvent.mozPressure Read only
+
A quantidade de pressão aplicada a um dispositivo de toque ou tablet ao gerar o evento; este valor varia entre 0.0 (pressão mínima) e 1.0 (pressão máxima).
+
MouseEvent.mozInputSource Read only
+
+
+

O tipo de dispositivo que gerou o evento (uma das constantes MOZ_SOURCE_*   listadas abaixo). Isso permite, por exemplo, determinar se um evento de mouse foi gerado por um mouse real ou por um evento de toque (o que pode afetar o grau de precisão com que você interpreta as coordenadas associadas ao evento).

+
+
MouseEvent.webkitForce Read only
+
A quantidade de pressão aplicada ao clicar
+
MouseEvent.xRead only
+
Alias ​​para MouseEvent.clientX.
+
MouseEvent.y Read only
+
Alias ​​para MouseEvent.clientY
+
+ +

Constantes

+ +
+
MouseEvent.WEBKIT_FORCE_AT_MOUSE_DOWN Read only
+
Força mínima necessária para um clique normal.
+
MouseEvent.WEBKIT_FORCE_AT_FORCE_MOUSE_DOWN Read only
+
Força mínima necessária para um clique de força
+
+ +

Método

+ +

Essa interface também herda métodos de seus pais, UIEvent e Event.

+ +
+
MouseEvent.getModifierState()
+
+ +
+
Retorna o estado tual da tecla modificadora especificada. Consulte KeyboardEvent.getModifierState() para obter detalhes.
+
+ +
+
MouseEvent.initMouseEvent()
+
Inicializa o valor de um MouseEvent criado. Se o evento já foi despachado, este método não faz nada.
+
+ +

Exemplo

+ +

Este exemplo demonstra a simulação de um clique (que está gerando programaticamente um evento de clique) em uma caixa de seleção usando métodos DOM.

+ +
function simulateClick() {
+  var evt = new MouseEvent("click", {
+    bubbles: true,
+    cancelable: true,
+    view: window
+  });
+  var cb = document.getElementById("checkbox"); //element to click on
+  var canceled = !cb.dispatchEvent(evt);
+  if(canceled) {
+    // A handler called preventDefault
+    alert("canceled");
+  } else {
+    // None of the handlers called preventDefault
+    alert("not canceled");
+  }
+}
+document.getElementById("button").addEventListener('click', simulateClick);
+ +
<p><label><input type="checkbox" id="checkbox"> Checked</label>
+<p><button id="button">Click me</button>
+ +

Clique no botão para ver como funciona a amostra:

+ +

{{EmbedLiveSample('Example')}}

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSSOM View','#extensions-to-the-mouseevent-interface', 'MouseEvent')}}Rascunho de trabalhoRedefine MouseEvent de longo para duplo. Isto significa que um PointerEvent cuja pointerType é rato será uma de casal.
{{SpecName("HTML WHATWG", "#dom-mouseevent-region", "MouseEvent.region")}}{{Spec2('HTML WHATWG')}}Do Document Object Model (DOM) Nível 3 Events Specification , adicionado propriedades movementX e movementY.
{{SpecName('Pointer Lock','#extensions-to-the-mouseevent-interface','MouseEvent')}}{{Spec2('Pointer Lock')}}
{{SpecName('CSSOM View', '#extensions-to-the-mouseevent-interface', 'MouseEvent')}}{{Spec2('CSSOM View')}}A partir do documento de modelo de objeto (DOM) Nível 3 Especificação de eventos , adicionados offsetX e offsetY, pageX e pageY, x, e y propriedades. Propriedades redefinidas de tela, página, cliente e coordenadas (x e y) a partir double de long.
{{SpecName('DOM3 Events','#events-mouseevents','MouseEvent')}}{{Spec2('DOM3 Events')}}Em Document Object Model (DOM) Nível 2, especificação de eventos, adicionado ao construtor MouseEvent (), o método getModifierState() e a propriedade de buttons.
{{SpecName('DOM2 Events','#Events-MouseEvent','MouseEvent')}}{{Spec2('DOM2 Events')}}Definição inicial.
+ +

Compatibilidade do navegador

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}
{{domxref("MouseEvent.movementX","movementX")}}
+ {{domxref("MouseEvent.movementY","movementY")}}
{{CompatChrome(37)}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}} {{property_prefix("moz")}}{{ CompatUnknown() }}{{CompatVersionUnknown()}}{{ CompatUnknown() }}
{{ domxref("MouseEvent.buttons", "buttons") }}{{CompatChrome(43)}}{{CompatVersionUnknown()}}{{ CompatVersionUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{CompatNo}}
{{ domxref("MouseEvent.which", "which") }}{{CompatChrome(1)}}{{CompatVersionUnknown()}}1.09.05.01.0
{{domxref("MouseEvent.getModifierState()", "getModifierState()")}}{{CompatChrome(47)}}{{CompatVersionUnknown()}}{{CompatGeckoDesktop(15)}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}
{{domxref("MouseEvent.mozPressure", "mozPressure")}} and {{domxref("MouseEvent.mozInputSource", "mozInputSource")}} {{non-standard_inline}}{{CompatNo}}{{ CompatUnknown() }}{{CompatGeckoDesktop(2)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
{{domxref("MouseEvent.MouseEvent", "MouseEvent()")}}{{CompatChrome(45)}}{{ CompatUnknown() }}{{CompatGeckoDesktop(11)}}9.0{{CompatVersionUnknown()}}{{ CompatUnknown() }}
{{domxref("MouseEvent.region")}}{{CompatChrome(51)}}[1]{{ CompatUnknown() }}{{CompatGeckoDesktop(32)}}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
{{domxref("MouseEvent.offsetX")}}, and {{domxref("MouseEvent.offsetY")}}{{CompatVersionUnknown()}}9{{CompatGeckoDesktop(40)}}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
{{domxref("MouseEvent.screenX")}}, {{domxref("MouseEvent.screenY")}}, {{domxref("MouseEvent.clientX")}}, and {{domxref("MouseEvent.Y")}} are double instead of long.{{CompatChrome(56)}}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

[1] Requires enabling the ExperimentalCanvasFeatures flag.

+ +

Veja também

+ +

Seu pai direto, UIEvent.
+ PointerEvent: Para eventos de ponteiro avançados, incluindo multitoque

diff --git a/files/pt-br/web/api/mutationobserver/index.html b/files/pt-br/web/api/mutationobserver/index.html new file mode 100644 index 0000000000..2ca0d03404 --- /dev/null +++ b/files/pt-br/web/api/mutationobserver/index.html @@ -0,0 +1,221 @@ +--- +title: MutationObserver +slug: Web/API/MutationObserver +translation_of: Web/API/MutationObserver +--- +

{{APIRef("DOM")}}

+ +

MutationObserver fornece aos desenvolvedores uma maneira de reagir a mudanças em um DOM. Ele é concebido como um substituto para Mutation Events definido na especificação de eventos DOM nível 3.

+ +

Constructor

+ +

MutationObserver()

+ +

Construtor para instanciar novos observadores de mutação do DOM.

+ +
MutationObserver(
+  function callback
+);
+
+ +
Parâmetros
+ +
+
callback
+
A função que será chamada em cada mutação do DOM. O observador irá chamar esta função com dois argumentos. O primeiro é um array de objetos, cada um do tipo MutationRecord. O segundo é a essa instância MutationObserver.
+
+ +

Métodos da instância

+ + + + + + + + + + + + + +
void observe( {{domxref("Node")}} target, MutationObserverInit options );
void disconnect();
Array takeRecords();
+ +

observe()

+ +

Registra a instância MutationObserver para receber notificações das mutações do DOM no nó especificado.

+ +
void observe(
+  {{domxref("Node")}} target,
+  MutationObserverInit options
+);
+
+ +
Parâmetros
+ +
+
target
+
O {{domxref("Node")}} no qual é observadas as mutações do DOM.
+
options
+
Um objeto MutationObserverInit especifica quais mutações DOM devem ser reportadas.
+
+ +
NOTA: Adicionar um observador para um elemento é como utilizar o addEventListener, se você observar o elemento várias vezes não faz diferença. Ou seja, se você observar um elemento duas vezes, o callback do observador não disparará duas vezes, nem você deverá executar duas vezes o disconnect(). Em outras palavras, uma vez que um elemento é observado, observá-lo novamento com a mesma instância do observador não fará nada. No entanto, se o objeto callback for diferente, ele, é claro, adicionará outro observador para isso.
+ +

disconnect()

+ +

Pára o rebimento de notificações das mutações do DOM na instância MutationObserver. O callback do observador não será invocado até que método observe() seja novamente utilizado.

+ +
void disconnect();
+
+ +

takeRecords()

+ +

Esvazia a fila de registro da instância MutationObserver e retorna o que estava nela.

+ +
Array takeRecords();
+
+ +
Valor de retorno
+ +

Retorna um Array de MutationRecords.

+ +

MutationObserverInit

+ +

MutationObserverInit é um objeto que pode especificar as seguintes propriedades:

+ +
NOTA: No mínimo childList, attributes, ou characterData devem ser definidos como true. Caso contrário o erro "An invalid or illegal string was specified" é lançado.
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyDescription
childListDefina como true se adições e remoções dos elementos filho do nó alvo (incluindo nós de texto) devem ser observadas.
attributesDefina como true se mutações dos atributos do alvo devem ser observadas.
characterDataDefina como true se mutações dos dados do alvo devem ser observadas.
subtreeDefina como true se mutações não apenas do alvo, mas também dos descendentes do alvo devem ser observadas.
attributeOldValueDefina como true se attributes é definido como true e o valor do atributo do alvo antes da mutação precisa ser gravado.
characterDataOldValueDefina como true se characterData é definido como true e os dados do alvo antes da mutação precisam ser gravados.
attributeFilterDefina como um array de nomes locais de atributo (sem namespace) se nem todas mutações de atributo precisam ser observadas.
+ +

MutationRecord

+ +

MutationRecord é um objeto que será passado para o callback do observador. Tem as seguintes propriedades:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
typeStringRetorna attributes se a mutação foi a de um atributo, characterData se foi de um nó CharacterData, e childList se foi a mutação para uma árvore de nós.
target{{domxref("Node")}}Retorna o nó que a mutação afetou, dependendo do type. Para attributes é o elemento cujo atributo mudou. Para characterData é o nó CharacterData. Para childList é o nó cujos filhos mudaram.
addedNodes{{domxref("NodeList")}}Retorna os nós adicionados. Será uma NodeList vazia se nenhum nó foi adicionado.
removedNodes{{domxref("NodeList")}}Retorna os nós removidos. Será uma NodeList vazia se nenhum nó foi removido.
previousSibling{{domxref("Node")}}Retorna o irmão anterior dos nós adicionados ou removidos, ou null.
nextSibling{{domxref("Node")}}Retorna o próximo irmão dos nós adicionados ou removidos, ou null.
attributeNameStringRetorna o nome local do atributo modificado, ou null.
attributeNamespaceStringRetorna o namespace do atributo modificado, ou null.
oldValueStringO valor retornado depende do type. Para attributes, é o valor do atributo modificado antes da troca. Para characterData, são os dados do nó modificado antes da troca. Para childList é null.
+ +

Exemplo de uso

+ +

O exemplo a seguir foi retirado deste post.

+ +
// seleciona o nó alvo
+var target = document.querySelector('#some-id');
+
+// cria uma nova instância de observador
+var observer = new MutationObserver(function(mutations) {
+  mutations.forEach(function(mutation) {
+    console.log(mutation.type);
+  });
+});
+
+// configuração do observador:
+var config = { attributes: true, childList: true, characterData: true };
+
+// passar o nó alvo, bem como as opções de observação
+observer.observe(target, config);
+
+// mais tarde você pode parar de observar
+observer.disconnect();
+
+ +

Leitura adicional

+ + + +

Compatibilidade de browser

+ +

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

diff --git a/files/pt-br/web/api/navigation_timing_api/index.html b/files/pt-br/web/api/navigation_timing_api/index.html new file mode 100644 index 0000000000..d40f46ba45 --- /dev/null +++ b/files/pt-br/web/api/navigation_timing_api/index.html @@ -0,0 +1,153 @@ +--- +title: Navigation Timing +slug: Web/API/Navigation_timing_API +tags: + - Web Performance API +translation_of: Web/API/Navigation_timing_API +--- +

A API Navigation Timing fornece dados que podem ser usados para medir a performance de um website. Diferente de outros mecanismos baseados em Javascript que já foram usados para o mesmo propósito, esta API pode fornecer dados sobre a latência do começo ao fim que podem ser mais precisas e relevantes.

+ +

O exemplo a seguir mostra como você pode medir o tempo de carregamento percebido:

+ +
function onLoad() {
+  var now = new Date().getTime();
+  var page_load_time = now - performance.timing.navigationStart;
+  console.log("Tempo de carregamento percebido pelo usuário: " + page_load_time);
+}
+
+ +

Existem muitos eventos medidos em milisegundos que podem ser acessados através da interface {{domxref("PerformanceTiming")}} interface. A lista de eventos na ordem em que ocorrem são:

+ + + +

O objeto window.performance.navigation guarda dois atributos que podem ser usados para saber se o carregamento da página é iniciada por um redirecionamento, pelo botão voltar/avançar ou pela URL mesmo.

+ +

window.performance.navigation.type:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ConstanteValorDescrição
TYPE_NAVIGATENEXT0Navegação iniciada pelo clique em um link, ou pela entrada da URL na barra de endereços, ou envio de formulário, ou inicializada através da operação de um script diferente que os usados por TYPE_RELOAD e TYPE_BACK_FORWARD como listado abaixo.
TYPE_RELOAD1Navegação através da operação de recarregamento ou pelo método location.reload().
TYPE_BACK_FORWARD2Navegação através de uma operação de histórico.
TYPE_UNDEFINED255Qualquer tipo de navegação não definida pelos valores acima.
+ +

window.performance.navigation.redirectCount indicará, se houver, quantos redirecionamentos aconteceram até que a página final seja alcançada.

+ +

A API Navigation Timing pode ser usada para colher dados da performance do lado do cliente enviado para um servidor via XHR tanto quanto os dados medidos que eram muito dificultosos de medir de outras maneiras como o tempo de "descarga" de uma página anterior, tempo de look up do dominio, tempo total do window.onload total time, etc.

+ +

Exemplos

+ +

Calculando o tempo total necessário para carregar uma página:

+ +
var perfData = window.performance.timing;
+var pageLoadTime = perfData.loadEventEnd - perfData.navigationStart;
+
+ +

Calculando os tempos de resposta da requisição:

+ +
var connectTime = perfData.responseEnd - perfData.requestStart;
+ +

Links

+ + + +

Compatibillidade de Navegadores

+ +

{{ CompatibilityTable }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico6.0{{ CompatGeckoDesktop("7") }}915.08
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico4.0{{ CompatGeckoDesktop("15") }}915.08
+
diff --git a/files/pt-br/web/api/navigator/battery/index.html b/files/pt-br/web/api/navigator/battery/index.html new file mode 100644 index 0000000000..5ae9f207f4 --- /dev/null +++ b/files/pt-br/web/api/navigator/battery/index.html @@ -0,0 +1,40 @@ +--- +title: Navigator.battery +slug: Web/API/Navigator/battery +tags: + - API + - Battery API + - Propriedade +translation_of: Web/API/Navigator/battery +--- +

{{ ApiRef("Battery API") }}

+ +

Resumo

+ +

O objeto battery fornece informações sobre o nível de carga da bateria do sistema; você pode também escutar eventos enviados por ele que fornecem atualizações sobre o status atual da carga. Isso implementa a Battery Status API; consulte essa documentação para mais detalhes, um guia de utilização da API e códigos de exemplo.

+ +

Sintaxe

+ +
var battery = window.navigator.battery;
+ +

Valor

+ +

navigator.battery é um objeto do tipo {{domxref("BatteryManager")}}.

+ +

Especificações

+ +

{{page("/pt-BR/docs/Web/API/BatteryManager","Specifications")}}

+ +

Compatibilidade entre navegadores

+ +

{{page("/pt-BR/docs/Web/API/BatteryManager","Browser_compatibility")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/navigator/cookieenabled/index.html b/files/pt-br/web/api/navigator/cookieenabled/index.html new file mode 100644 index 0000000000..430471cb24 --- /dev/null +++ b/files/pt-br/web/api/navigator/cookieenabled/index.html @@ -0,0 +1,49 @@ +--- +title: Navigator.cookieEnabled +slug: Web/API/Navigator/cookieEnabled +translation_of: Web/API/Navigator/cookieEnabled +--- +

{{ ApiRef("HTML DOM") }}

+ +

navigator.cookieEnabled retorna um valor Booleano que indica quando cookies estão habilitados ou não. A propriedade é de apenas leitura.

+ +

Sintaxe

+ +
var cookieEnabled = navigator.cookieEnabled;
+
+ + + +

Exemplo

+ +
if (!navigator.cookieEnabled) {
+  // The browser does not support or is blocking cookies from being set.
+}
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName("HTML WHATWG", "webappapis.html#dom-navigator-cookieenabled", "Navigator.cookieEnabled")}}{{Spec2("HTML WHATWG")}}Initial definition
+ +

Compatibilidade entre navegadores

+ + + +

{{Compat("api.Navigator.cookieEnabled")}}

diff --git a/files/pt-br/web/api/navigator/devicememory/index.html b/files/pt-br/web/api/navigator/devicememory/index.html new file mode 100644 index 0000000000..9b4a48aae5 --- /dev/null +++ b/files/pt-br/web/api/navigator/devicememory/index.html @@ -0,0 +1,39 @@ +--- +title: Navigator.deviceMemory +slug: Web/API/Navigator/deviceMemory +translation_of: Web/API/Navigator/deviceMemory +--- +

{{SeeCompatTable}}{{APIRef("Device Memory")}}

+ +

A propriedade de somente-leitura deviceMemory da interface {{domxref("navigator")}} retorna a quantidade de memória do dispositivo em gigabytes. Este valor é uma aproximação por arredondamento da potência mais próxima de 2 e dividindo este número por 1024.

+ +

Sintaxe

+ +
var memory = navigator.deviceMemory
+ +

Valor

+ +

Um número de ponto flutuante.

+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('Device Memory','#sec-device-memory-js-api','deviceMemory')}}{{Spec2('Device Memory')}}Definição inicial.
+ +

Compatibilidade de navegadores

+ + + +

{{Compat("api.Navigator.deviceMemory")}}

diff --git a/files/pt-br/web/api/navigator/geolocation/index.html b/files/pt-br/web/api/navigator/geolocation/index.html new file mode 100644 index 0000000000..12cc9cbfbc --- /dev/null +++ b/files/pt-br/web/api/navigator/geolocation/index.html @@ -0,0 +1,46 @@ +--- +title: Navigator.geolocation +slug: Web/API/Navigator/geolocation +translation_of: Web/API/Navigator/geolocation +--- +
{{APIRef("Geolocation API")}}
+ +

A propriedade de apenas leitura Navigator.geolocation retorna um objeto {{domxref("Geolocation")}} que disponibiliza acesso de conteúdo Web à localização do dispositivo. Isso permite que um Web site ou aplicativo ofereçam resultados customizados baseado na localização do usuário.

+ +
+

Nota: Por questão de segurança, quando uma página web tenta acessar as informações de localização, o usuário é notificado e lhe é perguntado se este garante permissão. Esteja alerta que cada navegador possui suas próprias políticas e métodos para requisitar permissão.

+
+ +

Sintaxe

+ +
geo = navigator.geolocation
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoSituaçãoComentário
{{SpecName('Geolocation', '#navi-geo', 'Navigator.geolocation')}}{{Spec2('Geolocation')}}Definição inicial
+ +

Compatibilidade de navegador

+ +

{{Compat("api.Navigator.geolocation")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/navigator/getusermedia/index.html b/files/pt-br/web/api/navigator/getusermedia/index.html new file mode 100644 index 0000000000..4df2f528d4 --- /dev/null +++ b/files/pt-br/web/api/navigator/getusermedia/index.html @@ -0,0 +1,184 @@ +--- +title: navigator.getUserMedia +slug: Web/API/Navigator/getUserMedia +translation_of: Web/API/Navigator/getUserMedia +--- +

{{APIRef("Media Capture and Streams")}}{{deprecated_header}}

+ +

O método Navigator.getUserMedia() atualmente esta deprecated (obseleto), ele é responsavel por pedir a permissão do usuário para usar até 1 dispositivo de entrada de vídeo (como câmera, ou tela compartilhada) e até 1 dispositivo de entrada de áudio (como o microfone) como fonte para o stream de mídia (pode ser representado por uma instância MediaStream).

+ +

Se o usuário der permissão, a MediaStream (o track do video e/ou audio) , é entregue ao callback de sucesso, se a permissão é negada, pode ser que não haja dispositivo compatível ou alguma condição de erro aconteceu, retornando o callback de erro com uma instancia do objeto   {{domxref("MediaStreamError")}} , com a descrição do erro que aconteceu, se o usuário não fizer nenhuma escolha, nenhum callback é retornado.

+ +

Sintaxe

+ +
navigator.getUserMedia ( permissoes, callbackSucesso, callbackErro );
+ +

Exemplo

+ +

Este é um exemplo de uso da função getUserMedia() com prefixos específicos dos navegadores.

+ +
navigator.getMedia = ( navigator.getUserMedia ||
+                       navigator.webkitGetUserMedia ||
+                       navigator.mozGetUserMedia ||
+                       navigator.msGetUserMedia);
+
+navigator.getMedia (
+
+   // permissoes
+   {
+      video: true,
+      audio: true
+   },
+
+   // callbackSucesso
+   function(localMediaStream) {
+      var video = document.querySelector('video');
+      video.src = window.URL.createObjectURL(localMediaStream);
+      video.onloadedmetadata = function(e) {
+         // Faz algo com o vídeo aqui.
+      };
+   },
+
+   // callbackErro
+   function(err) {
+    console.log("O seguinte erro ocorreu: " + err);
+   }
+
+);
+ +

Parâmetros

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
parâmetroObrigatório/ 
+ Opcional 
Descrição
permissoesObrigatórioOs tipos de mídia habilitados no objeto LocalMediaStream enviado para a callbackSucesso.
callbackSucessoObrigatórioA função da aplicação a ser invocada para receber o objeto LocalMediaStream.
callbackErroOpcionalA função a ser invocada na aplicação se a chamada a getUserMedia falhar.
+ +

permissoes

+ +

O parâmetro permissoes é um objeto MediaStreamConstraints com dois membros do tipo Boolean: video e audio. Estes membros descrevem os tipos de mídia habilitados no objeto LocalMediaStream. Pelo menos um destes membros deve ser especificado para que o argumento seja validado. Se um membro especificado não for suportado pelo navegador, a função getUserMedia invocará a callbackErro com o erro NOT_SUPPORTED_ERROR. Se o navegador não puder encontrar nenhuma fonte de mídia com o tipo especificado, a função getUserMedia invocará a callbackErro com o erro MANDATORY_UNSATISFIED_ERR.

+ +

Se o valor de um membro não estiver especificado no objeto, o valor padrão deste membro será falso. Veja como configurar o objeto permissoes para obter tanto áudio como vídeo:

+ +
{ video: true, audio: true }
+ +

callbackSucesso

+ +

A função getUserMedia invocará a função especificada em callbackSucesso com o objeto LocalMediaStream que contém a fonte de mídia. Você pode associar este objeto com o elemento apropriado e trabalhar com ele, como mostrado no exemplo a seguir:

+ +
function(localMediaStream) {
+   var video = document.querySelector('video');
+   video.src = window.URL.createObjectURL(localMediaStream);
+   video.onloadedmetadata = function(e) {
+      // Faz algo com o vídeo aqui.
+   };
+},
+ +

callbackErro

+ +

A função getUserMedia invocará a função especificada em callbackErro com um argumento code. Os códigos de erro são descritos abaixo:

+ + + + + + + + + + + + + + + + + + + + + + +
ErroDescrição
PERMISSION_DENIED O usuário não permitiu acesso a um dispositivo de mídia necessário para essa operação. 
NOT_SUPPORTED_ERROR Uma mídia especificada não é suportada pelo navegador.
MANDATORY_UNSATISFIED_ERROR Nenhuma fonte de mídia do tipo especificado foi encontrada.
+ +

Compatibilidade de navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Stream API 21{{property_prefix("webkit")}} 20{{property_prefix("moz")}} {{CompatNo}} 12{{CompatUnknown}} 
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FuncionalidadeAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Stream API {{CompatNo}} {{CompatNo}}{{CompatUnknown}} 12{{CompatNo}} 
+
+ +

Atualmente, usar o WebRTC para acessar a câmera de vídeo é suportado nos navegadores Chrome, Opera e Firefox 20.

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/navigator/index.html b/files/pt-br/web/api/navigator/index.html new file mode 100644 index 0000000000..6ef2055b7a --- /dev/null +++ b/files/pt-br/web/api/navigator/index.html @@ -0,0 +1,119 @@ +--- +title: Navigator +slug: Web/API/Navigator +translation_of: Web/API/Navigator +--- +

{{ apiref() }}

+ +

The Navigator interface represents the state and the identity of the user agent. It allows scripts to query it and to register themselves to carry on some activities.

+ +

A Navigator object can be retrieved using the read-only {{domxref("Window.navigator")}} property.

+ +

Properties

+ +

Doesn't inherit any property, but implements those defined in {{domxref("NavigatorID")}}, {{domxref("NavigatorLanguage")}}, {{domxref("NavigatorOnLine")}}, {{domxref("NavigatorGeolocation")}}, {{domxref("NavigatorPlugins")}}, {{domxref("NavigatorUserMedia")}}, and {{domxref("NetworkInformation")}}.

+ +

Standard

+ +
+
{{domxref("NavigatorID.appCodeName")}} {{readonlyInline}}{{experimental_inline}}
+
Returns the internal "code" name of the current browser. Do not rely on this property to return the correct value.
+
{{domxref("NavigatorID.appName")}} {{readonlyInline}}{{experimental_inline}}
+
Returns a {{domxref("DOMString")}} with the official name of the browser. Do not rely on this property to return the correct value.
+
{{domxref("NavigatorID.appVersion")}} {{readonlyInline}}{{experimental_inline}}
+
Returns the version of the browser as a {{domxref("DOMString")}}. Do not rely on this property to return the correct value.
+
{{domxref("Navigator.battery")}} {{readonlyInline}}
+
Returns a {{domxref("BatteryManager")}} object you can use to get information about the battery charging status.
+
{{domxref("NetworkInformation.connection")}} {{readonlyInline}}{{experimental_inline}}
+
Provides a {{domxref("Connection")}} with information about the network connection of a device.
+
{{domxref("NavigatorGeolocation.geolocation")}} {{readonlyInline}}
+
Returns a {{domxref("Geolocation")}} object allowing accessing the location of the device.
+
{{domxref("NavigatorPlugins.javaEnabled")}} {{readonlyInline}}{{experimental_inline}}
+
Returns a {{domxref("Boolean")}} flag indicating whether the host browser is Java-enabled or not.
+
{{domxref("NavigatorLanguage.language")}} {{readonlyInline}}
+
Returns a {{domxref("DOMString")}} representing the preferred language of the user, usually the language of the browser UI. The null value is returned when this is unknown.
+
{{domxref("NavigatorLanguage.languages")}} {{readonlyInline}}
+
Returns an array of {{domxref("DOMString")}} representing the languages known to the user, by order of preference.
+
{{domxref("NavigatorPlugins.mimeTypes")}} {{readonlyInline}}{{experimental_inline}}
+
Returns an {{domxref("MimeTypeArray")}} listing the MIME types supported by the browser.
+
{{domxref("NavigatorOnLine.onLine")}} {{readonlyInline}}
+
Returns a {{domxref("Boolean")}} indicating whether the browser is working online.
+
{{domxref("Navigator.oscpu")}}
+
Returns a string that represents the current operating system.
+
{{domxref("NavigatorID.platform")}} {{readonlyInline}}{{experimental_inline}}
+
Returns a string representing the platform of the browser. Do not rely on this function to return a significant value.
+
{{domxref("NavigatorPlugins.plugins")}} {{readonlyInline}}{{experimental_inline}}
+
Returns a {{domxref("PluginArray")}} listing the plugins installed in the browser.
+
{{domxref("NavigatorID.product")}} {{readonlyInline}} {{experimental_inline}}
+
Always returns 'Gecko', on any browser. This property is kept only for compatibility purpose.
+
{{domxref("NavigatorID.userAgent")}} {{readonlyInline}}
+
Returns the user agent string for the current browser.
+
{{domxref("Navigator.serviceWorker")}} {{readonlyInline}}
+
Returns a {{domxref("ServiceWorkerContainer")}} object, which provides access to registration, removal, upgrade, and communication with the {{domxref("ServiceWorker")}} objects for the associated document.
+
+ +

Non-standard

+ +
+
{{domxref("window.navigator.buildID", "navigator.buildID")}} {{non-standard_inline}}
+
Returns the build identifier of the browser (e.g., "2006090803").
+
{{domxref("Navigator.cookieEnabled")}} {{non-standard_inline}}
+
Returns a boolean indicating whether cookies are enabled in the browser or not.
+
{{domxref("navigator.doNotTrack")}} {{non-standard_inline}}
+
Reports the value of the user's do-not-track preference. When this value is "yes", your web site or application should not track the user.
+
{{domxref("navigator.id")}} {{non-standard_inline}}
+
Returns the {{domxref("window.navigator.id", "id")}} object which you can use to add support for BrowserID to your web site.
+
{{domxref("window.navigator.mozApps", "navigator.mozApps")}} {{non-standard_inline}}
+
Returns an {{domxref("window.navigator.mozApps", "Apps")}} object you can use to install, manage, and control Open Web apps.
+
{{domxref("Navigator.mozAudioChannelManager", "navigator.mozAudioChannelManager")}} {{non-standard_inline}}
+
The navigator.mozAudioChannelManager object provides access to the {{domxref("mozAudioChannelManager")}} interface, which is used to manage your Firefox OS device's audio channels, including setting what channel's volume to affect when the volume buttons are pressed inside a particular app.
+
{{domxref("window.navigator.mozNotification","navigator.mozNotification")}} {{deprecated_inline("22")}} {{non-standard_inline}}
+ {{domxref("window.navigator.webkitNotification","navigator.webkitNotification")}}
+
Returns a {{domxref("navigator.mozNotification", "notification")}} object you can use to deliver notifications to the user from your web application.
+
{{domxref("navigator.mozSocial")}} {{non-standard_inline}}
+
The Object, returned by the navigator.mozSocial property, is available within the social media provider's panel to provide functionality it may need.
+
{{domxref("window.navigator.productSub", "navigator.productSub")}} {{non-standard_inline}}
+
Returns the build number of the current browser (e.g., "20060909").
+
{{domxref("window.navigator.securitypolicy", "navigator.securitypolicy")}} {{non-standard_inline}}
+
Returns an empty string. In Netscape 4.7x, returns "US & CA domestic policy" or "Export policy".
+
{{domxref("window.navigator.standalone", "navigator.standalone")}} {{non-standard_inline}}
+
Returns a boolean indicating whether the browser is running in standalone mode. Available on Apple's iOS Safari only.
+
{{domxref("window.navigator.vendor", "navigator.vendor")}} {{non-standard_inline}}
+
Returns the vendor name of the current browser (e.g., "Netscape6").
+
{{domxref("window.navigator.vendorSub", "navigator.vendorSub")}} {{non-standard_inline}}
+
Returns the vendor version number (e.g. "6.1").
+
navigator.webkitPointer {{non-standard_inline}}
+
Returns a PointerLock object for the Mouse Lock API.
+
+ +

Methods

+ +

Doesn't inherit any method, but implements those defined in {{domxref("NavigatorID")}}, {{domxref("NavigatorContentUtils")}}, {{domxref("NavigatorUserMedia")}}, and {{domxref("NavigatorStorageUtils")}}.

+ +

Standard

+ +
+
{{domxref("NavigatorUserMedia.getUserMedia()")}}
+
After having prompted the user for permission, returns the audio or video stream associated to a camera or microphone on the local computer.
+
{{domxref("window.navigator.registerContentHandler", "navigator.registerContentHandler")}}
+
Allows web sites to register themselves as a possible handler for a given MIME type.
+
{{domxref("navigator.registerProtocolHandler", "navigator.registerProtocolHandler")}}
+
Allows web sites to register themselves as a possible handler for a given protocol.
+
{{domxref("NavigatorID.taintEnabled()")}} {{deprecated_inline("1.7.8")}} {{obsolete_inline("9.0")}} {{experimental_inline}}
+
Returns false. JavaScript taint/untaint functions removed in JavaScript 1.2.
+
{{domxref("Navigator.vibrate()")}} {{gecko_minversion_inline("11.0")}}
+
Causes vibration on devices with support for it. Does nothing if vibration support isn't available.
+
+ +

Non standard

+ +
+
{{domxref("window.navigator.mozIsLocallyAvailable", "navigator.mozIsLocallyAvailable")}} {{non-standard_inline}}
+
Lets code check to see if the document at a given URI is available without using the network.
+
{{domxref("window.navigator.mozPay", "navigator.mozPay")}} {{non-standard_inline}}
+
Allows in-app payment.
+
{{domxref("window.navigator.preference", "navigator.preference")}} {{obsolete_inline("2.0")}} {{non-standard_inline}}
+
Sets a user preference. This method is only available to privileged code and is obsolete; you should use the XPCOM Preferences API instead.
+
{{domxref("window.navigator.requestWakeLock", "navigator.requestWakeLock")}} {{non-standard_inline}}
+
Request a wake lock for a resource. A wake lock prevents a specific part of a device from being turned off automatically.
+
diff --git a/files/pt-br/web/api/navigator/share/index.html b/files/pt-br/web/api/navigator/share/index.html new file mode 100644 index 0000000000..ce6640ada2 --- /dev/null +++ b/files/pt-br/web/api/navigator/share/index.html @@ -0,0 +1,87 @@ +--- +title: Navigator.share() +slug: Web/API/Navigator/share +translation_of: Web/API/Navigator/share +--- +
{{APIRef("HTML DOM")}}{{securecontext_header}}
+ +

O método navigator.share() da API de compartilhamento da Web chama o mecanismo de compartilhamento nativo do dispositivo.

+ +

Sintaxe

+ +
var sharePromise = navigator.share(data);
+
+ +

Parâmetros

+ +
+
data
+
Um objeto que contém dados para compartilhar. Pelo menos um dos seguintes campos deve ser especificado. As opções disponíveis são:
+
+ + + +
+
+ +

Valor de retorno

+ +

Um {{domxref ("Promise")}} que será cumprido assim que um usuário concluir uma ação de compartilhamento (geralmente o usuário escolheu um aplicativo para compartilhar). Ele rejeitará imediatamente se o parâmetro de dados não estiver especificado corretamente e também rejeitará se o usuário cancelar o compartilhamento.

+ +

Exemplos

+ +

Em nosso teste de compartilhamento na Web (consulte o código-fonte), há um botão que, quando clicado, invoca a API de compartilhamento na Web para compartilhar o URL da MDN. O JavaScript fica assim:

+ +
const shareData = {
+  title: 'MDN',
+  text: 'Aprenda desenvolvimento web no MDN!',
+  url: 'https://developer.mozilla.org',
+}
+
+const btn = document.querySelector('button');
+const resultPara = document.querySelector('.result');
+
+// Deve ser acionado algum tipo de "ativação do usuário"
+btn.addEventListener('click', async () => {
+  try {
+    await navigator.share(shareData)
+  } catch(err) {
+    resultPara.textContent = 'Error: ' + e
+  }
+  resultPara.textContent = 'MDN compartilhado com sucesso!'
+});
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComment
{{SpecName('Web Share API','#share-method','share()')}}{{Spec2('Web Share API')}}
+ +

Compatibilidade do navegador

+ + + +

{{Compat("api.Navigator.share")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/navigatorid/index.html b/files/pt-br/web/api/navigatorid/index.html new file mode 100644 index 0000000000..c56f1e1b81 --- /dev/null +++ b/files/pt-br/web/api/navigatorid/index.html @@ -0,0 +1,120 @@ +--- +title: NavigatorID +slug: Web/API/NavigatorID +translation_of: Web/API/NavigatorID +--- +

{{APIRef("HTML DOM")}}

+ +

The NavigatorID interface contains methods and properties related to the identity of the browser.

+ +

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

+ +

Properties

+ +

The NavigatorID interface doesn't inherit any property.

+ +
+
{{domxref("NavigatorID.appCodeName")}} {{readonlyInline}}{{deprecated_inline}}
+
Always returns 'Mozilla', on any browser. This property is kept only for compatibility purpose.
+
{{domxref("NavigatorID.appName")}} {{readonlyInline}} {{deprecated_inline}}
+
Returns the official name of the browser. Do not rely on this property to return the correct value.
+
{{domxref("NavigatorID.appVersion")}} {{readonlyInline}} {{deprecated_inline}}
+
Returns the version of the browser as a string. Do not rely on this property to return the correct value.
+
{{domxref("NavigatorID.platform")}} {{readonlyInline}} {{deprecated_inline}}
+
Returns a string representing the platform of the browser. Do not rely on this property to return the correct value.
+
{{domxref("NavigatorID.product")}} {{readonlyInline}} {{deprecated_inline}}
+
Always returns 'Gecko', on any browser. This property is kept only for compatibility purpose.
+
{{domxref("NavigatorID.userAgent")}} {{readonlyInline}}
+
Returns the user agent string for the current browser.
+
+ +

Methods

+ +

The NavigatorID interface doesn't inherit any method.

+ +
+
{{domxref("NavigatorID.taintEnabled()")}} {{deprecated_inline()}}
+
Always returns false. JavaScript taint/untaint functions were removed in JavaScript 1.2. This method is only kept for compatibility purpose
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#navigatorid', 'NavigatorID')}}{{Spec2('HTML WHATWG')}}Added the appCodeName property and the taintEnabled() method,  for compatibility purpose.
{{SpecName('HTML5 W3C', '#navigatorid', 'NavigatorID')}}{{Spec2('HTML5 W3C')}}Initial specification.
+ +

Browser compatibility

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

See also

+ + diff --git a/files/pt-br/web/api/navigatorid/platform/index.html b/files/pt-br/web/api/navigatorid/platform/index.html new file mode 100644 index 0000000000..590d9bd515 --- /dev/null +++ b/files/pt-br/web/api/navigatorid/platform/index.html @@ -0,0 +1,63 @@ +--- +title: NavigatorID.platform +slug: Web/API/NavigatorID/platform +tags: + - API + - DOM + - DOM_0 + - Gecko + - HTML5 + - Propriedade + - Referencia + - Referência(2) +translation_of: Web/API/NavigatorID/platform +--- +

{{ ApiRef("HTML DOM") }}

+ +

Retorna uma string representando a plataforma do navegador. A especificação permite aos navegadores retornar sempre strings vazias, portanto não se utilize dessa propriedade para obter resultados confiáveis.

+ +

Sintaxe

+ +
plataforma = navigator.platform
+
+ +

Valor

+ +

Uma {{domxref("DOMString")}} identificando a plataforma na qual o navegador está sendo executado, ou uma string vazia se o browser se negar a (ou for incapaz de) identificar a plataforma. plataforma é uma string que pode estar vazia ou representar a plataforma na qual o navegador está sendo executado.

+ +

Por exemplo: "MacIntel", "Win32", "FreeBSD i386", "WebTV OS"

+ +

Exemplo

+ +
console.log(navigator.platform);
+ +

Notas

+ +

Na maioria dos browsers, incluindo Chrome, Edge e Firefox 63 em diante, NavegatorID.platform retorna "Win32", mesmo que o browser seja executado em uma versão 64-bit do Windows. No Internet Explorer e em versões do Firefox anteriores à versão 63, a propriedade ainda retorna "Win64".

+ +

No Firefox, a preferência general.platform.override pode ser usada para sobrepor o valor de retorno padrão dessa propriedade.

+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG', '#dom-navigator-platform', 'NavigatorID.platform')}}{{Spec2('HTML WHATWG')}}Definição inicial.
+ +

Compatibilidade

+ + + +

{{Compat("api.NavigatorID.platform")}}

diff --git a/files/pt-br/web/api/navigatorid/useragent/index.html b/files/pt-br/web/api/navigatorid/useragent/index.html new file mode 100644 index 0000000000..c5e6211724 --- /dev/null +++ b/files/pt-br/web/api/navigatorid/useragent/index.html @@ -0,0 +1,89 @@ +--- +title: NavigatorID.userAgent +slug: Web/API/NavigatorID/userAgent +tags: + - API + - Descontinuado + - Propriedade + - Referencia + - Somente Leitura +translation_of: Web/API/NavigatorID/userAgent +--- +

{{ApiRef("HTML DOM")}}

+ +

A propriedade read-only (apenas leitura) NavigatorID.userAgent retorna a string do agente do usuário (user agent) para o browser atual.

+ +
+

 A especifícação demanda que os navegadores forneçam, nessa propriedade, a menor quantidade de informações posssível. Nunca assuma que o valor dessa propriedade permanecerá o mesmo em verções futuras de um mesmo navegador. Tente não utiliza-la, ou ultileze-a somente para verções presentes ou passadas de um navegador. Novos navegadores podem utilizar-se do mesmo agente do usuário, ou parte dele, que navegadores mais aintigos: não existe qualquer garantia de que o agente do navegador é de fato o enunciado por essa propriedade.
+
+ Além disso, tenha em mente que os usuários do navegador podem manipular o valor dessa propriedade caso queiram (UA spoofing).

+
+ +

A idenficação de browsers baseada na detecção de sua string de agente de usuário não é confiável e não é recomendável, pois a string de agente de usuário pode ser configurada pelo usuário. Por exemplo:

+ + + +

Sintaxe

+ +
var au = window.navigator.userAgent;
+
+ +

Valor

+ +

au guarda o valor da string de agente de usuário do browser atual.

+ +

A string de agente de usuário é contruida em uma estrutura formal que pode ser decomposta em diferentes informações. Cada uma dessas informações é provinda de outras propriedades de window.navigator, que também podem ser configuradas pelo usuário. Navegadores baseados na engine Gecko seguem a seguinte estrutura:

+ +
ageteDeUsuário = códigoDoNomeDoAplicativo/versãoDoAplicativo número (Plataforma; Segurança; OS-ou-CPU;
+Localização; rv: número-da-verção-de-revisão) produto/produtoSub
+Nome-do-Aplicativo versão-do-Nome-do-Aplicativo
+
+ +

Examplo

+ +
alert(window.navigator.userAgent)
+// alerta "Mozilla/5.0 (Windows; U; Win98; en-US; rv:0.9.2) Gecko/20010725 Netscape6/6.1"
+
+ + + +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG', '#dom-navigator-useragent', 'NavigatorID.userAgent')}}{{Spec2('HTML WHATWG')}}Definição inicial.
+ +

Compatibilidade

+ + + +

{{Compat("api.NavigatorID.userAgent")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/navigatorlanguage/index.html b/files/pt-br/web/api/navigatorlanguage/index.html new file mode 100644 index 0000000000..7d6b0751e7 --- /dev/null +++ b/files/pt-br/web/api/navigatorlanguage/index.html @@ -0,0 +1,148 @@ +--- +title: NavigatorLanguage +slug: Web/API/NavigatorLanguage +tags: + - API + - HTML-DOM + - NeedsTranslation + - No Interface + - Reference + - TopicStub +translation_of: Web/API/NavigatorLanguage +--- +

{{APIRef("HTML DOM")}}

+ +

NavigatorLanguage contains methods and properties related to the language of the navigator.

+ +

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

+ +

Properties

+ +

The NavigatorLanguage interface doesn't inherit any property.

+ +
+
{{domxref("NavigatorLanguage.language")}} {{readonlyInline}}
+
Returns a {{domxref("DOMString")}} representing the preferred language of the user, usually the language of the browser UI. The null value is returned when this is unknown.
+
{{domxref("NavigatorLanguage.languages")}} {{readonlyInline}}
+
Returns an array of {{domxref("DOMString")}} representing the languages known to the user, by order of preference.
+
+ +

Methods

+ +

The NavigatorLanguage interface neither implements, nor inherit any method.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#navigatorlanguage', 'NavigatorLanguage')}}{{Spec2('HTML WHATWG')}}Since the {{SpecName('HTML5 W3C')}} snapshot, the languages property has been added.
{{SpecName('HTML5 W3C', '#navigatorlanguage', 'NavigatorLanguage')}}{{Spec2('HTML5 W3C')}}Initial specification; snapshot of  an early version{{SpecName('HTML WHATWG')}}.
+ +

Browser compatibility

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
languages37{{CompatGeckoDesktop("32")}}{{CompatNo}}24{{CompatNo}}
on {{domxref("WorkerNavigator")}}{{CompatUnknown}}{{CompatGeckoDesktop("35")}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
languages{{CompatUnknown}}{{CompatUnknown}} {{CompatGeckoMobile("32")}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
on {{domxref("WorkerNavigator")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("35")}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
+
+ +

See also

+ + diff --git a/files/pt-br/web/api/navigatorlanguage/language/index.html b/files/pt-br/web/api/navigatorlanguage/language/index.html new file mode 100644 index 0000000000..c29fe80ac0 --- /dev/null +++ b/files/pt-br/web/api/navigatorlanguage/language/index.html @@ -0,0 +1,131 @@ +--- +title: NavigatorLanguage.language +slug: Web/API/NavigatorLanguage/language +translation_of: Web/API/NavigatorLanguage/language +--- +
{{APIRef("HTML DOM")}}
+ +

A propriedade NavigatorLanguage.language retorna uma string representando a língua de preferência do usuário, normalmente a língua da interface do navegador.

+ +

Sintaxe

+ +
var lang = navigator.language
+
+ +

Valor

+ +

Uma {{domxref("DOMString")}} lang armazena a string representando a língua como definida em BCP 47. Exemplos de códigos de línguas válidos incluem "en", "en-US", "fr", "fr-FR", "es-ES", etc.

+ +

Atente-se que no Safari no macOS e iOS antes da versão 10.2, o código do país é retornado em caixa baixa: "en-us", "fr-fr" etc.

+ +

Exemplo

+ +
if (window.navigator.language != 'en') {
+  doLangSelect(window.navigator.language);
+}
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComentários
{{ SpecName('HTML5.1', '#dom-navigator-language', 'NavigatorLanguage.language') }}{{ Spec2('HTML5.1') }}Definição inicial
+ +

Compatibilidade com navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}[1]{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.0")}}[2]
+ {{CompatGeckoDesktop("5.0")}}[3]
11.0[4]{{CompatVersionUnknown}}{{CompatVersionUnknown}}
on {{domxref("WorkerNavigator")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop("35")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile(1.0)}}{{CompatNo}}[4]{{CompatVersionUnknown}}{{CompatVersionUnknown}}
on {{domxref("WorkerNavigator")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop("35")}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Retorna a língua da interface do browser, não o valor do HTTP header Accept-Language .

+ +

[2] Antes do Gecko 2.0 {{geckoRelease("2.0")}}, o valor dessa propriedade também fazia parte da string de user agent, como reportado em {{domxref("window.navigator.userAgent", "navigator.userAgent")}}.

+ +

[3] Começando no Gecko 5.0 {{geckoRelease("5.0")}}, o valor dessa propriedade é baseado no valor do HTTP header Accept-Language.

+ +

[4] As propriedades (não padronizadas) mais próximas disponíveis são userLanguage e browserLanguage.

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/navigatoronline/index.html b/files/pt-br/web/api/navigatoronline/index.html new file mode 100644 index 0000000000..6e5118c62b --- /dev/null +++ b/files/pt-br/web/api/navigatoronline/index.html @@ -0,0 +1,134 @@ +--- +title: NavigatorOnLine +slug: Web/API/NavigatorOnLine +tags: + - API + - HTML-DOM +translation_of: Web/API/NavigatorOnLine +--- +

{{APIRef("HTML DOM")}}

+ +

A interface NavigatorOnLine contém métodos e propriedades relacionados ao status de conectividade do navegador.

+ +

Não há objetosdo tipo NavigatorOnLine, mas há outras interfaces, como {{domxref("Navigator")}} ou {{domxref("WorkerNavigator")}} que o implementa.

+ +

Propriedades

+ +

A interface NavigatorOnLine não herda nenhuma propriedade.

+ +

 

+ +
+
{{domxref("NavigatorOnLine.onLine")}} {{readonlyInline}}
+
Retorna um {{domxref("Boolean")}} indicando se o browser está online.
+
+ +

Métodos

+ +

A interface NavigatorOnLine não implementa nem herda nenhum método.

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG', '#navigatoronline', 'NavigatorOnLine')}}{{Spec2('HTML WHATWG')}}Nenhuma mudança desde a ultima atualização, do {{SpecName('HTML5 W3C')}}
{{SpecName('HTML5 W3C', '#navigatoronline', 'NavigatorOnLine')}}{{Spec2('HTML5 W3C')}}Snapshot do {{SpecName('HTML WHATWG')}} com sua especificação inicial
+ +

Compatibilidade de navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
on {{domxref("WorkerNavigator")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop(29)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome para AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
on {{domxref("WorkerNavigator")}}{{CompatUnknown}}{{CompatGeckoMobile(29)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/navigatoronline/online/index.html b/files/pt-br/web/api/navigatoronline/online/index.html new file mode 100644 index 0000000000..acaed23e82 --- /dev/null +++ b/files/pt-br/web/api/navigatoronline/online/index.html @@ -0,0 +1,91 @@ +--- +title: Navigator.onLine +slug: Web/API/NavigatorOnLine/onLine +tags: + - API + - DOM Reference + - NavigatorOnLine + - Offline + - Online + - Propriedade + - Referencia +translation_of: Web/API/NavigatorOnLine/onLine +--- +
{{ApiRef("HTML DOM")}}
+ +

Retorna o estado da conexão do navegador. A propriedade retorna um valor booleano, com true significando online e false significando offline. A propriedade envia atualizações assim que a capacidade do navegador de se conectar a rede muda. A atualização ocorre quando o usuário entra em um link ou quando algum script faz uma requisição a uma página remota. Exemplo, a propriedade deve retornar false quando usuários clicam em links assim que perderem suas conexões com a internet.

+ +

Navegadores implementam esta propriedade de formas diferentes.

+ +

No Chrome e Safari, caso o navegador não for capaz de se conectar a uma rede local (LAN) ou a um roteador, ele está offline; em todas as outras condições, retorna true. Utilizar essa propriedade para determinar que o navegador está offline seja sempre que o navegador retornar false como valor pode gerar falsos positivos, em casos em que o computador está executando um software de virtualização que tem adaptadores de ethernet virtuais que sempre estão "conectados." ou quando o computador estiver conectado ao roteador e este estiver sem internet. Se você realmente quer determinar o estado da conexão do navegador, você deve desenvolver meios adicionais para esta verificação. Para aprender mais, veja o artigo do HTML5 Rocks, Working Off the Grid.

+ +

No Firefox e Internet Explorer, mudar o navegador para o modo offline envia um valor false. Até o Firefox 41, todas as outras condições retornam um valor true; desde o Firefox 41, no OS X e Windows, o valor seguirá a conectividade real da rede.

+ +

Você pode ver mudanças no estado da rede escutando os eventos window.ononline e window.onoffline.

+ +

Sintaxe

+ +
online = window.navigator.onLine;
+
+ +

Valor

+ +

online é um booleano true ou false.

+ +

Exemplo

+ +

Veja  um exemplo ao-vivo.

+ +

Para verificar se você está online, chame window.navigator.onLine, como no exemplo abaixo:

+ +
if (navigator.onLine) {
+  console.log('online');
+} else {
+  console.log('offline');
+}
+ +

Caso o navegador não suporta o exemplo de navigator.onLine acima, ele sempre retornará false/undefined.

+ +

Para ver mudanças no estado da rede, use addEventListener para escutar os eventos em window.online e window.offline, como no exemplo abaixo:

+ +
window.addEventListener('offline', function(e) { console.log('offline'); });
+
+window.addEventListener('online', function(e) { console.log('online'); });
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçõesStatusComentário
{{SpecName("HTML WHATWG", "browsers.html#dom-navigator-online", "navigator.onLine")}}{{Spec2("HTML WHATWG")}}Definição inicial
+ +

Compatibilidade com os navegadores

+ + + +

{{Compat("api.NavigatorOnLine.onLine")}}

+ +

Notas

+ +

Veja s eventos Online/Offline para descrições mais detalhadas desta propriedade assim como novas funcionalidades offline introduzidas no Firefox 3.

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/navigatoronline/online_and_offline_events/index.html b/files/pt-br/web/api/navigatoronline/online_and_offline_events/index.html new file mode 100644 index 0000000000..e12a1fc649 --- /dev/null +++ b/files/pt-br/web/api/navigatoronline/online_and_offline_events/index.html @@ -0,0 +1,99 @@ +--- +title: Eventos on-line e off-line +slug: Web/API/NavigatorOnLine/Online_and_offline_events +translation_of: Web/API/NavigatorOnLine/Online_and_offline_events +--- +

IAlguns navegadores utilizam Online/Offline events relacionados à WHATWG Web Applications 1.0 specification.

+ +

Introdução

+ +

Para criar um bom aplicativo off-line, primeiramente é necessário que você saiba quando o aplicativo está off-line. Consequentemente, você também precisará saber quando seu aplicativo retorna ao estado on-line novamente, ou seja, os eventos são:

+ +
    +
  1. Você precisa saber quando o usuário está on-line novamente, assim você pode sincronizar novamente com o servidor.
  2. +
  3. Você precisa saber quando o usuário está off-line, então você deverá agendar os acessos ao servidor para mais tarde.
  4. +
+ +

Este é o processo que os eventos on-line/off-line ajudam a facilitar.

+ +

Seu aplicativo também poderá precisar estabelecer que certos documentos deverão ser mantidos em um cache off-line. Você pode saber mais sobre isso no artigo Offline resources in Firefox.

+ +

API

+ + + +

navigator.onLine é uma propriedade que mantém valores true/false (true para on-line, false para off-line). Esta propriedade é atualizada quando o usuário entra em "Modo Off-line" clicando no item de menu correspondente (Arquivo -> Modo Off-line).

+ +

Essa propriedade também deverá ser atualizada toda vez que o navegador perde a conexão com a Internet. De acordo com a especificação:

+ +
A propriedade navigator.onLine deve retornar false se o usuário clicar num link ou se um aplicativo tentar contatar uma página remota e não estiver conectado à Internet ou se o navegador souber que a tentativa irá falhar por qualquer motivo...
+ +

O Firefox 2 atualiza esta propriedade quando se entra em Modo Off-line ou sai do mesmo e também quando a conexão com a Internet é perdida ou reestabelecida no Windows e no Linux.

+ +

Essa propriedade existiu em versões mais antigas do Firefox e do Internet Explorer (a especificação acima foi baseada nestas implementações anteriores), então você pode começar a utilizá-la imediatamente. A auto-detecção de estado de rede foi implementada no Firefox 2.

+ +

Eventos "on-line" e "off-line"

+ +

O Firefox 3 implementou dois novos eventos: "on-line" e "off-line". Estes dois eventos são chamados na tag <body> de cada página quando o navegador muda entre os modos on e off-line. Também, esses eventos são propagados a partir do document.body, para document, terminando em window. Ambos eventos não podem ser interrompidos (você não pode prevenir que o usuário fique on-line ou off-line).

+ +

Você pode resgistrar listeners para esses eventos em caminhos conhecidos:

+ + + +

Example

+ +

a simple test case que você pode rodar para ver como esses eventos funcionam. XXX Quando os testes para isso forem criados, redirecione para eles e atualize 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>
+
+ +

Notas

+ +

Se a API não estiver implementada no navegador, você pode usar outros sinais para detectar quando se está off-line, inclusive receber AppCache error events e responses from XMLHttpRequest.

+ +

Referências

+ + + +

{{ HTML5ArticleTOC() }}

+ +

{{ languages( { "es": "es/Eventos_online_y_offline", "fr": "fr/\u00c9v\u00e8nements_online_et_offline", "ja": "ja/Online_and_offline_events", "pl": "pl/Zdarzenia_online_i_offline", "pt": "pt/Eventos_online_e_offline" } ) }}

diff --git a/files/pt-br/web/api/navigatorplugins/index.html b/files/pt-br/web/api/navigatorplugins/index.html new file mode 100644 index 0000000000..ddcc629eb8 --- /dev/null +++ b/files/pt-br/web/api/navigatorplugins/index.html @@ -0,0 +1,69 @@ +--- +title: NavigatorPlugins +slug: Web/API/NavigatorPlugins +tags: + - API + - DOM + - Experimental + - HTML + - Interface + - Navigation + - NavigatorPlugins + - Plugins + - Reference +translation_of: Web/API/NavigatorPlugins +--- +

{{APIRef("HTML DOM")}}{{SeeCompatTable}}

+ +

O NavigatorPlugins {{Glossary("mixin")}} adiciona na interface do {{domxref ("Navigator")}} métodos e propriedades para descobrir e interagir com plugins instalados no navegador.

+ +

 

+ +

Propriedades

+ +
+
{{domxref("NavigatorPlugins.mimeTypes")}} {{readonlyInline}}{{experimental_inline}}
+
Retorna um {{domxref ("MimeTypeArray")}} listando os tipos MIME suportados pelo navegador.
+
{{domxref("NavigatorPlugins.plugins")}} {{readonlyInline}}{{experimental_inline}}
+
Retorna um {{domxref ("PluginArray")}} listando os plugins instalados no navegador.
+
+ +

Métodos

+ +

A interface NavigatorPlugins NavigatorPlugins não herda nenhum método.

+ +
+
{{domxref("NavigatorPlugins.javaEnabled", "NavigatorPlugins.javaEnabled()")}} {{readonlyInline}}{{experimental_inline}}
+
Retorna uma flag {{domxref ("Boolean")}} indicando se o navegador do host tem o Java ativo ou não.
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('HTML WHATWG', '#navigatorplugins', 'NavigatorPlugins')}}{{Spec2('HTML WHATWG')}}Definição inicial.
+ + + + + +

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

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/navigatorplugins/javaenabled/index.html b/files/pt-br/web/api/navigatorplugins/javaenabled/index.html new file mode 100644 index 0000000000..29aba43a52 --- /dev/null +++ b/files/pt-br/web/api/navigatorplugins/javaenabled/index.html @@ -0,0 +1,54 @@ +--- +title: NavigatorPlugins.javaEnabled() +slug: Web/API/NavigatorPlugins/javaEnabled +tags: + - API + - Example + - Method + - Reference +translation_of: Web/API/NavigatorPlugins/javaEnabled +--- +

{{ APIRef("HTML DOM") }}

+ +

Este método indica se o navegador atual tem o Java ativo ou não.

+ +

Sintaxe

+ +
result = window.navigator.javaEnabled()
+
+ +

Exemplo

+ +
if (window.navigator.javaEnabled()) {
+   // browser has java
+}
+
+ +

Notas

+ +

O valor de retorno para este método indica se a preferência que controla o Java está ativado ou desativado - não se o navegador oferece suporte ao Java, em geral.

+ +

Especificações

+ + + + + + + + + + + + + + + + +
EsécificaçõesEstadoComentário
{{SpecName('HTML WHATWG', '#dom-navigator-javaenabled', 'NavigatorPlugins.javaEnabled')}}{{Spec2('HTML WHATWG')}}Definição inicial.
+ + + + + +

{{Compat("api.NavigatorPlugins.javaEnabled")}}

diff --git a/files/pt-br/web/api/node/appendchild/index.html b/files/pt-br/web/api/node/appendchild/index.html new file mode 100644 index 0000000000..dbca22a3f2 --- /dev/null +++ b/files/pt-br/web/api/node/appendchild/index.html @@ -0,0 +1,56 @@ +--- +title: Node.appendChild +slug: Web/API/Node/appendChild +translation_of: Web/API/Node/appendChild +--- +
{{ApiRef("DOM")}}
+ +

Resumo

+ +

Adiciona um nó ao final da lista de filhos de um nó pai especificado. Se o nó já existir no documento, ele é removido de seu nó pai atual antes de ser adicionado ao novo pai.

+ +

Sintaxe

+ +
var filho = elemento.appendChild(filho);
+ + + +

Descrição

+ +

O método appendChild devolve uma referência ao nó adicionado.

+ +

Exemplo

+ +
// Cria um novo elemento de parágrafo e adiciona-o ao final do documento
+var p = document.createElement("p");
+document.body.appendChild(p);
+ +

Notas

+ +

Se filho é uma referência a um nó existente no documento, appendChild vai movê-lo de sua posição atual para a nova posição (i.e, não é necessário remover o nó de seu pai atual antes de adicioná-lo a outro nó).

+ +

Isso também significa que um nó não pode estar em dois lugares do documento ao mesmo tempo. Assim, se o nó já tem um pai, ele é primeiro removido para, só então, ser adicionado na nova posição.

+ +

Você pode usar o método {{domxref("Node.cloneNode")}} para criar uma cópia do nó antes de adicioná-lo ao novo pai. (Note que cópias feitas com o método cloneNode não serão mantidas sincronizadas automaticamente)

+ +

Este método não permite mover nós entre documentos diferentes. Se você quiser adicionar um nó de um documento diferente (por exemplo para mostrar o resultado de uma requisição AJAX), você precisa primeiro usar o método {{domxref("document.importNode")}}.

+ +

appendChild() é um dos métodos fundamentais da programação para a web usando o DOM. O método appendChild() insere um novo nó na estrutura do DOM de um documento, e é a segunda parte do processo criar-e-adicionar tão importante na construção de páginas web programaticamente.

+ +

Especificação

+ + + +

Ver também

+ + diff --git a/files/pt-br/web/api/node/baseuri/index.html b/files/pt-br/web/api/node/baseuri/index.html new file mode 100644 index 0000000000..fe376eac67 --- /dev/null +++ b/files/pt-br/web/api/node/baseuri/index.html @@ -0,0 +1,82 @@ +--- +title: Node.baseURI +slug: Web/API/Node/baseURI +translation_of: Web/API/Node/baseURI +--- +
+
{{APIRef("DOM")}}
+ +

Resumo

+
+ +

A propriedade somente leitura Node.baseURI retorna a URL base absoluta de um nó.

+ +

A URL base é usada para resolver URLs relativas quando o navegador precisa obter uma URL absoluta, por exemplo, quando processa o atributo src do elemento HTML  {{HTMLElement("img")}} ou o atributo xlink:href do XML.

+ +

No caso comum, a URL base é simplesmente a localização do documento, mas ela pode ser afetada por vários fatores, incluindo o elemento {{HTMLElement("base")}} em HTML e o atributo xml:base em XML.

+ +

Sintaxe

+ +
var baseURI = node.baseURI;
+
+ + + +

Detalhes

+ +

A URL base de um documento

+ +

É a URL base de um documento padrão ao endereço do documento ( como exibido pelo navegador e disponível em {{domxref("window.location")}} ), mas pode mudar o padrão:

+ + + +

Veja a seção URLs base do padrão HTML para mais detalhes.

+ +

Você pode usar {{domxref("document")}}.baseURI  para obter a URL base de um documento. Note que a obtenção da URL base para um documento pode retornar diferentes URLs ao longo do tempo se as tags {{HTMLElement("base")}} ou a localização do documento mudarem.

+ +

A URL base de um elemento

+ +

A URL base de um elemento em HTML é, normalmente,  igual  a URL base do documento onde o nó está.

+ +

Se o documento contém atributos xml:base ( que você não deve fazer em documento HTML), o element.baseURI recebe os atributos xml:base dos elementos pai into account when computing the base URL. Veja xml:base para mais detalhes.

+ +

Você pode usar {{domxref("element")}}.baseURI para obter a URL base de um elemento.

+ +

Especificação

+ + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{ SpecName( "DOM WHATWG", "#dom-node-baseuri", "baseURI" ) }}{{ Spec2( "DOM WHATWG" ) }} 
{{ SpecName( "DOM3 Core", "core.html#Node3-baseURI", "baseURI" ) }}{{ Spec2( "DOM3 Core" ) }}Introduzida
+ +

Ver também

+ + diff --git a/files/pt-br/web/api/node/childnodes/index.html b/files/pt-br/web/api/node/childnodes/index.html new file mode 100644 index 0000000000..f89acb5d8c --- /dev/null +++ b/files/pt-br/web/api/node/childnodes/index.html @@ -0,0 +1,66 @@ +--- +title: Node.childNodes +slug: Web/API/Node/childNodes +translation_of: Web/API/Node/childNodes +--- +
+
{{ApiRef("DOM")}}
+
+ +

A propriedade somente leitura Node.childNodes retorna uma coleção viva de nós filhos de um dado elemento.

+ +

Sintaxe

+ +
var listaNos = noReferencia.childNodes;
+
+ +

listaNos é uma coleção ordenada de objetos node que são filhos do elemento corrente. Se o elemento não tem filhos, então listaNos não contém nenhum nó.

+ +

A listaNos é uma variável que armazena a lista de nós de childNodes. O tipo dessa lista é {{domxref("NodeList")}}.

+ +

Exemplo

+ +
// parg é uma referência de objeto a um elemento <p>
+
+if (parg.hasChildNodes()) {
+  // Primeiramente verificamos se o objeto não está vazio, se o objeto tem nós filhos
+  var filhos= parg.childNodes;
+
+  for (var i = 0; i < filhos.length; i++) {
+    // fazer algo com cada filho em filhos[i]
+    // NOTE: A lista é viva - adicionar ou remover filhos altera a lista
+  }
+}
+ +
+
// Esta é uma forma para remover todos os filhos de um nó
+// box é uma referência de objeto para um elemento com filhos
+
+while (box.firstChild) {
+    // A lista é VIVA, então ela re-indexará a cada chamada
+    box.removeChild(box.firstChild);
+}
+ +

Notas

+ +

Os itens na coleção de nós são objetos, não strings. Para recuperar dados dos objetos dos nós, você deve usar suas propriedades (e.g.,  noReferencia.childNodes[1].nodeName para recuperar o nome, etc.).

+ +

O objeto document tem 2 filhos: a declaração Doctype declaration e o elemento raiz, tipicamente referido como documentElement. (Em documentos (X)HTML este é o elemento HTML)

+ +

Especificação

+ + + +

Veja também

+ + diff --git a/files/pt-br/web/api/node/clonenode/index.html b/files/pt-br/web/api/node/clonenode/index.html new file mode 100644 index 0000000000..fd62b8099d --- /dev/null +++ b/files/pt-br/web/api/node/clonenode/index.html @@ -0,0 +1,175 @@ +--- +title: Node.cloneNode() +slug: Web/API/Node/cloneNode +tags: + - API + - DOM + - Precisa de compatibilidade entre Browsers + - Referencia + - Referência DOM + - metodo +translation_of: Web/API/Node/cloneNode +--- +
{{APIRef("DOM")}}
+ +

O método Node.cloneNode() duplica um elemento node (nó) da estrutura de um documento DOM. Ele retorna um clone do elemento para o qual foi invocado.

+ +

Syntax

+ +
var dupNode = node.cloneNode(deep);
+
+ +
+
node
+
O elemento node (nó) a ser clonado 'duplicado'.
+
dupNode
+
O novo elemento node (nó) resultado da clonagem do elemento node.
+
deep {{optional_inline}} [1]
+
true se os elementos filhos do nó que está sendo clonado devem ser clonados juntos, ou false para clonar apenas o nó específico dispensando, assim, qualquer elemento DOM filho. Veja os exemplos abaixo.
+
+ +
+

Nota: Na especificação do DOM4 (implementado no Gecko 13.0 {{geckoRelease(13)}}), o argumento deep é opcional. Se omitido, por padrão, o método age como se o valor de deep fosse setado como true durante a sua execução.   Para criação de clones superficiais, o argumento deep deve ser setado como false.

+ +

Este comportamento foi alterado na última especificação. Se omitido o argumento deep, o método irá interpretar o valor de deep como se fosse false. Embora ele continue opcional, é recomendado que você sempre observe o argumento deep para fins de compatibilidade anterior e posterior. Com o Gecko 28.0 {{geckoRelease(28)}}), foi advertido aos desenvolvedores para não omitirem o argumento. Iniciado com o Gecko 29.0 {{geckoRelease(29)}}), um clone superficial é o padrão ao invés de um clone aprofundado.

+
+ +

Exemplo

+ +
<div id="paragrafos">
+    <p>Texto parágrafo</p>
+</div>
+
+//Obtém o elemento div
+var div_p = document.getElementById("paragrafos");
+
+//Obtém o primeiro filho do elemento div
+var p = div_p.firstChild;
+
+//Clona o elemento, no caso, um parágrafo
+var p_clone = p.cloneNode(true);
+
+//Adiciona o clone do elemento <p> ao elemento <div>
+div_p.appendChild(p_clone);
+
+
+ +

Notas

+ +

A clonagem de um elemento node copia todos os seus atributos e valores. Porém, não tem o mesmo comportamento em relação aos "event listeners".

+ +

O elmento node resultante da ação de clonagem não faz parte da estruturam DOM do documento até que ele seja adicionado utilizando o método appendChild() ou outro similar, conforme exemplo acima.

+ +

Se o argumento (deep) for setado como false, os nós filhos do elemento node clonado não serão clonados juntos, assim como os respectivos textos.

+ +

Se o argumento (deep) for setado como true, os nós filhos, toda a árvore DOM do elemento clonado, será clonada junto.

+ +
Cuidado: cloneNode() pode duplicar IDs em um documento.
+ +

Se o elemento node (nó) clonado tiver uma ID e o novo elemento node resultante da clonagem for ser inserido no mesmo documento, a ID de um dos nós deve ser alterada para que observem o princípio de unicidade. Em outras palavras, um mesmo documento não pode ter elementos com IDs iguais. Se for o caso de trabalhar com manipulação de elementos DOM através do atributo "name", tome cuidado em observá-lo.

+ +

Clonagem de node (nó)  para um documento diferente, use o seguinte método: {{domxref("Document.importNode()")}}.

+ +

Specificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificaçãoStatusComentários
{{SpecName("DOM WHATWG", "#dom-node-clonenode", "Node.cloneNode()")}}{{Spec2("DOM WHATWG")}} 
{{SpecName("DOM3 Core", "core.html#ID-3A0ED0A4", "Node.cloneNode()")}}{{Spec2("DOM3 Core")}} 
{{SpecName("DOM2 Core", "core.html#ID-3A0ED0A4", "Node.cloneNode()")}}{{Spec2("DOM2 Core")}}Definição Inicial
+ +

Compatibilidade de Browsers

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
(deep) como parâmetro opcional +

{{CompatVersionUnknown}}[1]

+
{{CompatGeckoDesktop("13.0")}}{{CompatVersionUnknown}}{{CompatUnknown}} +

{{CompatVersionUnknown}}[1]

+
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
(deep) como parâmetro opcional{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("13.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Valor padrão para o argumento (deep) é false.

diff --git a/files/pt-br/web/api/node/contains/index.html b/files/pt-br/web/api/node/contains/index.html new file mode 100644 index 0000000000..e468ac6bd3 --- /dev/null +++ b/files/pt-br/web/api/node/contains/index.html @@ -0,0 +1,98 @@ +--- +title: Node.contains +slug: Web/API/Node/contains +translation_of: Web/API/Node/contains +--- +
+
{{ApiRef("DOM")}}
+
+ +

Sumário

+ +

Indica se um nó é um descendente de um dado nó.

+ +

Sintaxe

+ +
node.contains( otherNode )
+
+ + + +

O valor de retorno é true se otherNode é um descendente de um nó ou o próprio nó. Caso contrário o valor de retorno é false.

+ +

Exemplo

+ +

Esta função verifica se um elemento está no corpo da página. As contains is inclusive and determining if the body contains itself isn't the intention of isInPage this case explicitly returns false.

+ +
function isInPage(node) {
+  return (node === document.body) ? false : document.body.contains(node);
+}
+ + + +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
RecursoChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatGeckoDesktop("9.0")}}5.0{{CompatVersionUnknown}}5.2.2 [1][2]
+
+ +
+ + + + + + + + + + + + + + + + + + + +
RecursoAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatUnknown}}{{CompatGeckoMobile("9.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Especificação

+ + + +

Ver também

+ + diff --git "a/files/pt-br/web/api/node/entendendo_o_uso_do_m\303\251todo_appendchild-javascript/index.html" "b/files/pt-br/web/api/node/entendendo_o_uso_do_m\303\251todo_appendchild-javascript/index.html" new file mode 100644 index 0000000000..a05abeae88 --- /dev/null +++ "b/files/pt-br/web/api/node/entendendo_o_uso_do_m\303\251todo_appendchild-javascript/index.html" @@ -0,0 +1,55 @@ +--- +title: Entendendo o uso do método appendChild em javascript +slug: Web/API/Node/Entendendo_o_uso_do_método_AppendChild-javascript +--- +
{{ApiRef("DOM")}}
+ +

Resumo

+ +

Adiciona um nó ao final da lista de filhos de um nó pai especificado. Se o nó já existir no documento, ele é removido de seu nó pai atual antes de ser adicionado ao novo pai.

+ +

Sintaxe

+ +
var filho = elemento.appendChild(filho);
+ + + +

Descrição

+ +

O método appendChild devolve uma referência ao nó adicionado.

+ +

Exemplo

+ +
// Cria um novo elemento de parágrafo e adiciona-o ao final do documento
+var p = document.createElement("p");
+document.body.appendChild(p);
+ +

Notas

+ +

Se filho é uma referência a um nó existente no documento, appendChild vai movê-lo de sua posição atual para a nova posição (i.e, não é necessário remover o nó de seu pai atual antes de adicioná-lo a outro nó).

+ +

Isso também significa que um nó não pode estar em dois lugares do documento ao mesmo tempo. Assim, se o nó já tem um pai, ele é primeiro removido para, só então, ser adicionado na nova posição.

+ +

Você pode usar o método {{domxref("Node.cloneNode")}} para criar uma cópia do nó antes de adicioná-lo ao novo pai. (Note que cópias feitas com o método cloneNode não serão mantidas sincronizadas automaticamente)

+ +

Este método não permite mover nós entre documentos diferentes. Se você quiser adicionar um nó de um documento diferente (por exemplo para mostrar o resultado de uma requisição AJAX), você precisa primeiro usar o método {{domxref("document.importNode")}}.

+ +

appendChild() é um dos métodos fundamentais da programação para a web usando o DOM. O método appendChild() insere um novo nó na estrutura do DOM de um documento, e é a segunda parte do processo criar-e-adicionar tão importante na construção de páginas web programaticamente.

+ +

Especificação

+ + + +

Ver também

+ + diff --git a/files/pt-br/web/api/node/firstchild/index.html b/files/pt-br/web/api/node/firstchild/index.html new file mode 100644 index 0000000000..ab177549a8 --- /dev/null +++ b/files/pt-br/web/api/node/firstchild/index.html @@ -0,0 +1,66 @@ +--- +title: Node.firstChild +slug: Web/API/Node/firstChild +tags: + - API + - DOM + - Node + - Node.firstChild +translation_of: Web/API/Node/firstChild +--- +
+
{{APIRef("DOM")}}
+
+ +

Node.firstChild é uma propriedade do tipo somente leitura que retorna o node (nó) do primeiro elemento filho de uma árvore DOM ou null no caso do elemento não ter filhos (children). 

+ +

Syntax

+ +
var childNode = node.firstChild;
+
+ +

node: elemento node (nó pai) de referência para busca do seu primeiro filho (firstChild) considerada a estrutura DOM.

+ +

childNode: elemento node (nó filho) considerado como primeiro filho (firstChild) de node (pai).

+ +

Descrição

+ +

childNode é uma referência para o primeiro filho (node) de uma estrutura DOM, um node (nó) que não tem filhos retornará null.

+ +

Exemplo

+ +

Este exemplo demonstra o uso do firstChild e como os espaços em branco "whitespace" de um node (nó) podem interferir. 

+ +
<p id="para-01">
+  <span>First span</span>
+</p>
+
+<script type="text/javascript">
+  var p01 = document.getElementById('para-01');
+  console.log(p01.firstChild.nodeName);
+</script>
+ +

No exemplo acima, o console.log() deverá exibir '#text' porque o nó de texto inserido mantém espaços em branco 'whitespace' entre a tag <p id="para-01"> e a tag <span>. Qualquer espaço em branco poderá causar '#text'.

+ +
+

"Tabs" também podem causar esse comportamento.

+
+ +

Se os espaços em branco for removidos do código, o '#text' não será mais considerado e a tag <span> se tornará o primeiro filho firstChild do parágrafo, conforme exemplo abaixo.

+ +
<p id="para-01"><span>First span</span></p>
+
+<script type="text/javascript">
+  var p01 = document.getElementById('para-01');
+  console.log(p01.firstChild.nodeName)
+</script>
+
+ +

Agora o console.log() irá exibir 'SPAN'.

+ +

Especificação

+ + diff --git a/files/pt-br/web/api/node/index.html b/files/pt-br/web/api/node/index.html new file mode 100644 index 0000000000..8b265cdbd5 --- /dev/null +++ b/files/pt-br/web/api/node/index.html @@ -0,0 +1,303 @@ +--- +title: Node +slug: Web/API/Node +translation_of: Web/API/Node +--- +
{{Apiref("DOM")}}
+ +

Node é uma interface da qual diversos tipos do DOM herdam, e que permite que esses tipos sejam tratados de forma similar, por exemplo, herdando os mesmos métodos ou sendo testados da mesma forma.
+
+ Todos os tipos a seguir herdam essa interface e seus métodos e propriedades (apesar de que alguns podem devolver null em casos particulares em que o método ou a propriedade não são relevantes; ou lançar uma exceção quando adicionando um filho a um tipo de nó que não pode ter filhos): {{domxref("Document")}}, {{domxref("Element")}}, {{domxref("Attr")}}, {{domxref("CharacterData")}} (do qual {{domxref("Text")}}, {{domxref("Comment")}}, e {{domxref("CDATASection")}} herdam), {{domxref("ProcessingInstruction")}}, {{domxref("DocumentFragment")}}, {{domxref("DocumentType")}}, {{domxref("Notation")}}, {{domxref("Entity")}}, {{domxref("EntityReference")}}

+ +

{{InheritanceDiagram}}

+ +

 

+ +

Propriedades

+ +

Herda propriedades de seus pais, {{domxref("EventTarget")}}.[1]

+ +
+
{{domxref("Node.baseURI")}} {{readonlyInline}}
+
Retorna uma {{domxref("DOMString")}} representando o URL base do nó. O conceito de URL base muda de uma linguagem para outra; no HTML, ela corresponde ao protocolo, ao nome de domínio e a estrutura de diretório; tudo isso até a última '/'.
+
{{domxref("Node.baseURIObject")}} {{Non-standard_inline()}} {{ Fx_minversion_inline("3") }}
+
Retorna um objeto {{ Interface("nsIURI") }}, representando o URL base do nó. (Indisponível para conteúdo Web)
+
{{domxref("Node.childNodes")}} {{readonlyInline}}
+
Retorna um objeto {{domxref("NodeList")}} "vivo" contendo todos os filhos deste nó. Dizer que um objeto {{domxref("NodeList")}} é vivo significa que se houver alguma mudança em um dos filhos deste nó, o objeto {{domxref("NodeList")}} é automaticamente atualizado com tais mudanças.
+
{{domxref("Node.firstChild")}} {{readonlyInline}}
+
Retorna um {{domxref("Node")}} representando o primeiro filho direto do nó ou null, caso o nó não tenha nenhum filho.
+
{{domxref("Node.lastChild")}} {{readonlyInline}}
+
Retorna um {{domxref("Node")}} representando o último filho direto do elemento ou null, caso o elemento não tenha nenhum filho.
+
{{domxref("Node.nextSibling")}} {{readonlyInline}}
+
Retorna um {{domxref("Node")}} representando o próximo elemento na árvore ou null, caso tal nó não exista.
+
{{domxref("Node.nodeName")}} {{readonlyInline}}
+
Retorna uma {{domxref("DOMString")}} contendo o nome do elemento, do Node. A estrutura do nome irá mudar conforme o tipo do elemento. Veja as diferenças na documentação do método {{domxref("Node.nodeName")}}.  
+
{{domxref("Node.nodePrincipal")}} {{Non-standard_inline()}}{{ Fx_minversion_inline("3") }}
+
Uma interface {{ Interface("nsIPrincipal") }} representando o nó principal.
+
{{domxref("Node.nodeType")}}{{readonlyInline}}
+
Retorna um unsigned short representando o tipo do nodo. Valores possíveis são:
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NomeValor
ELEMENT_NODE1
ATTRIBUTE_NODE2
TEXT_NODE3
CDATA_SECTION_NODE4
ENTITY_REFERENCE_NODE5
ENTITY_NODE6
PROCESSING_INSTRUCTION_NODE7
COMMENT_NODE8
DOCUMENT_NODE9
DOCUMENT_TYPE_NODE10
DOCUMENT_FRAGMENT_NODE11
NOTATION_NODE12
+ +
+
{{domxref("Node.nodeValue")}}
+
Retorna / Define o valor do nó atual
+
{{domxref("Node.ownerDocument")}} {{readonlyInline}}
+
Retorna o {{domxref("Document")}} qual esse nó pertence. Se o nó em si é um documento, retorna null.
+
{{domxref("Node.parentNode")}} {{readonlyInline}}
+
Retorna um {{domxref("Node")}} que é pai desse nó. Se não existe tal nó, como, por exemplo, se esse nó é o topo da árvore ou se ele não participa de uma árvore, essa propriedade retorna null.
+
{{domxref("Node.previousSibling")}} {{readonlyInline}}
+
Retorna um {{domxref("Node")}} representando o último nó em uma árvore ou null se não existe tal nodo.
+
{{domxref("Node.textContent")}}
+
Retorna / Define o conteúdo textual de um elemento e de todos os seus descendentes.
+
+  
+
+ +

Propriedades descontinuadas

+ +
+
{{domxref("Node.rootNode")}} {{readOnlyInline}} {{deprecated_inline}}
+
Retorna um objeto {{domxref("Node")}} representando o nó mais alto em uma árvore, ou o nó atual, se ele for o mais alto da árvore. Isso foi substituído por {{domxref("Node.getRootNode()")}}.
+
+

Propriedades obsoletas

+
+
{{domxref("Node.localName")}} {{obsolete_inline}}{{readonlyInline}}
+
Retorna um {{domxref("DOMString")}} representando a parte local do nome qualificado de um elemento. +
+

Nota: No Firefox 3.5 e nas versões anteriores, a propriedade coloca em caixa alta o nome local de elementos HTML (mas não elementos XHTML). Em versões posteriores, isso não acontece, então a propriedade está em caixa baixa para ambos HTML e XHTML. {{gecko_minversion_inline("1.9.2")}}

+
+
+
{{domxref("Node.namespaceURI")}} {{obsolete_inline}}{{readonlyInline}}
+
O espaço de nomes URI desse nó, ou null se não estiver no espaço de nomes. +
+

Nota: No Firefox 3.5 e nas versões anteriores, elementos HTML estão no espaço de nomes. Em versões posteriores, elementos HTML estão em http://www.w3.org/1999/xhtml/, nas árvores HTML e XML. {{gecko_minversion_inline("1.9.2")}}

+
+
+
{{domxref("Node.prefix")}} {{obsolete_inline}}{{readonlyInline}}
+
É um {{domxref("DOMString")}} representando o espaço de nomes do nó, ou null se nenhum prefixo é especificado.
+
+ +

Métodos

+ +

 

+ + + +

 

+ +

Constantes

+ +

Veja também {{domxref("Node.nodeType")}}

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NomeValor
ELEMENT_NODE1
ATTRIBUTE_NODE2
TEXT_NODE3
DATA_SECTION_NODE4
ENTITY_REFERENCE_NODE5
ENTITY_NODE6
PROCESSING_INSTRUCTION_NODE7
COMMENT_NODE8
DOCUMENT_NODE9
DOCUMENT_TYPE_NODE10
DOCUMENT_FRAGMENT_NODE11
NOTATION_NODE12
DOCUMENT_POSITION_DISCONNECTED0x01
DOCUMENT_POSITION_PRECEDING0x02
DOCUMENT_POSITION_FOLLOWING0x04
DOCUMENT_POSITION_CONTAINS0x08
DOCUMENT_POSITION_CONTAINED_BY0x10
DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC0x20
+ +

Exemplos de código

+ +

Recuperar todos os nós filhos

+ +

A função a seguir percorre todos os nós filhos de um nó recursivamente e executa uma função de callback em cada um deles (e no nó pai também).

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

Sintaxe

+ +
DOMComb(parentNode, callbackFunction);
+ +

Descrição

+ +

Percorre todos os nós filhos de parentNode recursivamente e o próprio parentNode e executa a callbackFunction em cada um deles como this.

+ +

Parâmetros

+ +
+
parentNode
+
O nó pai (Object do tipo Node).
+
callbackFunction
+
A função de callback (Function).
+
+ +

Exemplo de uso

+ +

O exemplo a seguir envia para a função console.log o conteúdo textual do body:

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

Especificações

+ + diff --git a/files/pt-br/web/api/node/innertext/index.html b/files/pt-br/web/api/node/innertext/index.html new file mode 100644 index 0000000000..1ab5e81027 --- /dev/null +++ b/files/pt-br/web/api/node/innertext/index.html @@ -0,0 +1,86 @@ +--- +title: Node.innerText +slug: Web/API/Node/innerText +translation_of: Web/API/HTMLElement/innerText +--- +
{{APIRef("DOM")}}
+ +

Resumo

+ +

Node.innerText é uma propriedade que representa o conteúdo textual "renderizado" de um nó e seus descendentes. Usada como getter, retorna de maneira aproximada o texto que o usuário obteria caso tivesse selecionado o conteúdo e copiado para a área de transferência. Este recurso fora introduzido originalmente pelo Internet Explorer, mas foi oficialmente especificado no padrão HTML apenas em 2016, sendo adotado por todos os principais navegadores a partir de então.

+ +

{{domxref("Node.textContent")}} é uma alternativa similar, embora existam diferenças significativas entre as duas.

+ +

Especificação

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG', 'dom.html#the-innertext-idl-attribute', 'innerText')}}{{Spec2('HTML WHATWG')}}Introduzida, baseado no rascunho da especifição de innerText. Ver whatwg/html#465 e whatwg/compat#5 para histórico.
+ +

Compatibilidade de navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
RecursoChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico4{{ CompatGeckoDesktop(45) }}69.6 (provavelmente antes)3
+
+ +
+ + + + + + + + + + + + + + + + + + + +
RecursoAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico2.3 (provavelmente antes){{ CompatGeckoMobile(45) }}10 (provavelmente antes)124.1 (provavelmente antes)
+
+ +

Ver também

+ + diff --git a/files/pt-br/web/api/node/insertbefore/index.html b/files/pt-br/web/api/node/insertbefore/index.html new file mode 100644 index 0000000000..d556885be7 --- /dev/null +++ b/files/pt-br/web/api/node/insertbefore/index.html @@ -0,0 +1,152 @@ +--- +title: Node.insertBefore +slug: Web/API/Node/insertBefore +translation_of: Web/API/Node/insertBefore +--- +
+
{{ApiRef("DOM")}}
+
+ +

O método Node.insertBefore() insere um nó antes do nó de referência como um filho de um nó pai especificado. Se o filho especificado for uma referência a um nó existente no documento, insertBefore() o moverá de sua posição atual para a nova posição (não há necessidade de remover o nó de seu nó pai antes de anexá-lo a outro nó).

+ +

Isso significa que um nó não pode estar em dois pontos do documento simultaneamente. Portanto, se o nó já tiver um pai, o nó será removido pela primeira vez e inserido na nova posição. O {{domxref("Node.cloneNode()")}} pode ser usado para fazer uma cópia do nó antes de anexá-lo ao novo pai. Note que as cópias feitas com cloneNode() não serão automaticamente mantidas em sincronia.

+ +

 

+ +

Se o nó de referência for null, o nó especificado será incluído no final da lista de filhos do nó pai especificado.

+ +

Se o filho especificado for um {{domxref("DocumentFragment")}}, todo o conteúdo do DocumentFragment será movido para a lista de filhos do nó pai especificado.

+ +

 

+ +

Sintaxe

+ +
var elementoInserido = elementoPai.insertBefore(novoElemento, elementoDeReferencia);
+
+ +

 

+ + + +

 

+ +

Se elementoDeReferencia for null, novoElemento será inserido no fim da lista de nós filhos.

+ +
+

elementoDeReferencia não é um parâmetro opcional - você deve passar explicitamente um Node ou null. Deixar de fornecer ou passar valores inválidos pode ter comportamento diferente em diferentes versões de navegadores.

+
+ +

 

+ +

Return value

+ +

O valor retornado é o filho incluído, exceto quando newNode é um {{domxref("DocumentFragment")}}, caso em que o {{domxref("DocumentFragment")}} vazio é retornado.

+ +

 

+ +

Exemplo

+ +
<div id="elementoPai">
+  <span id="elementoFilho">foo bar</span>
+</div>
+
+<script>
+// Cria um novo elemento <span> vazio
+var sp1 = document.createElement("span");
+
+// Guarda a referência do elemento atraś do qual nos queremos inserir o novo elemento
+var sp2 = document.getElementById("elementoFilho");
+// Guarda a referência do elemento pai
+var divPai = sp2.parentNode;
+
+// Insere o novo elemento no DOM antes de sp2
+divPai.insertBefore(sp1, sp2);
+</script>
+
+ +

Não existe um método insertAfter. Mas ele pode ser emulado combinando o método insertBefore com nextSibling.

+ +

No exemplo anterior, sp1 poderia ser inserido após sp2 desta forma:

+ +
divPai.insertBefore(sp1, sp2.nextSibling);
+ +

Se sp2 não possuir um próximo nó, significa que ele deve ser o último filho — sp2.nextSibling retorna null, e sp1 é inserido ao fim da  da lista de nós filhos (logo após sp2).

+ +

Exemplo 2

+ +

Inserir um elemento antes do primeiro nó filho, usando a propriedade firstChild.

+ +
// Guarda a referêncis do elemento no quela nóe queremos inserir o novo nó
+var elementoPai = document.getElementById('elementoPai');
+// Guarda a referência do primeiro filho
+var primeiroFilho = elementoPai.firstChild;
+
+// Cria um novo elemento
+var novoElemento = document.createElement("div");
+
+// Insere o novo elemento antes do primeiro filho
+elementoPai.insertBefore(novoElemento, primeiroFilho);
+
+ +

Quando o elemento não possui o primeiro filho, então firstChild é null. O elemento ainda será inserido no pai, mas após o último filho. Pois se o elemento pai não possui primeiro filho, ele também não possui o último filho. Conseqüentemente, o novo elemento será o único elemento após a inserção.

+ +

Compatibilidade de navegadores

+ +

{{CompatibilityTable()}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico1.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FuncionalidadeAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Suporte básico{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Especificação

+ + diff --git a/files/pt-br/web/api/node/isconnected/index.html b/files/pt-br/web/api/node/isconnected/index.html new file mode 100644 index 0000000000..52aee94508 --- /dev/null +++ b/files/pt-br/web/api/node/isconnected/index.html @@ -0,0 +1,118 @@ +--- +title: Node.isConnected +slug: Web/API/Node/isConnected +translation_of: Web/API/Node/isConnected +--- +
{{APIRef("DOM")}}
+ +

A propriedade somente-leitura isConnected da interface {{domxref("Node")}} retorna um boleano indicando se um nó está conectado (direta ou indiretamente) ao contexto do objeto, por exemplo o objeto {{domxref("Document")}} no caso da DOM normal, ou o {{domxref("ShadowRoot")}} no caso de uma shadow DOM.

+ +

Sintaxe

+ +
var isItConnected = nodeObjectInstance.isConnected
+ +

Retorno

+ +

Um {{domxref("Boolean")}} que é true se o nó está conectado ao contexto relevante do objeto, e false se não está.

+ +

Examples

+ +

Standard DOM

+ +

Um exemplo em um DOM padrão:

+ +
let test = document.createElement('p');
+console.log(test.isConnected); // Returns false
+document.body.appendChild(test);
+console.log(test.isConnected); // Returns true
+
+ +

Shadow DOM

+ +

Um exemplo em um Shadow DOM:

+ +
// Cria um raíz Shadow
+var shadow = this.attachShadow({mode: 'open'});
+
+// Cria um CSS para aplicar a Shadow DOm
+var style = document.createElement('style');
+console.log(style.isConnected); // retorna false
+
+style.textContent = `
+.wrapper {
+  position: relative;
+}
+
+.info {
+  font-size: 0.8rem;
+  width: 200px;
+  display: inline-block;
+  border: 1px solid black;
+  padding: 10px;
+  background: white;
+  border-radius: 10px;
+  opacity: 0;
+  transition: 0.6s all;
+  positions: absolute;
+  bottom: 20px;
+  left: 10px;
+  z-index: 3
+}
+`;
+
+// Anexa a estilização criada a Shadow DOM.
+
+shadow.appendChild(style);
+console.log(style.isConnected); // retorna true
+ +

Polyfill

+ +

Node.isConnected pode ser polyfilled com o seguinte código para IE10 e EdgeHTML:

+ +
/*
+ * Node.isConnected polyfill para IE and EdgeHTML
+ * 2020-02-04
+ *
+ * Por Eli Grey, https://eligrey.com
+ * Domínio Público.
+ * NENHUMA GARANTIA É EXPRESSADA OU IMPLÍCITA. USE AO SEU PRÓPRIO RISCO.
+ */
+
+if (!('isConnected' in Node.prototype)) {
+  Object.defineProperty(Node.prototype, 'isConnected', {
+    get() {
+      return (
+        !this.ownerDocument ||
+        !(
+          this.ownerDocument.compareDocumentPosition(this) &
+          this.DOCUMENT_POSITION_DISCONNECTED
+        )
+      );
+    },
+  });
+}
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentários
{{SpecName('DOM WHATWG','#dom-node-isconnected','isConnected')}}{{Spec2('DOM WHATWG')}}Definição Inicial.
+ +

Compatibilidade de Browser

+ +
+ + +

{{Compat("api.Node.isConnected")}}

+
diff --git a/files/pt-br/web/api/node/lastchild/index.html b/files/pt-br/web/api/node/lastchild/index.html new file mode 100644 index 0000000000..3bfccdafb0 --- /dev/null +++ b/files/pt-br/web/api/node/lastchild/index.html @@ -0,0 +1,34 @@ +--- +title: Node.lastChild +slug: Web/API/Node/lastChild +tags: + - API + - DOM + - Elements + - lastChild +translation_of: Web/API/Node/lastChild +--- +
{{APIRef("DOM")}}
+ +

Node.lastChild é uma propriedade do tipo somente leitura (read-only) que retorna o último elemento filho (node) de uma estrutura DOM. Se seu parentNode for um Element, ele retornará um Element node, um text node, ou um comment node. Retornará null se o elemento de referência não tiver elementos filhos child. É extremamente recomendável que você conheça a estrutura DOM para um melhor aprendizado e entendimento.

+ +

Syntax

+ +
var last_child = element.lastChild
+
+ +

Exemplo

+ +
// Obtém um elemento <ul>
+var ul = document.getElementById('lista');
+
+// Obtém o último <li> pertencente a estrutura <ul> obtida
+var li_last = ul.lastChild;
+
+ +

Specificações

+ + diff --git a/files/pt-br/web/api/node/nextsibling/index.html b/files/pt-br/web/api/node/nextsibling/index.html new file mode 100644 index 0000000000..5bdb2b888e --- /dev/null +++ b/files/pt-br/web/api/node/nextsibling/index.html @@ -0,0 +1,66 @@ +--- +title: Node.nextSibling +slug: Web/API/Node/nextSibling +translation_of: Web/API/Node/nextSibling +--- +
+
{{ApiRef("DOM")}}
+
+ +

Resumo

+ +

Retorna o nó seguinte ao especificado dentro do lista de filhos do seu pai({{domxref("Node.childNodes","childNodes")}}), ou null se o nó especificado for o último nó da lista.

+ +

Sintaxe

+ +
proximoNo = no.nextSibling
+
+ +

Exemplo

+ +
<div id="div-01">Aqui esta a div-01</div>
+<div id="div-02">Aqui esta a div-02</div>
+
+<script type="text/javascript">
+var el = document.getElementById('div-01').nextSibling;
+
+document.write('<p>Nós irmãos de div-01</p><ol>');
+
+while (el) {
+  document.write('<li>' + el.nodeName + '</li>');
+  el = el.nextSibling;
+}
+
+document.write('</ol>');
+</script>
+
+/**************************************************
+     O seguinte texto será escrito na página quando ela carregar:
+
+     Nós irmãos de div-01
+
+      1. #text
+      2. DIV
+      3. #text
+      4. SCRIPT
+      5. P
+      6. OL
+**************************************************/
+
+ +

No exemplo acima, pode ser visto que nós #text são inseridos no DOM onde espaços em branco aparecem na marcação entre as tags (ex.: após o fechamento da tag de um elemento e antes da abertura da próxima tag). Nenhum espaço em branco é criado entre  elementos inseridos pelo comando document.write.

+ +

A possível inclusão de nós de texto no DOM deve ser permitida quando navegar pelo mesmo usando nextSibling.

+ +

Especificação

+ + + +

Veja também

+ + diff --git a/files/pt-br/web/api/node/parentnode/index.html b/files/pt-br/web/api/node/parentnode/index.html new file mode 100644 index 0000000000..e68aef8eca --- /dev/null +++ b/files/pt-br/web/api/node/parentnode/index.html @@ -0,0 +1,116 @@ +--- +title: Node.parentNode +slug: Web/API/Node/parentNode +tags: + - API + - DOM + - Node + - ParentNode +translation_of: Web/API/Node/parentNode +--- +
+
{{APIRef("DOM")}}
+
+ +

Node.parentNode é uma propriedade DOM somente leitura que retorna o nó (node) parente de um Node referenciado na árvore DOM. É extremamente aconselhável que você conheça a estrutura DOM para um melhor estudo e aprendizado.

+ +

Syntax

+ +
parentNode = node.parentNode
+
+ +

parentNode é o node parente do node referenciado. O parente de um elemento é um Element node, um Document node, ou um DocumentFragment node. Será muito complicado entender tudo isso sem conhecer a estrutura DOM e seus Elements.

+ +

Exemplo

+ +
// Exemplo de como obter um elemento pai
+parente = node.parentNode; // Retorna o elemento pai
+
+// Obtém o primeiro <li> de uma lista
+var li = document.getElementsById('li-first');
+// A partir do <li> obtido, obtém o element <ul>
+var ul = li.parentNode;
+
+// Estrutura com parágrafos dentro de uma div
+var p = document.getElementsByTagName('p');
+var div = p[0].parentNode;
+
+if (node.parentNode) {
+  // remove um node da árvore (estrutura) DOM, a menos que
+  // ele já não exista não estrutura
+  node.parentNode.removeChild(node);
+}
+ +

Notas

+ +

Document e DocumentFragment nodes nunca podem ter um node parent, sendo assim parentNode sempre retornará null. Também retornará null se o node já tiver sido criado e não ainda não estiver anexado à estrutura DOM.

+ +

Compatibilidade entre Browsers

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Suporte Básico{{CompatGeckoDesktop(1.0)}}0.2{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte Básico{{CompatVersionUnknown}}{{CompatGeckoMobile(1)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

 

+ +

Specificações

+ + + +

Veja também

+ + diff --git a/files/pt-br/web/api/node/previoussibling/index.html b/files/pt-br/web/api/node/previoussibling/index.html new file mode 100644 index 0000000000..ad5a88c16c --- /dev/null +++ b/files/pt-br/web/api/node/previoussibling/index.html @@ -0,0 +1,46 @@ +--- +title: Node.previousSibling +slug: Web/API/Node/previousSibling +translation_of: Web/API/Node/previousSibling +--- +
+
{{ApiRef("DOM")}}
+
+ +

Resumo

+ +

Retorna o nó que precede o nó especificado na lista de childNodes do nó pai, retorna null se o nó especificado é o primeiro desta lista.

+ +

Sintaxe

+ +
previousNode = node.previousSibling;
+
+ +

Exemplo

+ +
// <a><b1 id="b1"/><b2 id="b2"/></a>
+
+alert(document.getElementById("b1").previousSibling); // null
+alert(document.getElementById("b2").previousSibling.id); // "b1"
+
+ +

Notas

+ +

Navegador baseados na engine Gecko inserem nós de texto no documento para representar espaços em branco na marcação do fonte. + Portanto um nó obtido, por exemplo, usando Node.firstChild ou Node.previousSibling pode fazer referência a um + espaço em banco ao invés do elemento que o autor pretendia obter.

+ +

Veja Whitespace in the DOM e + W3C DOM 3 FAQ: Why are some Text nodes empty? + Para mais informações. +

+ +

Para navegar no sentido contrário da lista de nós filhos use Node.nextSibling.

+ +

Especificação

+ + diff --git a/files/pt-br/web/api/node/removechild/index.html b/files/pt-br/web/api/node/removechild/index.html new file mode 100644 index 0000000000..9eb927294d --- /dev/null +++ b/files/pt-br/web/api/node/removechild/index.html @@ -0,0 +1,72 @@ +--- +title: Node.removeChild +slug: Web/API/Node/removeChild +translation_of: Web/API/Node/removeChild +--- +
+
{{ApiRef("DOM")}}
+
+ +

Sumário

+ +

Remove um nó filho do DOM. Devolve o nó removido.

+ +

Sintaxe

+ +
var filhoRemovido = elemento.removeChild(filho);
+elemento.removeChild(filho);
+
+ + + +

O nó filho removido ainda existe em memória, mas não é mais parte do DOM. Você pode reutilizar o nó removido mais tarde no seu código por meio da referência filhoRemovido.

+ +

Se filho não for um filho do nó elemento, o método lança uma exceção. Isto também acontecerá se filho era, de fato, um filho de elemento no momento da chamada, mas foi removido por um manipulador de eventos invocado enquanto o elemento estava sendo removido (por exemplo, blur).

+ +

Exemplos

+ +
<!--Código HTML de exemplo-->
+
+<div id="topo" align="center">
+  <div id="interno"></div>
+</div>
+
+ +
// Removendo um elemento específico quando se conhece seu pai
+var d = document.getElementById("topo");
+var d_interno = document.getElementById("interno");
+var noRemovido = d.removeChild(d_interno);
+
+ +
// Removendo um elemento específico sem precisar especificar seu pai
+var no = document.getElementById("interno");
+if (no.parentNode) {
+  no.parentNode.removeChild(no);
+}
+
+ +
// Removendo todos os nós filhos de um elemento
+var elemento = document.getElementById("topo");
+while (elemento.firstChild) {
+  elemento.removeChild(elemento.firstChild);
+}
+
+ +

Especificação

+ + + +

Veja também

+ + diff --git a/files/pt-br/web/api/node/replacechild/index.html b/files/pt-br/web/api/node/replacechild/index.html new file mode 100644 index 0000000000..e6d78e3121 --- /dev/null +++ b/files/pt-br/web/api/node/replacechild/index.html @@ -0,0 +1,69 @@ +--- +title: Node.replaceChild +slug: Web/API/Node/replaceChild +translation_of: Web/API/Node/replaceChild +--- +
+
{{ApiRef("DOM")}}
+
+ +

Sumário

+ +

Substitui o elemento filho especificado por outro.

+ +

Sintaxe

+ +
replacedNode = parentNode.replaceChild(newChild, oldChild);
+
+ + + +

Exemplo

+ +
// <div>
+//  <span id="childSpan">foo bar</span>
+// </div>
+
+// Cria um novo elemento vazio
+// sem ID, atributos ou conteúdo
+var sp1 = document.createElement("span");
+
+// Adiciona um ID 'newSpan' para o elemento
+sp1.setAttribute("id", "newSpan");
+
+// Adiciona contéudo para o elemento
+var sp1_content = document.createTextNode("new replacement span element.");
+
+// Coloca o conteúdo no elemento
+sp1.appendChild(sp1_content);
+
+// Procura o elemento que será substituído
+var sp2 = document.getElementById("childSpan");
+var parentDiv = sp2.parentNode;
+
+// Substituí o elemento que já existe (sp2) por o novo elemento (sp1)
+parentDiv.replaceChild(sp1, sp2);
+
+// resultado:
+// <div>
+//   <span id="newSpan">new replacement span element.</span>
+// </div>
+
+ +

Especificação

+ + + +

Veja também

+ + diff --git a/files/pt-br/web/api/node/textcontent/index.html b/files/pt-br/web/api/node/textcontent/index.html new file mode 100644 index 0000000000..0fb3c38bdb --- /dev/null +++ b/files/pt-br/web/api/node/textcontent/index.html @@ -0,0 +1,138 @@ +--- +title: Node.textContent +slug: Web/API/Node/textContent +tags: + - API + - DOM + - Property +translation_of: Web/API/Node/textContent +--- +
{{APIRef("DOM")}}
+ +
+ +

A propriedade textContent da interface {{domxref("Node")}} representa o conteúdo de texto de um nó e dos seus descendentes.

+ +
+

Nota: textContent e {{domxref("HTMLElement.innerText")}} são facilmente confundidos, mas os dois possuem importantes diferenças entre sí.

+
+ +

Sintaxe

+ +
var text = Node.textContent;
+Node.textContent = string;
+
+ +

Valor de retorno

+ +

Uma String ou null

+ +

Descrição

+ +

Ao obter valores desta propriedade:

+ + + +

Definir valores textContent em um nó, remove todos os nós filhos e os substituem por um único nó de texto cujo o valor é a string inserida.

+ +

Diferenças para o innerText

+ +

Não fique confuso pelas diferenças entre o Node.textContent e o {{domxref("HTMLElement.innerText")}}. Apesar dos nomes parecerem similares, eles possuem importantes diferenças:

+ + + +

Diferenças para o innerHTML

+ +

O {{domxref("Element.innerHTML")}} retorna HTML, Como seu próprio nome indica. As vezes as pessoas usam o innerHTML para obter ou escrever textos dentro de um elemento, mas o textContent possui melhor performance pois seus valores não são analisados como HTML. Além do mais, utilizar textContent pode prevenir ataques XSS.

+ +

Exemplos

+ +

Dado o seguinte fragmento HTML:

+ +
<div id="divA">Isto é<span>algum</span> texto!</div>
+ +

... Você pode usar textContent para obter o conteúdo de texto do elemento:

+ +
let text = document.getElementById('divA').textContent;
+// Agora a variável de texto é: 'Isto é algum texto!'
+ +

... Ou definir o conteúdo de texto do elemento:

+ +
document.getElementById('divA').textContent = 'Este texto é diferente!';
+// O HTML de divA agora é:
+// <div id="divA">Este texto é diferente!</div>
+
+ +

Polyfill para o IE8

+ +
// Fonte: Eli Grey @ https://eligrey.com/blog/post/textcontent-in-ie8
+if (Object.defineProperty
+  && Object.getOwnPropertyDescriptor
+  && Object.getOwnPropertyDescriptor(Element.prototype, "textContent")
+  && !Object.getOwnPropertyDescriptor(Element.prototype, "textContent").get) {
+  (function() {
+    var innerText = Object.getOwnPropertyDescriptor(Element.prototype, "innerText");
+    Object.defineProperty(Element.prototype, "textContent",
+     // Passando innerText ou innerText.get diretamente não funciona,
+     // Função wrapper(que envolve) é necessária.
+     {
+       get: function() {
+         return innerText.get.call(this);
+       },
+       set: function(s) {
+         return innerText.set.call(this, s);
+       }
+     }
+   );
+  })();
+}
+
+ +

Browser compatibility

+ + + +

{{Compat("api.Node.textContent")}}

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG','#dom-node-textcontent','Node.textContent')}}{{Spec2('DOM WHATWG')}}Sem alterações vs. DOM4
{{SpecName('DOM4','#dom-node-textcontent','Node.textContent')}}{{Spec2('DOM4')}}
{{SpecName('DOM3 Core','core.html#Node3-textContent','Node.textContent')}}{{Spec2('DOM3 Core')}}Introduzida
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/nodefilter/index.html b/files/pt-br/web/api/nodefilter/index.html new file mode 100644 index 0000000000..7aaa6fb99b --- /dev/null +++ b/files/pt-br/web/api/nodefilter/index.html @@ -0,0 +1,163 @@ +--- +title: NodeFilter +slug: Web/API/NodeFilter +translation_of: Web/API/NodeFilter +--- +
{{APIRef("DOM")}}
+ +
Uma interface NodeFilter  representa um objeto usado para filtrar os nós (elementos), em uma iteração {{ domxref("NodeIterator") }} ou  {{ domxref("TreeWalker") }}. Essas interfaces não conhecem nada sobre o DOM ou sobre como percorrer ou atravessar, elementos; elas apenas sabem como avaliar se um único nó atende aos requisitos do filtro fornecido ou não.
+ +
 
+ +
+

O navegador não fornece nenhum objeto que implemente essa interface. É esperado que o desenvolvedor escreva tal objeto, utilizando o método acceptNode() conforme as suas necessidades, podendo mesclar com objetos do tipo {{domxref("TreeWalker")}} ou {{domxref("NodeIterator")}}  em sua implementação.. 

+
+ +

Properties

+ +

Essa interface não implementa, nem herda, nenhuma propriedade.

+ +

Methods

+ +

Essa interface não herda nenhum método.

+ +
+
{{domxref("NodeFilter.acceptNode()")}}
+
Returns an unsigned short that will be used to tell if a given {{domxref("Node")}} must be accepted or not by the {{ domxref("NodeIterator") }} or {{ domxref("TreeWalker") }} iteration algorithm. This method is expected to be written by the user of a NodeFilter. Possible return values are: + + + + + + + + + + + + + + + + + + + +
ConstantDescription
FILTER_ACCEPTValue returned by the {{ domxref("NodeFilter.acceptNode()") }} method when a node should be accepted.
FILTER_REJECTValue to be returned by the {{ domxref("NodeFilter.acceptNode()") }} method when a node should be rejected. For {{ domxref("TreeWalker") }}, child nodes are also rejected. For {{ domxref("NodeIterator") }}, this flag is synonymous with FILTER_SKIP.
FILTER_SKIPValue to be returned by {{ domxref("NodeFilter.acceptNode()") }} for nodes to be skipped by the {{ domxref("NodeIterator") }} or {{ domxref("TreeWalker") }} object. The children of skipped nodes are still considered. This is treated as "skip this node but not its children".
+
+
+ +

Example

+ +
var nodeIterator = document.createNodeIterator(
+  // Node to use as root
+  document.getElementById('someId'),
+
+  // Only consider nodes that are text nodes (nodeType 3)
+  NodeFilter.SHOW_TEXT,
+
+  // Object containing the function to use for the acceptNode method
+  // of the NodeFilter
+    { acceptNode: function(node) {
+      // Logic to determine whether to accept, reject or skip node
+      // In this case, only accept nodes that have content
+      // other than whitespace
+      if ( ! /^\s*$/.test(node.data) ) {
+        return NodeFilter.FILTER_ACCEPT;
+      }
+    }
+  },
+  false
+);
+
+// Show the content of every non-empty text node that is a child of root
+var node;
+
+while ((node = nodeIterator.nextNode())) {
+  alert(node.data);
+}
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#interface-nodefilter', 'NodeFilter')}}{{Spec2('DOM WHATWG')}} 
{{SpecName('DOM2 Traversal_Range', 'traversal.html#Traversal-NodeFilter', 'NodeFilter')}}{{Spec2('DOM2 Traversal_Range')}}Initial definition.
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(1)}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.8.1")}}9.09.03.0
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.8.1")}}{{CompatVersionUnknown}}9.03.0
+
+ +

See also

+ + diff --git a/files/pt-br/web/api/nodelist/index.html b/files/pt-br/web/api/nodelist/index.html new file mode 100644 index 0000000000..d20d2978a9 --- /dev/null +++ b/files/pt-br/web/api/nodelist/index.html @@ -0,0 +1,155 @@ +--- +title: NodeList +slug: Web/API/NodeList +tags: + - API + - DOM + - Interface + - NodeList +translation_of: Web/API/NodeList +--- +
{{APIRef("DOM")}}
+ +

Objetos NodeList são coleções de nodos semelhantes aos objetos retornados pelos métodos {{domxref("Node.childNodes")}} e {{domxref("document.querySelectorAll()")}}.

+ +
+

Apesar de NodeList não ser um Array, é possível ser iterada usando o método forEach(). Muitos navegadores antigos ainda não implementaram este método.

+
+ +

Em alguns casos, NodeList é uma coleção viva, ou seja, toda alteração feita no {{ Glossary("DOM") }} reflete nos elementos da coleção. Por exemplo, {{ domxref("Node.childNodes") }} é uma coleção viva:

+ +
var parent = document.getElementById('parent');
+var child_nodes = parent.childNodes;
+console.log(child_nodes.length); // let's assume "2"
+parent.appendChild(document.createElement('div'));
+console.log(child_nodes.length); // should output "3"
+
+ +

Já em outros casos NodeList é um coleção estática, significando que toda alteração subsequente ao {{ Glossary("DOM") }} não afeta o conteúdo da coleção. {{domxref("document.querySelectorAll()")}} é um exemplo de método que retorna uma NodeList estática.

+ +

É aconselhável lembrar dessa distinção quando for escolher como iterar sobre os itens de uma NodeList, e como você faz o cache do tamanho dessa lista.

+ +

Propriedades

+ +
+
{{domxref("NodeList.length")}}
+
A quantidade de nodos na NodeList.
+
+ +

Métodos

+ +
+
{{domxref("NodeList.item()")}}
+
Retorna um item da lista pelo índice, ou null se o índice for inválido; pode ser usado como uma alternativa a nodeList[idx] (que retorna  undefined quando idx é inválido).
+
{{domxref("NodeList.entries()")}}
+
Retorna um {{jsxref("Iteration_protocols","iterador")}} que permite passar por todos os pares chave/valor contidos no objeto.
+
{{domxref("NodeList.forEach()")}}
+
Executa uma função recebida uma vez para cada elemento no NodeList.
+
{{domxref("NodeList.keys()")}}
+
Retorna um {{jsxref("Iteration_protocols","iterador")}} que permite passar por todas as chaves dos pares chave/valor contidos no objeto.
+
{{domxref("NodeList.values()")}}
+
Retorna um {{jsxref("Iteration_protocols","iterador")}} que permite passar por todos os valores dos pares chave/valor contidos no objeto.
+
+ +

Exemplo

+ +

É possivel iterar sobre os items de um NodeList usando:

+ +
for (var i = 0; i < myNodeList.length; ++i) {
+  var item = myNodeList[i];  // Calling myNodeList.item(i) isn't necessary in JavaScript
+}
+
+ +

Não caia na tentação de usar for...in ou for each...in para enumerar os items de uma lista, já que também serão enumeradas as propriedades length e item da NodeList, o que causará erros se o seu script assumir que processará apenas objetos {{ domxref("element") }}. Não esquecendo que for..in não garante a iteração nas propriedades de forma ordenada.

+ +

for...of iterará sobre os objetos da NodeList de maneira correta:

+ +
var list = document.querySelectorAll( 'input[type=checkbox]' );
+for (var item of list) {
+  item.checked = true;
+}
+ +

Navegadores modernos suportam métodos de iteração, {{ domxref("NodeList.forEach()", "forEach()") }}, bem como {{ domxref("NodeList.entries()", "entries()") }}, {{ domxref("NodeList.values()", "values()") }}, e {{ domxref("NodeList.keys()", "keys()") }}

+ +

Há também um jeito compatível com o Internet Explorer de usar {{ jsxref("Array.forEach()", "Array.prototype.forEach") }} para iteração.

+ +
var list = document.querySelectorAll( 'input[type=checkbox]' );
+Array.prototype.forEach.call(list, function (item) {
+  item.checked = true;
+});
+ +

NodeList prototype

+ +

Você também pode adicionar protótipos para NodeList:

+ +
var elements = document.querySelectorAll(".suggestions");
+
+NodeList.prototype.addEventListener = function(event, func) {
+    this.forEach(function(content, item) {
+       content.addEventListener(event, func);
+    });
+}
+
+function log() {
+    console.log(this, " was clicked");
+}
+
+elements.addEventListener("click", log);
+//or
+elements.addEventListener("click", function() {
+    console.log(this, "  awas clicked");
+});
+// output from both will be element was clicked the element would be HTML Element
+ +

Para mais informações sobre forEach veja {{ jsxref("Array.forEach()", "Array.prototype.forEach") }}.

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#interface-nodelist', 'NodeList')}}{{ Spec2('DOM WHATWG') }} 
{{SpecName('DOM4', '#interface-nodelist', 'NodeList')}}{{ Spec2('DOM4') }} 
{{SpecName('DOM3 Core', 'core.html#ID-536297177', 'NodeList')}}{{ Spec2('DOM3 Core') }} 
{{SpecName('DOM2 Core', 'core.html#ID-536297177', 'NodeList')}}{{ Spec2('DOM2 Core') }} 
{{SpecName('DOM1', 'level-one-core.html#ID-536297177', 'NodeList')}}{{ Spec2('DOM1') }}Initial definition.
+ +

Compatibilidade nos navegadores

+ + + +

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

+ +
 
+ +
 
diff --git a/files/pt-br/web/api/notificacoes/index.html b/files/pt-br/web/api/notificacoes/index.html new file mode 100644 index 0000000000..9103aac190 --- /dev/null +++ b/files/pt-br/web/api/notificacoes/index.html @@ -0,0 +1,217 @@ +--- +title: Notificações +slug: Web/API/notificacoes +tags: + - API + - Interface + - Notificações +translation_of: Web/API/Notification +--- +

{{APIRef("Web Notifications")}}{{AvailableInWorkers}}{{securecontext_header}}

+ +

A interface da API de Notificações é usada para configurar e exibir notificações  na área de trabalho do usuário. A aparência e algumas funcionalidades específicas das notificações variam entre as plataformas mas geralmente eles fornecem uma forma assíncrona de prover informações para o usuário.

+ + +

Construtor

+ +
+
{{domxref("Notification.Notification", "Notification()")}}
+
Cria uma nova instancia do objeto {{domxref('Notification')}}.
+
+ +

Propriedades

+ +

Propriedades estáticas

+ +

Estas propriedades estão disponíveis apenas no próprio objeto  Notification.

+ +
+
{{domxref("Notification.permission")}} {{readonlyinline}}
+
+
+
+
+ +
+
Uma sequência de caracteres que representa a permissão atual para exibir notificações. Valor possíveis são: "denied" (o usuário se recusa a ter notificações exibidas), "granted" (o usuário aceita ter notificações exibidas) ou "default" (a escolha do usuário é desconhecido e, portanto, o navegador irá agir como se o valor foram negados).
+
+
+
+ +

Propriedades da instância

+ +

Estas propriedades estão disponíveis apenas em instâncias do objeto Notification.

+ +
+
{{domxref("Notification.title")}} {{readonlyinline}}
+
Retorna o título da notificação conforme foi definido no parâmetro opções do construtor.
+
{{domxref("Notification.dir")}} {{readonlyinline}}
+
A direção do texto da notificação, conforme especificado no parâmetro opções do construtor.
+
{{domxref("Notification.lang")}} {{readonlyinline}}
+
+
+
O código de idioma da notificação, conforme especificado no parâmetro opções do construtor.
+
+
+
{{domxref("Notification.body")}} {{readonlyinline}}
+
O corpo(mensagem) da notificação, conforme especificado no parâmetro opções do construtor.
+
{{domxref("Notification.tag")}} {{readonlyinline}}
+
O ID da notificação (se houver), conforme especificado no parâmetro opções do construtor.
+
{{domxref("Notification.icon")}} {{readonlyinline}}
+
A URL da imagem usada como um ícone da notificação, conforme especificado no parâmetro opções do construtor.
+
{{domxref("Notification.data")}} {{readonlyinline}}
+
Retorna um clone estruturado de dados da notificação.
+
{{domxref("Notification.silent")}} {{readonlyinline}}
+
+
+
Especifica se a notificação deve ser silenciosa, ou seja, sons ou vibrações não devem ser emitidos, independentemente das configurações do dispositivo.
+
+
+
+ +

Propriedades não suportadas

+ +

As propriedades a seguir estão listados na especificação mais up-to-date, mas não são suportadas em quaisquer navegadores ainda. É aconselhável manter a verificação de volta regularmente para ver se o status destes actualiza, e deixe-nos saber se você encontrar qualquer informações desatualizadas.

+ +
+
{{domxref("Notification.noscreen")}} {{readonlyinline}}
+
+
+
Especifica se o disparo notificação deve permitir que a tela do dispositivo ou não.
+
+
+
{{domxref("Notification.renotify")}} {{readonlyinline}}
+
+
+
Especifica se o usuário deve ser notificado após uma nova notificação substitui um antigo.
+
+
+
{{domxref("Notification.sound")}} {{readonlyinline}}
+
Especifica um recurso de som para reproduzir durante o disparo da notificação, em vez do som de notificação do sistema padrão.
+
{{domxref("Notification.sticky")}} {{readonlyinline}}
+
Especifica se a notificação deve ser "fixa", ou seja, não facilmente eliminável pelo usuário.
+
{{domxref("Notification.vibrate")}} {{readonlyinline}}
+
Especifica um padrão de vibração para dispositivos com hardware de vibração.
+
+ +

Manipuladores de Eventos

+ +
+
{{domxref("Notification.onclick")}}
+
O manipulador para o evento {{event("click")}} é acionado cada vez que o usuário clica sobre a notificação.
+
{{domxref("Notification.onerror")}}
+
O manipulador para o evento {{event("error")}} é acionado quando a notificação encontra um erro.
+
+ +

Manipuladores Obsoletos

+ +

Os seguintes manipuladores de eventos ainda são suportados, conforme listado na seção {{anch("browser compatibility")}}. Estes serão listados abaixo, mas não são listados na especificação atual. Saiba que eles são obsoletos, e pode parar de funcionar em versões futuras do navegador.

+ +
+
{{domxref("Notification.onclose")}}
+
Manipulador do evento {{event("close")}} é acionado quando a notificação é fechada.
+
{{domxref("Notification.onshow")}}
+
Manipulador do evento {{event("show")}}. é acionado quando a notificação é exibida.
+
+ +

Métodos

+ +

Métodos Estáticos

+ +

Estes métodos estão disponíveis apenas no próprio objeto Notification.

+ +
+
{{domxref("Notification.requestPermission()")}}
+
+
+
Solicita a permissão do usuário para exibir notificações.
+
+
+
+ +

Métodos de instância

+ +

Estas propriedades estão disponíveis apenas no objeto Notification ou através do seu prototype. O objeto de notificação também herda a interface {{domxref("EventTarget")}}.

+ +
+
{{domxref("Notification.close()")}}
+
Programaticamente fecha uma notificação.
+
+ +

Exemplos

+ +

Leve em conta este HTML básico:

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

É possível enviar uma notificação da seguinte forma - aqui nós apresentamos um conjunto bastante detalhado e completo de código que você pode usar se você quiser verificar primeiro se as notificações são suportados, em seguida, verifique se a permissão foi concedida para a origem atual para enviar notificações, em seguida, solicitar permissão, se necessário, antes, em seguida, enviar uma notificação.

+ +
function notifyMe() {
+  // Verifica se o browser suporta notificações
+  if (!("Notification" in window)) {
+    alert("Este browser não suporta notificações de Desktop");
+  }
+
+  // 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!");
+      }
+    });
+  }
+
+  // At last, if the user has denied notifications, and you
+  // want to be respectful there is no need to bother them any more.
+}
+ +

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

+ +

Em muitos casos, você não precisa estar presente detalhado. Por exemplo, na nosso Emogotchi demo (veja o código fonte), basta simlesmente executar {{domxref("Notification.requestPermission")}} independentemente de se certificar de que pode obter permissão para enviar notificações:

+ +
Notification.requestPermission();
+ +

Em seguida executar um simples spawnNotification() quando queremos disparar uma notificação — este é passado argumentos para especificar o, ícone corpo e título que queremos, então ele cria as opções necessárias objeto e dispara a notificação usando o construtor {{domxref("Notification.Notification","Notification()")}}.

+ +
function spawnNotification(corpo,icone,titulo) {
+  var opcoes = {
+      body: corpo,
+      icon: icone
+  }
+  var n = new Notification(titulo,opcoes);
+}
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('Web Notifications')}}{{Spec2('Web Notifications')}}Living standard
+ +

Compatibilidade dos Navegadores

+ + + +

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

+

Veja também

+ + diff --git a/files/pt-br/web/api/notificationaction/index.html b/files/pt-br/web/api/notificationaction/index.html new file mode 100644 index 0000000000..a7cb904ac5 --- /dev/null +++ b/files/pt-br/web/api/notificationaction/index.html @@ -0,0 +1,79 @@ +--- +title: NotificationAction +slug: Web/API/NotificationAction +translation_of: Web/API/NotificationAction +--- +
{{APIRef("Web Notifications")}}{{AvailableInWorkers}}{{securecontext_header}}
+ +

A interface NotificationAction de Notifications API é usada para representar botões de ação que o usuário pode clicar para intergair com as notificações. As aparências e as funcionalidades específicas dos botões variam entre plataformas, mas geralmente providenciam maneiras de mostrar ações assincronamente ao usuário, em forma de notificações.

+ +

Propriedades

+ +

Propriedades de instância

+ +

Essas propriedades estão disponíveis somente para instâncias do objeto Notification.

+ +
+
{{domxref("NotificationAction.action")}} {{readonlyinline}}
+
O nome da ação, que pode ser usado para identificar a ação clicada, similiar a input names.
+
{{domxref("NotificationAction.title")}} {{readonlyinline}}
+
Uma string descrevendo a ação que sera mosrada ao usuário.
+
{{domxref("NotificationAction.icon")}} {{readonlyinline}}
+
O URL da imagem usado para representar a notificação quando não houver espaço suficiente para mostrar a propria notificação.
+
+ +

Exemplo

+ +

Notifications can fire {{Event("notificationclick")}} events on the {{domxref("ServiceWorkerGlobalScope")}}.

+ +

Here a service worker shows a notification with a single "Archive" action, allowing users to perform this common task from the notification without having to open the website. The user can also click the main body of the notification to open their inbox instead.

+ +
self.registration.showNotification("New mail from Alice", {
+  actions: [
+    {
+      action: 'archive',
+      title: 'Archive'
+    }
+  ]
+});
+
+self.addEventListener('notificationclick', function(event) {
+  event.notification.close();
+  if (event.action === 'archive') {
+    // Archive action was clicked
+    archiveEmail();
+  } else {
+    // Main body of notification was clicked
+    clients.openWindow('/inbox');
+  }
+}, false);
+
+ +

Specifications

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

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/pt-br/web/api/offlineaudiocontext/index.html b/files/pt-br/web/api/offlineaudiocontext/index.html new file mode 100644 index 0000000000..2e0c205feb --- /dev/null +++ b/files/pt-br/web/api/offlineaudiocontext/index.html @@ -0,0 +1,150 @@ +--- +title: OfflineAudioContext +slug: Web/API/OfflineAudioContext +translation_of: Web/API/OfflineAudioContext +--- +
{{APIRef("Web Audio API")}}
+ +
A interface OfflineAudioContext é uma interface {{domxref("AudioContext")}} que representa um gráfico de processament de áudio construido a partir de conexões entre {{domxref("AudioNode")}}s. Em contraste com o padrão {{domxref("AudioContext")}}, um OfflineAudioContext não processa o áudio para o hardware do dispositivo; Em vez disso, ele gera, o mais rápido possível, e exibe o resultado para um {{domxref("AudioBuffer")}}.
+ +

{{InheritanceDiagram}}

+ +

Construtor

+ +
+
{{domxref("OfflineAudioContext.OfflineAudioContext()")}}
+
Cria uma nova instância OfflineAudioContext.
+
+ +

Propriedades

+ +

Também herda propriedades da sua entidade paterna, {{domxref("BaseAudioContext")}}.

+ +
+
{{domxref('OfflineAudioContext.length')}} {{readonlyinline}}
+
+

Um número inteiro que representa o tamanho do buffer em quadros de amostra.

+
+
+ +

Manipuladores de Eventos

+ +
+
{{domxref("OfflineAudioContext.oncomplete")}}
+
É uma chamada {{domxref("EventHandler")}} quando o processamento é encerrado, é quando o evento {{event("complete")}}  - do tipo {{domxref("OfflineAudioCompletionEvent")}} - é gerado, após a versão baseada em eventos do {{domxref("OfflineAudioContext.startRendering()")}} é usada.
+
+ +

Métodos

+ +

Também herda métodos da interface paterna, {{domxref("BaseAudioContext")}}.

+ +
+
{{domxref("OfflineAudioContext.resume()")}}
+
+

Programa uma suspensão da progressão do tempo no contexto de áudio no horário especificado e retorna uma promessa.

+
+
{{domxref("OfflineAudioContext.suspend()")}}
+
+

Agende uma suspensão da progressão do tempo no contexto de áudio no horário especificado e retorna uma promessa.

+
+
{{domxref("OfflineAudioContext.startRendering()")}}
+
+

Inicia a renderização do áudio, levando em consideração as conexões atuais e as mudanças programadas atuais. Esta página abrange a versão baseada em eventos e a versão baseada em promessas.

+
+
+ +

Exemplo

+ +

Nesse exemplo, declaramos um ambos {{domxref("AudioContext")}} e um OfflineAudioContext objeto. Nós usamos o AudioContext para carregar uma faixa de áudio via XHR ({{domxref("AudioContext.decodeAudioData")}}), então o OfflineAudioContext para renderizar o áudio em um {{domxref("AudioBufferSourceNode")}} e reproduzir a trilha. Depois que o gráfico de áudio off-line estiver configurado, você deve renderizá-lo para {{domxref("AudioBuffer")}} usando {{domxref("OfflineAudioContext.startRendering")}}.

+ +

Quando a 'promise' startRendering() é resolvida, a renderização foi concluída e a saída AudioBuffer é retornada fora da 'promise.

+ +

Neste ponto, criamos outro contexto de áudio, criamos um {{domxref("AudioBufferSourceNode")}} dentro dele e configuramos o buffer para ser igual à promessa AudioBuffer. Isso é jogado como parte de um gráfico de áudio padrão simples.

+ +
+

Nota: Para um exemplo de trabalho, veja nosso offline-audio-context-promise Github repo (veja o código fonte também.)

+
+ +
// define o contexto de áudio online e offline
+
+var audioCtx = new AudioContext();
+var offlineCtx = new OfflineAudioContext(2,44100*40,44100);
+
+source = offlineCtx.createBufferSource();
+
+// usa XHR para carregar uma faixa de áudio, e
+// decodeAudioData para decodificar e OfflineAudioContext para renderizar
+
+function getData() {
+  request = new XMLHttpRequest();
+
+  request.open('GET', 'viper.ogg', true);
+
+  request.responseType = 'arraybuffer';
+
+  request.onload = function() {
+    var audioData = request.response;
+
+    audioCtx.decodeAudioData(audioData, function(buffer) {
+      myBuffer = buffer;
+      source.buffer = myBuffer;
+      source.connect(offlineCtx.destination);
+      source.start();
+      //source.loop = true;
+      offlineCtx.startRendering().then(function(renderedBuffer) {
+        console.log('Rendering completed successfully');
+        var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
+        var song = audioCtx.createBufferSource();
+        song.buffer = renderedBuffer;
+
+        song.connect(audioCtx.destination);
+
+        play.onclick = function() {
+          song.start();
+        }
+      }).catch(function(err) {
+          console.log('Rendering failed: ' + err);
+          // Nota: A promessa deve rejeitar quando o StartRendering é chamado uma segunda vez em um OfflineAudioContext
+      });
+    });
+  }
+
+  request.send();
+}
+
+// Run getData to start the process off
+
+getData();
+ +

Especificações

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#OfflineAudioContext', 'OfflineAudioContext')}}{{Spec2('Web Audio API')}}Initial definition
+ +

Compatibilidade de Navegadores/Browser

+ +
+ + +

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

+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/page_visibility_api/index.html b/files/pt-br/web/api/page_visibility_api/index.html new file mode 100644 index 0000000000..1fc2222ad0 --- /dev/null +++ b/files/pt-br/web/api/page_visibility_api/index.html @@ -0,0 +1,209 @@ +--- +title: Page Visibility API +slug: Web/API/Page_Visibility_API +tags: + - DOM + - Intermediário + - Tutoriais + - Visibilidade +translation_of: Web/API/Page_Visibility_API +--- +

{{DefaultAPISidebar("Page Visibility API")}}

+ +

API de visibilidade de página deixa você saber quando uma página da web está visível ou em foco. Com a navegação em abas, existem razões para que quaisquer páginas da web que estejam sendo executadas em segundo plano e não visíveis para o usuário. Quando o usuário minimiza a página ou muda para outra aba, a API envia um evento {{event("visibilitychange")}} informando o estado de visibilidade da página. Você pode detectar o evento e realizar algumas ações ou modificar o seu comportamento. Por exemplo, se a sua aplicação web estiver reproduzindo um video, ela pode pausar durante o momento que o usuário estiver olhando para outra aba, e reproduz novamente quando o usuário retorna para a aba. O usuário não perde nenhuma parte do video e pode continuar assistindo.

+ +

Benefícios

+ +

A API é particularmente util para economizar recursos dando aos desenvolvedores a oportunidade de não realizar tarefas desnecessárias quando a página não está visível.

+ +

Casos de uso

+ +

Alguns exemplos:

+ + + +

Desenvolvedores têm historicamente usado alternativas de se detectar isto. Por exemplo, registrando um handler onblur/onfocus na janela te ajuda a saber quando a sua página não é a ativa, mas isto não te diz se a sua página não está visível para o usuário. Já a API de Visibilidade de Página faz isto. (Quando comparada com a técnica de registrar handlers de onblur/onfocus na janela, uma diferencia chave é que a página não fica escondida quando outra janela é ativada e a janela do navegador perde o foco. A página só fica escondida quando o usuário troca para uma aba diferente ou minimiza a janela do navegador.)

+ +

Exemplo

+ +

Veja exemplo em caso real (video com som).

+ +

O exemplo, que pausa o video quando você troca para outra aba e volta a reproduzir quando você retorna, foi criado com o seguinte código:

+ +
// Configura o nome da propriedade hidden e o evento de mudança para visibilidade
+var hidden, visibilityChange;
+if (typeof document.hidden !== "undefined") { // Suporte para Opera 12.10 e Firefox 18 em diante
+  hidden = "hidden";
+  visibilityChange = "visibilitychange";
+} else if (typeof document.mozHidden !== "undefined") {
+  hidden = "mozHidden";
+  visibilityChange = "mozvisibilitychange";
+} 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");
+
+// Se a página está escondida, pausa o video;
+// Se a página está visível, reproduz o video
+function handleVisibilityChange() {
+  if (document[hidden]) {
+    videoElement.pause();
+  } else {
+    videoElement.play();
+  }
+}
+
+// Alerta se o navegador não suporta addEventListener ou a API de visibilidade da página
+if (typeof document.addEventListener === "undefined" ||
+  typeof document[hidden] === "undefined") {
+  alert("This demo requires a browser, such as Google Chrome or Firefox, that supports the Page Visibility API.");
+} else {
+  // Manipula o evento de mudança da visibilidade da página
+  document.addEventListener(visibilityChange, handleVisibilityChange, false);
+
+  // Reverte para o favicon existente para o site quando a página é fechada;
+  // caso contrário, o favicon continua como paused.png
+  window.addEventListener("unload", function(){
+    favicon.change("/favicon.ico");
+  }, false);
+
+  // Quando o video é pausado, configura o favicon.
+  // Isso mostra a imagem paused.png
+  videoElement.addEventListener("pause", function(){
+    favicon.change("images/paused.png");
+  }, false);
+
+  // Quando o video é reproduzido, configura o favicon.
+  videoElement.addEventListener("play", function(){
+    favicon.change("images/playing.png");
+  }, false);
+
+  // Configura o título da aba com o tempo atual do video
+  videoElement.addEventListener("timeupdate", function(){
+    document.title = Math.floor(videoElement.currentTime) + " segundo(s)";
+  }, false);
+}
+
+ +

Visão geral das propriedades

+ +

document.hidden Somented leitura 

+ +

Retorna true se a página está escondida para o usuário, caso contrário, retorna false.

+ +

document.visibilityState Somente leitura 

+ +

É a cadeia de caracteres que denota a visibilidade do documento. Possíveis valores:

+ + + +
//startSimulation e pauseSimulation definidas em outro lugar
+function handleVisibilityChange() {
+  if (document.hidden) {
+    pauseSimulation();
+  } else  {
+    startSimulation();
+  }
+}
+
+document.addEventListener("visibilitychange", handleVisibilityChange, false);
+
+ +

Nota

+ +

Os estados de visibilidade de {{HTMLElement("iframe")}} são os mesmos do documento pai. Esconder o iframe com propriedades CSS não ativa os eventos de visibilidade nem muda o estado do documento do conteúdo.

+ +

Especificações

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

Compatibilidade com navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico13 {{property_prefix("webkit")}}
+ 33
{{CompatGeckoDesktop(10)}} {{property_prefix("moz")}}
+ {{CompatGeckoDesktop(18)}}
1012.10[1]7
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FuncionalidadeAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Suporte básico4.4 {{property_prefix("webkit")}}{{CompatGeckoMobile(10)}} {{property_prefix("moz")}}
+ {{CompatGeckoMobile(18)}}
1012.10[1]7
+
+ +

[1] Não ativa o evento visibilitychange quando a janela do navegador é minimizada, nem configura hidden como true.

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/parentnode/childelementcount/index.html b/files/pt-br/web/api/parentnode/childelementcount/index.html new file mode 100644 index 0000000000..dea1fed6cd --- /dev/null +++ b/files/pt-br/web/api/parentnode/childelementcount/index.html @@ -0,0 +1,98 @@ +--- +title: ParentNode.childElementCount +slug: Web/API/ParentNode/childElementCount +tags: + - Child + - DOM + - JavaScript + - ParentNode +translation_of: Web/API/ParentNode/childElementCount +--- +
{{ APIRef("DOM") }}
+ +

A propriedade ParentNode.childElementCount, do tipo "somente leitura" (read-only), tem como retorno um unsigned long que representa q quantidade de elementos filhos de um outro determinado elemento.

+ +
+

Essa propriedade foi inicialmente definida na interface pura {{domxref("ElementTraversal")}}. Como essa interface continha dois conjuntos distintos de propriedades, sendo uma destinada para {{domxref("Node")}} que tem filhos, e outra destinada para aqueles que são filhos de fato, essas propriedades foram movidas para duas interfaces puras distintas: {{domxref("ParentNode")}} e {{domxref("ChildNode")}}. Nesse caso, childElementCount foi movido para {{domxref("ParentNode")}}.  Essa é uma alteração bastante técnica que não deve afetar a compatibilidade.

+
+ +

Sintaxe

+ +
var count = node.childElementCount;
+
+ +
+
count
+
variável que recebe o valor retornado pelo método, sendo esse valor do tipo unsigned long (simplesmente um número inteiro).
+
node
+
Objeto que representa {{domxref("Document")}}, {{domxref("DocumentFragment")}}, ou {{domxref("Element")}}.
+
+ +

Exemplo

+ +
var foo = document.getElementById('foo');
+if (foo.childElementCount > 0) {
+  // Faz algo
+}
+
+ +

Utilizando Polyfill no IE8, IE9 e Safari

+ +

Essa propriedade não é suportada em versões anteriores ao IE9. Já no IE9 ou Safari, não será suportada somente por Objetos de Document e DocumentFragment.

+ +
;(function(constructor) {
+  if (constructor &&
+      constructor.prototype &&
+      constructor.prototype.childElementCount == null) {
+    Object.defineProperty(constructor.prototype, 'childElementCount', {
+      get: function() {
+        var i = 0, count = 0, node, nodes = this.childNodes;
+        while (node = nodes[i++]) {
+          if (node.nodeType === 1) count++;
+        }
+        return count;
+      }
+    });
+  }
+})(window.Node || window.Element);
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + +
EspecificaçõesStatusComentários
{{SpecName('DOM WHATWG', '#dom-parentnode-childelementcount', 'ParentNode.childElementCount')}}{{Spec2('DOM WHATWG')}}Divide a interface ElementTraversal entre {{domxref("ChildNode")}} e ParentNode. Esse método é definido ao final.
+ {{domxref("Document")}} e {{domxref("DocumentFragment")}} implementam essas novas interfaces.
{{SpecName('Element Traversal', '#attribute-childElementCount', 'ElementTraversal.childElementCount')}}{{Spec2('Element Traversal')}} +

Adicionada sua definição inicial à interface pura do ElementTraversal e use-a em {{domxref("Element")}}.

+
+ +

Compatibilidade de navegadores

+ + + +

{{Compat("api.ParentNode.childElementCount")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/parentnode/children/index.html b/files/pt-br/web/api/parentnode/children/index.html new file mode 100644 index 0000000000..755cff62a5 --- /dev/null +++ b/files/pt-br/web/api/parentnode/children/index.html @@ -0,0 +1,131 @@ +--- +title: ParentNode.children +slug: Web/API/ParentNode/children +translation_of: Web/API/ParentNode/children +--- +

{{ APIRef("DOM") }}

+ +

Node.children é uma propriedade exclusivamente de leitura que retorna uma coleção {{domxref("HTMLCollection")}} dos elementos filhos do .

+ +

Sintaxe

+ +
var elList = elementNodeReference.children; 
+ +

elList é uma {{ domxref("HTMLCollection") }}, que é uma lista ordenada de uma coleção de elementos do DOM que são filhos do elementNodeReference. Se não existir nenhum elemento filho, o elList não terá elemento algum sua propriedade length será 0.

+ +

Exemplo

+ +
// pEl é uma referência à um elemento <p>
+var elementChildren = pEl.children;
+for (var i = 0; i < elementChildren.length; i++) {
+    console.log(elementChildren[i].tagName);
+    // NOTE: elementChildren é uma lista viva, adicionar ou remover filhos de pEl
+    // mudará instantaneamente o valor retornado por elementChildren
+}
+
+ +

Especificação

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComment
{{SpecName('DOM WHATWG', '#dom-parentnode-children', 'ParentNode.children')}}{{Spec2('DOM WHATWG')}}Definição inicial.
+ +

Compatibilidade de navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerEdgeOperaSafari
Basic support (on {{domxref("Element")}})1.0{{CompatGeckoDesktop("1.9.1")}}9.0 [1]38.010.04.0
Support on {{domxref("Document")}} and {{domxref("DocumentFragment")}} {{experimental_inline}}29.0{{CompatGeckoDesktop("25.0")}}{{CompatNo}}{{CompatNo}}16.0{{CompatNo}}
Support on {{domxref("SVGElement")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support (on {{domxref("Element")}}){{ CompatVersionUnknown() }}{{CompatGeckoMobile("1.9.1")}}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
Support on {{domxref("Document")}} and {{domxref("DocumentFragment")}} {{experimental_inline}}{{CompatVersionUnknown}}{{CompatGeckoMobile("25.0")}}{{CompatNo}}16.0{{CompatNo}}
+
+ +

[1] Internet Explorer 6, 7 e 8 suportaram esse método, mas erroneamente incluiam nós de {{domxref("Comment")}}.

+ +

See also

+ + diff --git a/files/pt-br/web/api/parentnode/index.html b/files/pt-br/web/api/parentnode/index.html new file mode 100644 index 0000000000..ac2ca6c4ba --- /dev/null +++ b/files/pt-br/web/api/parentnode/index.html @@ -0,0 +1,163 @@ +--- +title: ParentNode +slug: Web/API/ParentNode +tags: + - API + - DOM + - NeedsTranslation + - TopicStub +translation_of: Web/API/ParentNode +--- +
{{APIRef("DOM")}}
+ +

The ParentNode interface contains methods that are particular to {{domxref("Node")}} objects that can have children.

+ +

ParentNode is a raw interface and no object of this type can be created; it is implemented by {{domxref("Element")}}, {{domxref("Document")}}, and {{domxref("DocumentFragment")}} objects.

+ +

Properties

+ +
+
{{ domxref("ParentNode.children") }} {{experimental_inline}} {{readonlyInline}}
+
Returns a live {{domxref("HTMLCollection")}} containing all objects of type {{domxref("Element")}} that are children of this ParentNode.
+
{{ domxref("ParentNode.firstElementChild") }} {{experimental_inline}} {{readonlyInline}}
+
Returns the {{domxref("Element")}} that is the first child of this ParentNode, or null if there is none.
+
{{ domxref("ParentNode.lastElementChild") }} {{experimental_inline}} {{readonlyInline}}
+
Returns the {{domxref("Element")}} that is the last child of this ParentNode, or null if there is none.
+
{{ domxref("ParentNode.childElementCount") }} {{experimental_inline}} {{readonlyInline}}
+
Returns an unsigned long giving the amount of children that the object has.
+
+ +

Methods

+ +
+
{{ domxref("ParentNode.append()") }} {{experimental_inline}}
+
Inserts a set of {{domxref("Node")}} objects or {{domxref("DOMString")}} objects after the last child of the ParentNode. {{domxref("DOMString")}} objects are inserted as equivalent {{domxref("Text")}} nodes.
+
{{ domxref("ParentNode.prepend()") }} {{experimental_inline}}
+
Inserts a set of {{domxref("Node")}} objects or {{domxref("DOMString")}} objects before the first child of the ParentNode. {{domxref("DOMString")}} objects are inserted as equivalent {{domxref("Text")}} nodes.
+
+ +

Specification

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-parentnode-firstelementchild', 'ParentNode.firstElementChild')}}{{Spec2('DOM WHATWG')}}Splitted the ElementTraversal interface in {{domxref("ChildNode")}} and ParentNode. The firstElementChild, lastElementChild, and childElementCount properties are now defined on the latter.
+ The {{domxref("Document")}} and {{domxref("DocumentFragment")}} implemented the new interfaces.
+ Added the children property.
+ Added the append() and prepend() methods.
{{SpecName('Element Traversal', '#interface-elementTraversal', 'ElementTraversal')}}{{Spec2('Element Traversal')}}Added the initial definition of its properties to the ElementTraversal pure interface and use it on {{domxref("Element")}}.
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support (on {{domxref("Element")}}){{CompatChrome(1.0)}}{{CompatGeckoDesktop("1.9.1")}}9.0 [1]10.04.0
Support on {{domxref("Document")}} and {{domxref("DocumentFragment")}} {{experimental_inline}}{{CompatChrome(29.0)}}{{CompatGeckoDesktop(25)}}{{CompatNo}}16.0{{CompatNo}}
append() and prepend() {{experimental_inline}}{{CompatChrome(54.0)}}{{CompatGeckoDesktop(49)}}{{CompatVersionUnknown}}{{CompatOpera(39)}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Mobile
Basic support (on {{domxref("Element")}}){{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.9.1")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Support on {{domxref("Document")}} and {{domxref("DocumentFragment")}} {{experimental_inline}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile(25)}}{{CompatNo}}16.0{{CompatNo}}{{CompatVersionUnknown}}
append() and prepend() {{experimental_inline}}{{CompatNo}}{{CompatChrome(54.0)}}{{CompatGeckoMobile(49)}}{{CompatNo}}{{CompatOperaMobile(39)}}{{CompatNo}}{{CompatChrome(54.0)}}
+
+ +

[1] Internet Explorer 6, 7 and 8 supported it, but erroneously returns {{domxref("Comment")}} nodes as part of the results.

+ +

See also

+ + diff --git a/files/pt-br/web/api/parentnode/queryselector/index.html b/files/pt-br/web/api/parentnode/queryselector/index.html new file mode 100644 index 0000000000..0e719e1a73 --- /dev/null +++ b/files/pt-br/web/api/parentnode/queryselector/index.html @@ -0,0 +1,101 @@ +--- +title: ParentNode.querySelector() +slug: Web/API/ParentNode/querySelector +tags: + - PrecisaDeExemplo + - Projeto + - Referencia + - Seletores + - metodo +translation_of: Web/API/ParentNode/querySelector +--- +

{{APIRef("DOM")}}{{Draft}}

+ +

O {{DOMxRef("ParentNode")}} mixin define o querySelector() método como retornar um {{DOMxRef("Element")}} representando o primeiro elemento que corresponde ao grupo especificado de seletores que são descendentes do objeto no qual o método foi chamado.

+ +

Se você precisar de todos os elementos correspondentes à lista de seletores, use{{DOMxRef("ParentNode.querySelectorAll", "querySelectorAll()")}} instead.

+ +
+

Nota: Este método é implementado como {{DOMxRef("Document.querySelector()")}}, {{DOMxRef("DocumentFragment.querySelector()")}} e {{DOMxRef("Element.querySelector()")}}.

+
+ +

Sintaxe

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

Parâmetros

+ +
+
selectors
+
Um {{DOMxRef("DOMString")}} contendo um ou mais seletores para comparar. Essa sequência deve ser um válido lista de seletores compostos suportado pelo navegador; se não for, um SyntaxError exceção é lançada. Veja Localizando elementos DOM usando seletores para obter mais informações sobre o uso de seletores para identificar elementos. Vários seletores podem ser especificados, separando-os usando vírgulas.
+
+ +
+

Nota: Os caracteres que não fazem parte da sintaxe CSS padrão devem ser escapados usando um caractere de barra invertida. Como o JavaScript também usa escape de backspace, deve-se tomar cuidado especial ao escrever literais de string usando esses caracteres. Veja {{anch("Escaping special characters")}} Para maiores informações.

+
+ +

Valor de retorno

+ +

O primeiro {{DOMxRef("Element")}} que corresponda a pelo menos um dos seletores ou null se esse elemento não for encontrado.

+ +
+

Nota: Se o especificado selectors inclua um CSS pseudo-elemento, o valor retornado é sempre null.

+
+ +

Exceções

+ +
+
SyntaxError
+
A sintaxe do especificado selectors string não é válida.
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName("DOM WHATWG", "#dom-parentnode-queryselector", "ParentNode.querySelector()")}}{{Spec2("DOM WHATWG")}}Padrão de vida
{{SpecName("Selectors API Level 2", "#dom-parentnode-queryselector", "ParentNode.querySelector()")}}{{Spec2("Selectors API Level 2")}}Sem alteração
{{SpecName("DOM4", "#dom-parentnode-queryselector", "ParentNode.querySelector()")}}{{Spec2("DOM4")}}Definição inicial
{{SpecName("Selectors API Level 1", "#interface-definitions", "document.querySelector()")}}{{Spec2("Selectors API Level 1")}}Definição original
+ +

Compatibilidade do navegador

+ + + +

{{Compat("api.ParentNode.querySelector")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/path2d/index.html b/files/pt-br/web/api/path2d/index.html new file mode 100644 index 0000000000..65f626f8f6 --- /dev/null +++ b/files/pt-br/web/api/path2d/index.html @@ -0,0 +1,82 @@ +--- +title: Path2D +slug: Web/API/Path2D +tags: + - Canvas + - Compatibilidade + - Interface + - JavaScript + - Métodos + - Pacote 2D + - Path2D + - Referencia +translation_of: Web/API/Path2D +--- +
{{APIRef("Canvas API")}} {{SeeCompatTable}}
+ +

Path2D interface da API Canvas 2D é usada para declarar caminhos que são usados ​​posteriormente em objetos {{domxref("CanvasRenderingContext2D")}}. Os métodos de caminho da interface CanvasRenderingContext2D também estão presentes nessa interface e permitem criar caminhos que você pode reter e reproduzir conforme necessário em uma tela.

+ +

Construtores

+ +
+
{{domxref("Path2D.Path2D", "Path2D()")}}
+
Path2D construtor. Cria um novo objeto Path2D.
+
+ +

Metodos

+ +
+
{{domxref("Path2D.addPath()")}}
+
Adiciona um caminho ao caminho atual.
+
{{domxref("CanvasRenderingContext2D.closePath", "Path2D.closePath()")}}
+
Faz com que o ponto da caneta retorne ao início do sub-caminho atual. Ele tenta desenhar uma linha reta desde o ponto atual até o início. Se a forma já foi fechada ou tem apenas um ponto, essa função não faz nada.
+
{{domxref("CanvasRenderingContext2D.moveTo()", "Path2D.moveTo()")}}
+
Move o ponto inicial de um novo subcaminho para as coordenadas (x, y).
+
{{domxref("CanvasRenderingContext2D.lineTo()", "Path2D.lineTo()")}}
+
Conecta o último ponto no subcaminho às coordenadas x, y com uma linha reta.
+
{{domxref("CanvasRenderingContext2D.bezierCurveTo()", "Path2D.bezierCurveTo()")}}
+
Adiciona uma curva cúbica de Bézier ao caminho. Requer três pontos. Os dois primeiros pontos são pontos de controle e o terceiro é o ponto final. O ponto de partida é o último ponto no caminho atual, que pode ser alterado usando moveTo () antes de criar a curva Bézier.
+
{{domxref("CanvasRenderingContext2D.quadraticCurveTo()", "Path2D.quadraticCurveTo()")}}
+
Adiciona uma curva quadrática de Bézier ao caminho atual.
+
{{domxref("CanvasRenderingContext2D.arc()", "Path2D.arc()")}}
+
Adiciona um arco ao caminho que é centralizado na posição (x, y) com raio r iniciando em startAngle e terminando em endAngle indo na direção dada no sentido anti-horário (padrão no sentido horário).
+
{{domxref("CanvasRenderingContext2D.arcTo()", "Path2D.arcTo()")}}
+
Adiciona um arco ao caminho com os pontos de controle e raio dados, conectados ao ponto anterior por uma linha reta.
+
{{domxref("CanvasRenderingContext2D.ellipse()", "Path2D.ellipse()")}}
+
Adiciona uma elipse ao caminho que é centralizado na posição (x, y) com os raios radiusX e radiusY começando em startAngle e terminando em endAngle indo na direção determinada no sentido anti-horário (padrão no sentido horário).
+
{{domxref("CanvasRenderingContext2D.rect()", "Path2D.rect()")}}
+
Cria um caminho para um retângulo na posição (x, y) com um tamanho determinado por width e height.
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "scripting.html#dom-path2d", "Path2D")}}{{Spec2('HTML WHATWG')}} 
+ +

Compatibilidade com o Navegador

+ +
+ + +

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

+
+ +

Veja também:

+ + diff --git a/files/pt-br/web/api/performance/index.html b/files/pt-br/web/api/performance/index.html new file mode 100644 index 0000000000..28e3a63c06 --- /dev/null +++ b/files/pt-br/web/api/performance/index.html @@ -0,0 +1,138 @@ +--- +title: Performance +slug: Web/API/Performance +tags: + - API + - Interface + - Navigation Timing + - NeedsTranslation + - Performance + - Reference + - TopicStub + - Web Performance +translation_of: Web/API/Performance +--- +
{{APIRef("High Resolution Time")}}
+ +

The Performance interface represents timing-related performance information for the given page.

+ +

An object of this type can be obtained by calling the {{domxref("Window.performance")}} read-only attribute.

+ +
+

Note: This interface and its members are available in Web Workers, except where indicated below. Note that some available parts of the interface are not yet documented (see the Performance Timeline and User Timing specs for more details.) Also note that performance markers and measures are per context. If you create a mark on the main thread (or other worker), you cannot see it in a worker thread, and vice versa.

+
+ +

Properties

+ +

The Performance interface doesn't inherit any properties.

+ +
+
{{domxref("Performance.navigation")}} {{readonlyInline}}
+
Is a {{domxref("PerformanceNavigation")}} object representing the type of navigation that occurs in the given browsing context, like the amount of redirections needed to fetch the resource. Not available in workers.
+
{{domxref("Performance.onframetimingbufferfull")}}
+
TBD
+
{{domxref("Performance.onresourcetimingbufferfull")}}
+
Is an {{domxref("EventTarget")}} which is a callback that will be called when the {{event("resourcetimingbufferfull")}} event is fired.
+
{{domxref("Performance.timing")}} {{readonlyInline}}
+
Is a {{domxref("PerformanceTiming")}} object containing latency-related performance information. Not available in workers.
+
+ +

Methods

+ +

The Performance interface doesn't inherit any method.

+ +
+
{{domxref("Performance.clearFrameTimings()")}}
+
TBD
+
{{domxref("Performance.clearMarks()")}}
+
Removes the given mark from the browser's performance entry buffer.
+
{{domxref("Performance.clearMeasures()")}}
+
Removes the given measure from the browser's performance entry buffer.
+
{{domxref("Performance.clearResourceTimings()")}}
+
Removes all {{domxref("PerformanceEntry","performance entries")}} with a {{domxref("PerformanceEntry.entryType","entryType")}} of "resource" from the browser's performance data buffer.
+
{{domxref("Performance.getEntries()")}}
+
Returns a list of {{domxref("PerformanceEntry")}} objects based on the given filter.
+
{{domxref("Performance.getEntriesByName()")}}
+
Returns a list of {{domxref("PerformanceEntry")}} objects based on the given name and entry type.
+
{{domxref("Performance.getEntriesByType()")}}
+
Returns a list of {{domxref("PerformanceEntry")}} objects of the given entry type.
+
{{domxref("Performance.mark()")}}
+
Creates a {{domxref("DOMHighResTimeStamp","timestamp")}} in the browser's performance entry buffer with the given name.
+
{{domxref("Performance.measure()")}}
+
Creates a named {{domxref("DOMHighResTimeStamp","timestamp")}} in the browser's performance entry buffer between two specified marks (known as the start mark and end mark, respectively).
+
{{domxref("Performance.now()")}}
+
Returns a {{domxref("DOMHighResTimeStamp")}} representing the amount of milliseconds elapsed since a reference instant.
+
{{domxref("Performance.setFrameTimingBufferSize()")}}
+
TBD
+
{{domxref("Performance.setResourceTimingBufferSize()")}}
+
Sets the browser's resource timing buffer size to the specified number of "resource" {{domxref("PerformanceEntry.entryType","type")}} {{domxref("PerformanceEntry","performance entry")}} objects.
+
{{domxref("Performance.toJSON()")}}
+
Is a jsonizer returning a json object representing the Performance object.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Highres Time Level 2', '#the-performance-interface', 'toJSON()')}}{{Spec2('Highres Time Level 2')}}Defines toJson() method.
{{SpecName('Highres Time', '#the-performance-interface', 'Performance')}}{{Spec2('Highres Time')}}Defines now() method.
{{SpecName('Navigation Timing', '#sec-window.performance-attribute', 'Performance')}}{{Spec2('Navigation Timing')}}Defines timing and navigation properties.
{{SpecName('Performance Timeline Level 2', '#extensions-to-the-performance-interface', 'Performance extensions')}}{{Spec2('Performance Timeline Level 2')}}Changes getEntries() interface.
{{SpecName('Performance Timeline', '#sec-window.performance-attribute', 'Performance extensions')}}{{Spec2('Performance Timeline')}}Defines getEntries(), getEntriesByType() and getEntriesByName() methods.
{{SpecName('Resource Timing', '#extensions-performance-interface', 'Performance extensions')}}{{Spec2('Resource Timing')}}Defines clearResourceTimings() and setResourceTimingBufferSize() methods and the onresourcetimingbufferfull property.
{{SpecName('User Timing Level 2', '#extensions-performance-interface', 'Performance extensions')}}{{Spec2('User Timing Level 2')}}Clarifies mark(), clearMark(), measure() and clearMeasure() methods.
{{SpecName('User Timing', '#extensions-performance-interface', 'Performance extensions')}}{{Spec2('User Timing')}}Defines mark(), clearMark(), measure() and clearMeasure() methods.
{{SpecName('Frame Timing', '#extensions-performance-interface','Performance extensions')}}{{Spec2('User Timing')}}Defines clearFrameTimings(), setFrameTimingBufferSize(), and onframetimingbufferfull methods.
+ +

Browser compatibility

+ +
+
+ + +

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

+
+
diff --git a/files/pt-br/web/api/performance/now/index.html b/files/pt-br/web/api/performance/now/index.html new file mode 100644 index 0000000000..b6539ebebe --- /dev/null +++ b/files/pt-br/web/api/performance/now/index.html @@ -0,0 +1,160 @@ +--- +title: performance.now() +slug: Web/API/Performance/now +translation_of: Web/API/Performance/now +--- +
{{APIRef("High Resolution Timing")}}
+ +

O método performance.now() retorna {{domxref("DOMHighResTimeStamp")}}, medido em milisegundos, com precisão de cinco milésimos de milissegundo (5 microsegundos).

+ +

O valor retornado representa o tempo decorrido desde o time origin (the {{domxref("PerformanceTiming.navigationStart")}} property). Em um web worker, o tempo inicial é o momento em que o contexto da execução(e.g. thread ou processo) é criado. Em uma janela, é o tempo em que o usuário iniciou a navegação neste documento. Tenha em mente que:

+ + + +

Sintaxe

+ +
t = performance.now();
+ +

Exemplo

+ +
var t0 = performance.now();
+doSomething();
+var t1 = performance.now();
+console.log("Call to doSomething took " + (t1 - t0) + " milliseconds.");
+
+ +

Unlike other timing data available to JavaScript (for example Date.now), the timestamps returned by Performance.now() are not limited to one-millisecond resolution. Instead, they represent times as floating-point numbers with up to microsecond precision.

+ +

Also unlike Date.now(), the values returned by Performance.now() always increase at a constant rate, independent of the system clock (which might be adjusted manually or skewed by software like NTP). Otherwise, performance.timing.navigationStart + performance.now() will be approximately equal to Date.now().

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Highres Time Level 2', '#dom-performance-now', 'performance.now()')}}{{Spec2('Highres Time Level 2')}}Stricter definitions of interfaces and types.
{{SpecName('Highres Time', '#dom-performance-now', 'performance.now()')}}{{Spec2('Highres Time')}}Initial definition
+ +

Compatibilidade de Navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("20.0")}} {{property_prefix("webkit")}}
+ {{CompatChrome("24.0")}} [1]
{{CompatVersionUnknown}}{{CompatGeckoDesktop("15.0")}}10.0{{CompatOpera("15.0")}}{{CompatSafari("8.0")}}
on Web workers{{CompatChrome("33")}}{{CompatUnknown}}{{CompatGeckoDesktop("34.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
now() in a dedicated worker is now separate from the main context's now().{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop("45.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatAndroid("4.0")}}{{CompatChrome("25.0")}}{{CompatVersionUnknown}}{{CompatGeckoMobile("15.0")}}10.0{{CompatNo}}9{{CompatChrome("25.0")}}
on Web workers{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("34.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
now() in a dedicated worker is now separate from the main context's now().{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("45.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Windows versions of Chrome 20 through 33 return performance.now() only to millisecond precision.

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/performance/tojson/index.html b/files/pt-br/web/api/performance/tojson/index.html new file mode 100644 index 0000000000..2dac99f0f5 --- /dev/null +++ b/files/pt-br/web/api/performance/tojson/index.html @@ -0,0 +1,61 @@ +--- +title: Performance.toJSON() +slug: Web/API/Performance/toJSON +translation_of: Web/API/Performance/toJSON +--- +
{{APIRef("High Resolution Timing")}}
+ +

O método toJSON() da interface {{domxref("Performance")}} é um serializador padrão: Ele retorna uma representação em JSON das propriedades do objeto performance.

+ +

Sintaxe

+ +
minhaPerf = performance.toJSON()
+
+ +

Argumentos

+ +
+
Nenhum
+
 
+
+ +

Valor de retorno

+ +
+
minhaPerf
+
Um objeto JSON que é a serialização do objeto {{domxref("Performance")}}.
+
+ +

Exemplo

+ +
var js;
+js = window.performance.toJSON();
+console.log("json = " + JSON.stringify(js));
+
+ +

Especificações

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Highres Time Level 2', '#the-performance-interface', 'toJSON() serializer')}}{{Spec2('Highres Time Level 2')}}Define toJson().
+ +

Compatibilidade de navegadores

+ +
+
+ + +

{{Compat("api.Performance.toJSON")}}

+
+
diff --git a/files/pt-br/web/api/positionoptions/index.html b/files/pt-br/web/api/positionoptions/index.html new file mode 100644 index 0000000000..5e7012e976 --- /dev/null +++ b/files/pt-br/web/api/positionoptions/index.html @@ -0,0 +1,109 @@ +--- +title: PositionOptions +slug: Web/API/PositionOptions +translation_of: Web/API/PositionOptions +--- +
{{APIRef("Geolocation API")}}
+ +
 
+ +
A interface PositionOptions consiste em um objeto que contém propriedades opcionais para passar como um parâmetro de {{domxref("Geolocation.getCurrentPosition()")}} e {{domxref("Geolocation.watchPosition()")}}.
+ +
 
+ +

Propriedades

+ +

A interface PositionOptions não herda qualquer propriedade.

+ +
+
{{domxref("PositionOptions.enableHighAccuracy")}}
+
É um {{domxref("Boolean")}} que indica se a aplicação deve receber os melhores (mais exatos) resultados possíveis. Se o valor for true e o dispositivo puder disponibilizar uma posição mais exata, ele o fará. Note que isto pode resultar em respostas mais lentas ou aumentar o consumo de bateria. (GPS em um dispositivo mobile). Se o valor for false, o dispositivo toma a liberdade de salvar os recursos respondendo mais rapidamente e/ou utilizando menos bateria. Default: false
+
{{domxref("PositionOptions.timeout")}}
+
É um valor long positivo que representa o tamanho máximo do tempo (em milissegundos) que o dispositivo deve levar para retornar uma posição. O valor default é Infinity, o que significa que getCurrentPosition() não terá retorno até que a posição esteja disponível.
+
{{domxref("PositionOptions.maximumAge")}}
+
É um valor long positivo indicando o valor máximo em milissegundos de uma possível posição em cache aceitável para retornar. Se o valor for 0, significa que o dispositivo não deve utilizar uma posição em cache e deve tentar obter a posição atual real. Se o valor for Infinity o dispositivo deve retornar uma posição em cache, independente de seu tempo de expiração. Default: 0.
+
+ +

Métodos

+ +

A interface PositionOptions  não implementa ou herda nenhum método.

+ +

Especificações

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Geolocation', '#positionoptions', 'PositionOptions')}}{{Spec2('Geolocation')}}Initial definition
+ + + +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support5{{CompatGeckoDesktop("1.9.1")}}910.60
+ {{CompatNo}} 15.0
+ 16.0
5
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("4")}}{{CompatUnknown}}10.60{{CompatUnknown}}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/processinginstruction/index.html b/files/pt-br/web/api/processinginstruction/index.html new file mode 100644 index 0000000000..94fdff0a2f --- /dev/null +++ b/files/pt-br/web/api/processinginstruction/index.html @@ -0,0 +1,39 @@ +--- +title: ProcessingInstruction +slug: Web/API/ProcessingInstruction +tags: + - API + - DOM +translation_of: Web/API/ProcessingInstruction +--- +
{{APIRef("DOM")}}
+ +

Uma ProcessingInstruction (Instrução de Processamento) incorpora instruções específicas de aplicações em XML que pode ser ignorada por outras aplicações que não as reconhece. Mesmo se um processador XML ignora as instruções de processamento, irá dá-los um lugar no DOM. 

+ +

Uma instrução de processamento é diferente de uma declaração XML, que fornece informação sobre o documento como por exemplo codificação de caracteres, e pode somente aparecer como o primeiro item em um documento.

+ +

Instruções de processamento definidas por usuário não podem começar com 'xml', pois estes são reservados (como <?xml-stylesheet ?>).

+ +

Instruções de processamento herdam métodos e propriedades do Node

+ +

{{InheritanceDiagram(700,70)}}

+ +

Atributos

+ + + +

Especificações

+ + + +

Veja também

+ + diff --git a/files/pt-br/web/api/pushmanager/index.html b/files/pt-br/web/api/pushmanager/index.html new file mode 100644 index 0000000000..12c2452bae --- /dev/null +++ b/files/pt-br/web/api/pushmanager/index.html @@ -0,0 +1,187 @@ +--- +title: PushManager +slug: Web/API/PushManager +tags: + - API + - API de armazenamento + - Experimental + - Interface + - Referencia + - Service Workers + - Subir dados +translation_of: Web/API/PushManager +--- +

{{SeeCompatTable}}{{ApiRef("Push API")}}

+ +

A PushManagerinterface da API Push fornece uma maneira de receber notificações de servidores de terceiros, bem como solicitar URLs para notificações push.

+ +

Essa interface é acessada através da propriedade {{domxref ("ServiceWorkerRegistration.pushManager")}}.

+ +
+

Nota : Esta interface substitui a funcionalidade anteriormente oferecida pela interface obsoleta {{domxref ("PushRegistrationManager")}}.

+
+ +

Propriedades

+ +
+
{{domxref ("PushManager.supportedContentEncodings")}}
+
Retorna uma série de codificações de conteúdo suportadas que podem ser usadas para criptografar a carga útil de uma mensagem push.
+
+ +

Métodos

+ +
+
{{domxref ("PushManager.getSubscription ()")}}
+
Recupera uma assinatura de envio existente. Retorna uma {{jsxref ("Promise")}} que resolve um objeto {{domxref ("PushSubscription")}} contendo detalhes de uma assinatura existente. Se não existe uma subscrição existente, isso resolve um nullvalor.
+
{{domxref ("PushManager.permissionState ()")}}
+
Retorna uma {{jsxref ( "Promise")}} que resolve para o estado de permissão do atual {{domxref ( "PushManager")}}, que será um dos 'granted', 'denied'ou 'prompt'.
+
{{domxref ("PushManager.subscribe ()")}}
+
Assine um serviço push. Retorna uma {{jsxref ("Promise")}} que resolve um objeto {{domxref ("PushSubscription")}} contendo detalhes de uma inscrição de envio. Uma nova assinatura de envio é criada se o trabalhador de serviço atual não tiver uma assinatura existente.
+
+ +

Métodos depreciados

+ +
+
{{domxref ("PushManager.hasPermission ()")}} {{deprecated_inline}}
+
Retorna uma {{jsxref ( "Promise")}} que resolve para o PushPermissionStatusdo webapp requerente, que será um dos granted, deniedou default. Substituído por {{domxref ("PushManager.permissionState ()")}}.
+
{{domxref ("PushManager.register ()")}} {{deprecated_inline}}
+
Assina uma assinatura de envio. Substituído por {{domxref ("PushManager.subscribe ()")}}.
+
{{domxref ("PushManager.registrations ()")}} {{deprecated_inline}}
+
Recupera as assinaturas de envio existentes. Substituído por {{domxref ("PushManager.getSubscription ()")}}.
+
{{domxref ("PushManager.unregister ()")}} {{deprecated_inline}}
+
Anula e exclui um ponto final de assinatura especificado. Na API atualizada, uma assinatura não está registrada chamando o método {{domxref ("PushSubscription.unsubscribe ()")}}.
+
+ +

Exemplo

+ +
this.onpush = function(event) {
+  console.log(event.data);
+  // From here we can write the data to IndexedDB, send it to any open
+  // windows, display a notification, etc.
+}
+
+navigator.serviceWorker.register('serviceworker.js').then(
+  function(serviceWorkerRegistration) {
+    serviceWorkerRegistration.pushManager.subscribe().then(
+      function(pushSubscription) {
+        console.log(pushSubscription.subscriptionId);
+        console.log(pushSubscription.endpoint);
+        // The push subscription details needed by the application
+        // server are now available, and can be sent to it using,
+        // for example, an XMLHttpRequest.
+      }, function(error) {
+        // During development it often helps to log errors to the
+        // console. In a production environment it might make sense to
+        // also report information about errors back to the
+        // application server.
+        console.log(error);
+      }
+    );
+  });
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('Push API','#pushmanager-interface','PushManager')}}{{Spec2('Push API')}}Definição inicial.
+ +

Compatibilidade do navegador

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeEdgeFirefox (Gecko)Internet ExplorerÓperaSafari (WebKit)
Suporte básico{{CompatChrome(42)}}{{CompatVersionUnknown}}{{CompatGeckoDesktop (44.0)}} [1]{{CompatNo}}{{CompatOpera (29)}}{{CompatNo}}
supportedContentEncodings propriedade{{CompatChrome (60)}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatNo}}{{CompatOpera (47)}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroid WebviewChrome para AndroidEdgeFirefox Mobile (Gecko)SO FirefoxIE MobileOpera MobileSafari Mobile
Suporte básico{{CompatChrome (42)}}{{CompatChrome (42)}}{{CompatVersionUnknown}}{{CompatGeckoMobile (48)}} [2]{{CompatNo}}{{CompatNo}}{{CompatOperaMobile (29)}}{{CompatNo}}
supportedContentEncodings propriedade{{CompatChrome (60)}}{{CompatChrome (60)}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatNo}}{{CompatNo}}{{CompatOperaMobile (47)}}{{CompatNo}}
+
+ + + +

Veja também

+ + diff --git a/files/pt-br/web/api/randomsource/getrandomvalues/index.html b/files/pt-br/web/api/randomsource/getrandomvalues/index.html new file mode 100644 index 0000000000..7e54e933ed --- /dev/null +++ b/files/pt-br/web/api/randomsource/getrandomvalues/index.html @@ -0,0 +1,116 @@ +--- +title: RandomSource.getRandomValues() +slug: Web/API/RandomSource/getRandomValues +translation_of: Web/API/Crypto/getRandomValues +--- +

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

+ +

O método RandomSource.getRandomValues() permite que você obtenha valores criptográficos randômicos. O array passado como parametro é preenchido com números randômicos (randômicos no sentido criptográfico).

+ +

Para garantir performance suficiente, as implementações não estão usando um gerador de número randômico de verdade, mas estão usando um gerador de número pseudo-randômico alimentado com um valor com {{Glossary("entropia")}} suficiente. Os PRNG (pseudo-random number generator - gerador de número pseudo-randômico) usados diferem de uma implementação para a outra, mas são adequadas para usos criptográficos. As implementações precisam ter um valor de alimentação com entropia suficiente, como uma fonte de entropia a nível de sistema.

+ +

Sintaxe

+ +
cryptoObj.getRandomValues(typedArray);
+ +

Parâmetros

+ +
+
typedArray
+
É uma {{jsxref("TypedArray")}} de números inteiros, que pode ser {{jsxref("Int8Array")}}, {{jsxref("Uint8Array")}}, {{jsxref("Uint16Array")}}, {{jsxref("Int32Array")}}, ou {{jsxref("Uint32Array")}}. Todos os elementos no array serão sobrescristos com números randômicos.
+
+ +

Exceções

+ + + +

Exemplo

+ +
/* assumindo que window.crypto.getRandomValues está disponível */
+
+var array = new Uint32Array(10);
+window.crypto.getRandomValues(array);
+
+console.log("Seus números da sorte são:");
+for (var i = 0; i < array.length; i++) {
+    console.log(array[i]);
+}
+
+ +

Especificação

+ + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('Web Crypto API', '#RandomSource-method-getRandomValues')}}{{Spec2('Web Crypto API')}}Definição inicial
+ + + +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support11.0 {{ webkitbug("22049") }}21.011.015.03.1
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatNo() }}23.021.011.0{{ CompatNo() }}6
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/randomsource/index.html b/files/pt-br/web/api/randomsource/index.html new file mode 100644 index 0000000000..8678075371 --- /dev/null +++ b/files/pt-br/web/api/randomsource/index.html @@ -0,0 +1,108 @@ +--- +title: RandomSource +slug: Web/API/RandomSource +tags: + - API + - Interface + - RandomSource + - Referencia + - Web Crypto API +translation_of: Web/API/Crypto/getRandomValues +--- +

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

+ +

RandomSource representa uma fonte criptografada segura de números aleatórios. É disponível via objeto {{domxref("Crypto")}} do objeto global: {{domxref("Window.crypto")}} em páginas Web, {{domxref("WorkerGlobalScope.crypto")}} em trabalhadores.

+ +

RandomSource não é uma interface e nenhum objeto deste tipo pode ser criado.

+ +

Propriedades

+ +

RandomSource não define ou herda nenhuma propriedade.

+ +
+
+ +

Métodos

+ +
+
{{ domxref("RandomSource.getRandomValues()") }}
+
Completa o {{ domxref("ArrayBufferView") }} com valores aleatoriamente criptografados.
+
+ +

Especificação

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('Web Crypto API', '#dfn-RandomSource')}}{{Spec2('Web Crypto API')}}Definição inicial.
+ +

Compatibilidade de Browser

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico11.0 {{ webkitbug("22049") }}{{CompatGeckoDesktop(21)}} [1]11.015.03.1
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{ CompatNo() }}23{{CompatGeckoMobile(21)}}{{ CompatNo() }}{{ CompatNo() }}6
+
+ +

[1] Apesar da RandomSource estar disponível apenas a partir da versão Firefox 26, ela já estava implementada na versão Firefox 21.

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/request/index.html b/files/pt-br/web/api/request/index.html new file mode 100644 index 0000000000..3c29999829 --- /dev/null +++ b/files/pt-br/web/api/request/index.html @@ -0,0 +1,167 @@ +--- +title: Request +slug: Web/API/Request +tags: + - API + - Experimental + - Fetch + - Fetch API + - Requisições + - request +translation_of: Web/API/Request +--- +
{{APIRef("Fetch")}}
+ +

A interface Request da Fetch API representa uma requisição de recursos.

+ +

Você pode criar um novo objeto Request usando o construtor {{domxref("Request.Request()")}}, porém é mais provável que você encontre um objeto Request que seja retornado como resultado de outra operação de API, como um service worker {{domxref("FetchEvent.request")}}.

+ +

Construtor

+ +
+
{{domxref("Request.Request()")}}
+
Cria um novo objeto Request.
+
+ +

Propriedades

+ +
+
{{domxref("Request.method")}} {{readonlyInline}}
+
Contém o método da requisição (GET, POST etc.)
+
{{domxref("Request.url")}} {{readonlyInline}}
+
Contém a URL da requisição.
+
{{domxref("Request.headers")}} {{readonlyInline}}
+
Contém o objeto {{domxref("Headers")}} associado à requisição.
+
{{domxref("Request.context")}} {{readonlyInline}} {{deprecated_inline()}}
+
Contém o contexto da requisição (ex., audio, image, iframe etc.)
+
{{domxref("Request.referrer")}} {{readonlyInline}}
+
Contém a referência da requisição (ex., client).
+
{{domxref("Request.referrerPolicy")}} {{readonlyInline}}
+
Contém a política de referência da requisição (ex., no-referrer).
+
{{domxref("Request.mode")}} {{readonlyInline}}
+
Contém o modo da requisição (ex., cors, no-cors, same-origin, navigate.)
+
{{domxref("Request.credentials")}} {{readonlyInline}}
+
Contém a credencial da requisição (Ex., omit, same-origininclude).
+
{{domxref("Request.redirect")}} {{readonlyinline}}
+
Contém o modo de como os redirecionamentos serão tratados. Pode ser: follow, error ou manual.
+
{{domxref("Request.integrity")}} {{readonlyInline}}
+
Contém o valor da subresource integrity da requisição (ex., sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=).
+
{{domxref("Request.cache")}} {{readonlyInline}}
+
Contém o modo de cache da requisição (ex., default, reload, no-cache).
+
+ +

Request implementa {{domxref("Body")}}, então também possui as seguintes propriedades disponíveis:

+ +
+
{{domxref("Body.body")}} {{readonlyInline}}
+
Um simples "getter" para ler o conteúdo do corpo através da interface {{domxref("ReadableStream")}}.
+
{{domxref("Body.bodyUsed")}} {{readonlyInline}}
+
Armazena um {{domxref("Boolean", "Booleano")}} que declara se o corpo da requisição já foi utilizado em uma resposta.
+
+ +

Métodos

+ +
+
{{domxref("Request.clone()")}}
+
Cria uma cópia atual do objeto Request.
+
+ +

Request implementa {{domxref("Body")}}, então também possui os seguintes métodos disponíveis:

+ +
+
{{domxref("Body.arrayBuffer()")}}
+
Retorna um objeto do tipo promise que resolve um {{domxref("ArrayBuffer")}} com a representação do corpo da requisição.
+
{{domxref("Body.blob()")}}
+
Retorna um objeto do tipo promise que resolve um {{domxref("Blob")}} com a representação do corpo da requisição.
+
{{domxref("Body.formData()")}}
+
Retorna um objeto do tipo promise que resolve um {{domxref("FormData")}} com a representação do corpo da requisição.
+
{{domxref("Body.json()")}}
+
Retorna um objeto do tipo promise que resolve um {{domxref("JSON")}} com a representação do corpo da requisição.
+
{{domxref("Body.text()")}}
+
Retorna um objeto do tipo promise que resolve um {{domxref("USVString")}} (texto) com a representação do corpo da requisição.
+
+ +
+

Nota: Os métodos de {{domxref("Body")}}  só poderão ser executadas apenas uma vez; As chamadas subsequentes serão resolvidas com strings/ArrayBuffers vazias.

+
+ +

Exemplos

+ +

No exemplo a seguir, nós criamos uma nova requisição utilizando o construtor Request() (para um arquivo de imagem no mesmo diretório do código) e, em seguida, nos retorna alguns valores das propriedades da requisição:

+ +
const myRequest = new Request('http://localhost/flowers.jpg');
+
+const myURL = myRequest.url; // http://localhost/flowers.jpg
+const myMethod = myRequest.method; // GET
+const myCred = myRequest.credentials; // omit
+
+ +

Você poderá, então, solicitar uma nova requisição passando o objeto Request como parâmetro para a chamada {{domxref("GlobalFetch.fetch()")}}, por exemplo:

+ +
fetch(myRequest)
+  .then(response => response.blob())
+  .then(blob => {
+    myImage.src = URL.createObjectURL(blob);
+  });
+ +

No exemplo a seguir, nós criamos uma nova requisição utilizando o construtor Request() com alguns valores iniciais e contendo o corpo para APIs que precisam processar essas informações:

+ +
const myRequest = new Request('http://localhost/api', {method: 'POST', body: '{"foo":"bar"}'});
+
+const myURL = myRequest.url; // http://localhost/api
+const myMethod = myRequest.method; // POST
+const myCred = myRequest.credentials; // omit
+const bodyUsed = myRequest.bodyUsed; // true
+
+ +
+

Nota: O tipo do corpo poderá ser apenas: {{domxref("Blob")}}, {{domxref("BufferSource")}}, {{domxref("FormData")}}, {{domxref("URLSearchParams")}}, {{domxref("USVString")}} ou {{domxref("ReadableStream")}}. Para adicionar um objeto JSON ao corpo, é necessário converter esse objeto para string.

+
+ +

Você poderá, então, solicitar uma nova requisição passando o objeto Request como parâmetro para a chamada {{domxref("GlobalFetch.fetch()")}}, por exemplo, e poderá capturar a resposta da seguinte forma:

+ +
fetch(myRequest)
+  .then(response => {
+    if (response.status === 200) {
+      return response.json();
+    } else {
+      throw new Error('Ops! Houve um erro em nosso servidor.');
+    }
+  })
+  .then(response => {
+    console.debug(response);
+    // ...
+  }).catch(error => {
+    console.error(error);
+  });
+ +

Especificações

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fetch','#request-class','Request')}}{{Spec2('Fetch')}}Initial definition
+ +

Compatibilidade entres navegadores

+ + + +

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

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/request/request/index.html b/files/pt-br/web/api/request/request/index.html new file mode 100644 index 0000000000..ac46f16fd3 --- /dev/null +++ b/files/pt-br/web/api/request/request/index.html @@ -0,0 +1,155 @@ +--- +title: Request() +slug: Web/API/Request/Request +translation_of: Web/API/Request/Request +--- +
{{APIRef("Fetch")}}
+ +

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

+ +

Sintaxe

+ +
var myRequest = new Request(input[, init]);
+ +

Parâmetros

+ +
+
input
+
Define o recurso que você deseja buscar. Isso pode ser: +
    +
  • Um {{domxref("USVString")}} contendo o URL direto do recurso que você deseja buscar.
  • +
  • Um objeto {{domxref("Request")}}, criando efetivamente uma cópia. Observe as seguintes atualizações comportamentais para reter a segurança e, ao mesmo tempo, tornar o construtor menos propenso a gerar exceções: +
      +
    • Se esse objeto existir em outra origem para a chamada do construtor, o {{domxref("Request.referrer")}} será removido.
    • +
    • Se esse objeto tiver um {{domxref("Request.mode")}} de navegação, o valor do modo será convertido para a mesma origem.
    • +
    +
  • +
+
+
init {{optional_inline}}
+
Um objeto de opções contendo quaisquer configurações personalizadas que você deseja aplicar à solicitação. As opções possíveis são: +
    +
  • method: O método de request, ex: GET, POST.
  • +
  • headers: Quaisquer cabeçalhos que você deseja adicionar à sua solicitação, contidos em um objeto {{domxref("Headers")}} ou em um objeto literal com valores de {{domxref("ByteString")}}.
  • +
  • body: Qualquer corpo que você deseja adicionar à sua solicitação: isso pode ser um {{domxref("Blob")}}, {{domxref("BufferSource")}}, {{domxref("FormData")}}, {{domxref("URLSearchParams")}}, {{domxref("USVString")}}, ou objeto {{domxref("ReadableStream")}}. Observe que uma solicitação usando o método GET ou HEAD não pode ter um corpo.
  • +
  • mode: O modo que você deseja usar para a solicitação, por exemplo: cors, no-cors, same-origin, or navigate. O padrão é cors. No Chrome o padrão é no-cors antes do Chrome 47 e same-origin do Chrome 47 em diante.
  • +
  • credentials: As credenciais de solicitação que você deseja usar para a solicitação: omit, same-origin, ou include. O padrão é omit. No Chrome o padrão é same-origin antes do Chrome 47 e include do Chrome 47 em diante.
  • +
  • cache: O cache mode  que você deseja usar para a solicitação.
  • +
  • redirect: O modo de redirecionamento para usar: follow, error, or manual. No Chrome o padrão é follow (antes do Chrome 47 foi padronizado manual).
  • +
  • referrer: Um {{domxref("USVString")}} especificando no-referrer, client, ou uma URL. O padrão é client.
  • +
  • integrity: Contém o valor de integridade do sub-recurso da solicitação (exemplo: sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=).
  • +
+
+
+ +

Erros

+ + + + + + + + + + + + + + +
TipoDescrição
TypeErrorDesde Firefox 43, Request() lançará um TypeError se o URL tiver credenciais, tal como http://user:password@example.com.
+ +

Exemplo

+ +

Em nosso exemplo Fetch Request (veja Fetch Request live) nós criamos um novo objeto Request usando o construtor, em seguida, busque-o usando uma chamada {{domxref("GlobalFetch.fetch")}}. Como estamos buscando uma imagem, executamos o {{domxref("Body.blob")}} na resposta para fornecer o tipo MIME adequado para que ela seja manipulada corretamente. Em seguida, criamos uma URL do objeto e a exibimos em um Elemento {{htmlelement("img")}}.

+ +
var myImage = document.querySelector('img');
+
+var myRequest = new Request('flowers.jpg');
+
+fetch(myRequest).then(function(response) {
+  return response.blob();
+}).then(function(response) {
+  var objectURL = URL.createObjectURL(response);
+  myImage.src = objectURL;
+});
+ +

Em nosso Fetch Request with init example (veja Fetch Request init live) nós fazemos a mesma coisa, exceto que passamos em um objeto init quando invocamos fetch():

+ +
var myImage = document.querySelector('img');
+
+var myHeaders = new Headers();
+myHeaders.append('Content-Type', 'image/jpeg');
+
+var myInit = { method: 'GET',
+               headers: myHeaders,
+               mode: 'cors',
+               cache: 'default' };
+
+var myRequest = new Request('flowers.jpg',myInit);
+
+fetch(myRequest).then(function(response) {
+  ...
+});
+ +

Observe que você também pode passar o objeto init para a chamada fetch para obter o mesmo efeito, por exemplo:

+ +
fetch(myRequest,myInit).then(function(response) {
+  ...
+});
+ +

Você também pode usar um literal de objeto como headers em init.

+ +
var myInit = { method: 'GET',
+               headers: {
+                   'Content-Type': 'image/jpeg'
+               },
+               mode: 'cors',
+               cache: 'default' };
+
+var myRequest = new Request('flowers.jpg', myInit);
+
+ +

Você também pode passar um objeto {{domxref ("Request")}} para o construtor Request() para criar uma cópia do Request (isso é semelhante a chamar o método {{domxref("Request.clone", "clone()")}} .)

+ +
+
var copy = new Request(myRequest);
+
+
+ +
+

Nota: Este último uso é provavelmente útil apenas em ServiceWorkers.

+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('Fetch','#dom-request','Request()')}}{{Spec2('Fetch')}} 
+ +

Compatibilidade de Browser

+ + + +

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

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/response/index.html b/files/pt-br/web/api/response/index.html new file mode 100644 index 0000000000..554edd15db --- /dev/null +++ b/files/pt-br/web/api/response/index.html @@ -0,0 +1,130 @@ +--- +title: Response +slug: Web/API/Response +tags: + - API + - Experimental + - Fetch + - Fetch API + - Interface + - Reference + - Referencia + - Response + - Resposta +translation_of: Web/API/Response +--- +
{{APIRef("Fetch API")}}
+ +

A interface Response da Fetch API representa a resposta para uma requisição.

+ +

Você pode criar um novo objeto Response usando o construtor {{domxref("Response.Response()")}}, porém é mais provável você encontrar um objeto Response sendo retornado como o resultado de uma outra operação da API, por exemplo um service worker {{domxref("Fetchevent.respondWith")}}, ou um simples {{domxref("GlobalFetch.fetch()")}}.

+ +

Construtor

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

Propriedades

+ +
+
{{domxref("Response.headers")}} {{readonlyinline}}
+
Contém o objeto {{domxref("Headers")}} associado à resposta.
+
{{domxref("Response.ok")}} {{readonlyinline}}
+
Contém um valor booleano indicando se a resposta foi bem sucedida ("status" no intervalo 200-299) ou não.
+
{{domxref("Response.redirected")}} {{ReadOnlyInline}}
+
Indica se a resposta é ou não o resultado de um redirecionamento; isto é, sua lista de URL tem mais de uma entrada.
+
{{domxref("Response.status")}} {{readonlyinline}}
+
Contém o código de "status" da resposta (ex., 200 para um sucesso).
+
{{domxref("Response.statusText")}} {{readonlyinline}}
+
Contém a mensagem de "status" correspondente ao código de "status" (ex., OK para 200).
+
{{domxref("Response.type")}} {{readonlyinline}}
+
Contém o tipo da resposta (ex., basic, cors).
+
{{domxref("Response.url")}} {{readonlyinline}}
+
Contém a URL de resposta.
+
{{domxref("Response.useFinalURL")}}
+
Contém um valor boleano indicando se essa é a URL final da resposta.
+
+ +

Response implementa {{domxref("Body")}}, por isso também tem as seguintes propriedades disponíveis:

+ +
+
{{domxref("Body.body")}} {{readonlyInline}}
+
Um simples "getter" para ler do conteúdo do corpo através da interface {{domxref("ReadableStream")}}.
+
{{domxref("Body.bodyUsed")}} {{readonlyInline}}
+
Armazena um {{domxref("Boolean")}} que indica se o corpo já foi utilizado em uma resposta.
+
+ +

Métodos

+ +
+
{{domxref("Response.clone()")}}
+
Cria uma cópia do objeto Response.
+
{{domxref("Response.error()")}}
+
Retorna um novo objeto Response associado a um erro de rede.
+
{{domxref("Response.redirect()")}}
+
Cria uma nova resposta com uma URL diferente.
+
+ +

Response implementa {{domxref("Body")}}, por isso também tem as seguintes propriedades disponíveis:

+ +
+
{{domxref("Body.arrayBuffer()")}}
+
Recebe um "stream" {{domxref("Response")}} e lê até a conclusão. Retorna uma "promise" que resolve com um  {{domxref("ArrayBuffer")}}.
+
{{domxref("Body.blob()")}}
+
Recebe um "stream" {{domxref("Response")}} e lê até a conclusão. Retorna uma "promise" que resolve com um {{domxref("Blob")}}.
+
{{domxref("Body.formData()")}}
+
Recebe um "stream" {{domxref("Response")}} e lê até a conclusão. Retorna uma "promise" que resolve com um objeto {{domxref("FormData")}}.
+
{{domxref("Body.json()")}}
+
Recebe um "stream" {{domxref("Response")}} e lê até a conclusão. Retorna uma "promise" que resolve com o resultado do parseamento do texto do corpo como {{jsxref("JSON")}}.
+
{{domxref("Body.text()")}}
+
Recebe um "stream" {{domxref("Response")}} e lê até a conclusão. Retorna uma "promise" que resolve com um {{domxref("USVString")}} (texto).
+
+ +

Exemplos

+ +

Em nosso exemplo básico fetch (executar exemplo live) nós usamos uma simples chamada fetch() para pegar uma imagem e exibi-la em uma tag {{htmlelement("img")}}. A chamada fetch() retorna uma "promise", que resolve com o objeto Response associado com o recurso da operação "fetch". Você irá notar que como estamos solicitando uma imagem, nós precisamos executar {{domxref("Body.blob")}} ({{domxref("Response")}} implementa o "body") para dar à resposta seu tipo MIME correto.

+ +
var myImage = document.querySelector('.my-image');
+fetch('flowers.jpg').then(function(response) {
+  return response.blob();
+}).then(function(blob) {
+  var objectURL = URL.createObjectURL(blob);
+  myImage.src = objectURL;
+});
+ +

Você também pode usar o construtor {{domxref("Response.Response()")}} para criar seu objeto Response personalizado:

+ +
var myResponse = new Response();
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('Fetch','#response-class','Response')}}{{Spec2('Fetch')}}Initial definition
+ +

Compatibilidade entre Navegadores

+ + + +

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

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/rtccertificate/index.html b/files/pt-br/web/api/rtccertificate/index.html new file mode 100644 index 0000000000..a0ecf39c65 --- /dev/null +++ b/files/pt-br/web/api/rtccertificate/index.html @@ -0,0 +1,47 @@ +--- +title: RTCCertificate +slug: Web/API/RTCCertificate +tags: + - API + - Comunicação em tempo-real + - Interface + - RTCCertificate + - Refenrência + - WebRTC +translation_of: Web/API/RTCCertificate +--- +

{{APIRef("WebRTC")}}

+ +

A interface da WebRTC API fornece um objeto representando um certificado que uma {{domxref("RTCPeerConnection")}} usa para autênticar.

+ +

Propriedades

+ +
+
{{domxref("RTCCertificate.expires")}} {{readonlyinline}}
+
Retorna a data de expiração do certificado.
+
+ +

Especificação

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('WebRTC 1.0')}}{{Spec2('WebRTC 1.0')}}definição inicial.
+ +

Compatibilidade de Browser

+ +
+ + +

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

+
diff --git a/files/pt-br/web/api/rtcdatachannel/index.html b/files/pt-br/web/api/rtcdatachannel/index.html new file mode 100644 index 0000000000..27514ba598 --- /dev/null +++ b/files/pt-br/web/api/rtcdatachannel/index.html @@ -0,0 +1,130 @@ +--- +title: RTCDataChannel +slug: Web/API/RTCDataChannel +tags: + - Compatibilidade + - Navegadores + - Referencia +translation_of: Web/API/RTCDataChannel +--- +

{{APIRef("WebRTC")}}{{SeeCompatTable}}

+ +

A interface RTCDataChannel representa um canal de rede que pode ser usado para transferências bidirecionais de dados arbitrários de ponto a ponto. Todo canal de dados está associado a {{domxref("RTCPeerConnection")}}, e cada conexão de pares pode ter até um máximo teórico de 65,534 canais de dados (o limite real pode variar de navegador para navegador).

+ +

Para criar um canal de dados e pedir a um ponto remoto para se juntar a você, chame os metodos {{domxref("RTCPeerConnection")}}'s {{domxref("RTCPeerConnection.createDataChannel", "createDataChannel()")}}.  O interlocutor que está sendo convidado a trocar dados recebe um evento {{event("datachannel")}} (que possui o tipo {{domxref("RTCDataChannelEvent")}}) para informá-lo de que o canal de dados foi adicionado à conexão.

+ +

{{InterfaceOverview("WebRTC")}}

+ +

Exemplo

+ +
var pc = new RTCPeerConnection();
+var dc = pc.createDataChannel("my channel");
+
+dc.onmessage = function (event) {
+  console.log("received: " + event.data);
+};
+
+dc.onopen = function () {
+  console.log("datachannel open");
+};
+
+dc.onclose = function () {
+  console.log("datachannel close");
+};
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{ SpecName('WebRTC 1.0', '#idl-def-RTCDataChannel', 'RTCDataChannel') }}{{ Spec2('WebRTC 1.0') }}Especificação inicial
+ +

Compatibilidade do navegador

+ +

{{ CompatibilityTable }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{ CompatVersionUnknown }}{{ CompatGeckoDesktop(22) }} [1]{{ CompatNo }}{{ CompatVersionUnknown }}{{ CompatUnknown }}
onbufferedamountlow{{CompatChrome(56)}}{{ CompatNo }}{{ CompatNo }}{{CompatOpera(43)}}{{ CompatNo }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatChrome(29)}}{{CompatChrome(29)}}{{ CompatGeckoMobile(22) }} [1]{{ CompatNo }}{{ CompatVersionUnknown }}{{ CompatNo }}
onbufferedamountlow{{CompatChrome(56)}}{{CompatChrome(56)}}{{ CompatNo }}{{CompatUnknown}}{{CompatOperaMobile(43)}}{{CompatUnknown}}
+
+ +

[1] A interface é chamada DataChannel e não RTCDataChannel no Firefox. No entanto, uma ligação foi implementada desde o Firefox 24 para que qualquer um dos nomes funcione.

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/rtcicetransport/index.html b/files/pt-br/web/api/rtcicetransport/index.html new file mode 100644 index 0000000000..008822d95c --- /dev/null +++ b/files/pt-br/web/api/rtcicetransport/index.html @@ -0,0 +1,91 @@ +--- +title: RTCIceTransport +slug: Web/API/RTCIceTransport +tags: + - API + - Audio + - Interface + - RTCIceTransport + - Referencia + - Video + - WebRTC + - WebRTC API + - rtc +translation_of: Web/API/RTCIceTransport +--- +
{{APIRef("WebRTC")}}
+ +

A interface RTCIceTransport fornece informação a respeito da camada de transporte {{Glossary("ICE")}} na qual os dados estão sendo enviados e recebidos. Isso é particulamente útil se você precisa acessar as informações de estado da conexão.

+ +

Propriedades

+ +

A interface RTCIceTransport herda propriedades de sua interface pai, {{domxref("EventTarget")}}. ele também oferta as seguintes propriedades:

+ +
+
{{domxref("RTCIceTransport.component", "component")}} {{ReadOnlyInline}}
+
O componente ICE que esta sendo usado pela transporte. O valor é uma das strings do {{domxref("RTCIceTransport")}} tipo enumerável: {{Glossary("RTP", '"RTP"')}} ou "RTSP".
+
{{domxref("RTCIceTransport.gatheringState", "gatheringState")}} {{ReadOnlyInline}}
+
O {{domxref("DOMString")}} indica em qual estado de recolhimento o agente ICE esta atualmente. O valor é um dos incluidos no {{domxref("RTCIceGathererState")}} tipo enumerável: "new", "gathering", ou "complete".
+
{{domxref("RTCIceTransport.role", "role")}} {{ReadOnlyInline}}
+
Retorna uma {{domxref("DOMString")}} cujo valor é um membro do tipo enumerável {{domxref("RTCIceRole")}}: "controlling" ou "controlled"; Isso indica se o agente ICE é aquele que toma a decisão final quanto ao par candidato a ser usado ou não.
+
{{domxref("RTCIceTransport.state", "state")}} {{ReadOnlyInline}}
+
O {{domxref("DOMString")}} indica qual o atual estado do agente ICE. O valor do state pode ser usado para determinar se o agente ICE fez uma conecxão inicial usando uma par de candidatos viável ("connected"), fez a seleção final do par de candidatos ("completed"), ou em um estado de erro ("failed"), além de outros estados. Veja o tipo enumerável {{domxref("RTCIceTransportState")}} para uma lista completa de estados.
+
+ +

Métodos

+ +

Também inclui métodos da interface pai {{domxref("EventTarget")}}.

+ +
+
{{domxref("RTCIceTransport.getLocalCandidates", "getLocalCandidates()")}}
+
Retorna um array de objetos {{domxref("RTCIceCandidate")}}, cada descrevendo um dos candidatos ICE que foram reunidos para o dispositivo local até o momento. Esses são os mesmos candidatos que já foram enviados para o peer remoto, enviando um evento {{event("icecandidate")}} ao {{domxref("RTCPeerConnection")}} para transmissão.
+
{{domxref("RTCIceTransport.getLocalParameters", "getLocalParameters()")}}
+
Retorna o objeto {{domxref("RTCIceParameters")}} descrevendo o parâmetro ICE estabelecido através de uma ligação ao método {{domxref("RTCPeerConnection.setLocalDescription()")}}. Retorna null se os parâmetros ainda não foram recebidos.
+
{{domxref("RTCIceTransport.getRemoteCandidates", "getRemoteCandidates()")}}
+
Retorna um array de objetos {{domxref("RTCIceCandidate")}}, um para cada candidato do dispositivo remoto, que foram recebidos pelo local final da {{domxref("RTCPeerConnection")}} e entrega ao ICE através da chamada {{domxref("RTCPeerConnection.addIceCandidate()", "addIceCandidate()")}}.
+
{{domxref("RTCIceTransport.getRemoteParameters", "getRemoteParameters()")}}
+
Retorna um objeto {{domxref("RTCIceParameters")}} contendo os parâmetros ICE para o dispositivo remoto, como definido por uma chamada para {{domxref("RTCPeerConnection.setRemoteDescription()")}}. Se setRemoteDescription() não foi chamada ainda, o retorno será null.
+
{{domxref("RTCIceTransport.getSelectedCandidatePair", "getSelectedCandidatePair()")}}
+
Retorna um objeto {{domxref("RTCIceCandidatePair")}} que identifica os dois candidatos — um para cada conexão — que foram selecionados até o momento. É possível que um par melhor sejá encontrado e selecionado posteriormente; Se você precisar acompanhar isso, veja o evento {{event("selectedcandidatepairchange")}}. Se nenhum par de candidatos foi selecionado ainda o valor retornado será null.
+
+ +

Eventos

+ +

Escute esses eventos usando {{domxref("EventTarget.addEventListener", "addEventListener()")}} ou atribuindo um event listener para oneventname propriedade dessa interface.

+ +
+
{{domxref("RTCIceTransport.gatheringstatechange_event", "gatheringstatechange")}}
+
Enviado ao objeto {{domxref("RTCIceTransport")}} para indicar que o valor da propriedade {{domxref("RTCIceTransport.gatheringState", "gatheringState")}} foi alterado, indicando uma mudança no processo de negociação de candidatos ICE deste transporte.
+ Também esta disponível através da propriedade event handler {{domxref("RTCIceTransport.ongatheringstatechange", "ongatheringstatechange")}}.
+
{{domxref("RTCIceTransport.selectedcandidatepairchange_event", "selectedcandidatepairchange")}}
+
Enviado para o RTCIceTransport quando um novo, melhor par de candidatos foi selecionado para descrever a conectividade entre os dois peers. Isso pode ocorrer durante a negotiação ou a renegociação, incluindo depois de um ICE restart, que reusa os objetos RTCIceTransport existentes. O par de candidatos atuais pode ser obtido usando {{domxref("RTCIceTransport.getSelectedCandidatePair", "getSelectedCandidatePair()")}}.
+ Também esta disponível através da propriedade event handler {{domxref("RTCIceTransport.onselectedcandidatepairchange", "onselectedcandidatepairchange")}}.
+
{{domxref("RTCIceTransport.statechange_event", "statechange")}}
+
Enviado par a instancia do RTCIceTransport quando o valor da propriedade {{domxref("RTCIceTransport.state", "state")}} foi alterada, indicando que o processo de recolhimento ICE mudou de estado.
+ Também esta disponível através da propriedade event handler {{domxref("RTCIceTransport.onstatechange", "onstatechange")}}.
+
+ +

Especificação

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('WebRTC 1.0', '#dom-rtcicetransport', 'RTCIceTransport')}}{{Spec2('WebRTC 1.0')}}Definição initial.
+ +

Compatibilidade de Browser

+ +
+ + +

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

+
diff --git a/files/pt-br/web/api/rtcpeerconnection/connectionstate/index.html b/files/pt-br/web/api/rtcpeerconnection/connectionstate/index.html new file mode 100644 index 0000000000..102b310ecd --- /dev/null +++ b/files/pt-br/web/api/rtcpeerconnection/connectionstate/index.html @@ -0,0 +1,64 @@ +--- +title: RTCPeerConnection.connectionState +slug: Web/API/RTCPeerConnection/connectionState +translation_of: Web/API/RTCPeerConnection/connectionState +--- +

{{APIRef("WebRTC")}}

+ +

A propriedade connectionState do tipo somente leitura da interface {{domxref("RTCPeerConnection")}} indica o estado atual da conexão em par, devolvendo um valor em string específicado por um enum {{domxref("RTCPeerConnection")}}.

+ +

Quando o valor da propriedade muda, o evento {{event("connectionstatechange")}} é enviado para a intância {{domxref("RTCPeerConnection")}}.

+ + + +

Syntax

+ +
var connectionState = RTCPeerConnection.connectionState;
+ +

Value

+ +

O estado atual da conexão, como um valor do enum RTCPeerConnectionState.

+ +

{{page("/en-US/docs/Web/API/RTCPeerConnection", "RTCPeerConnectionState enum", 0, 1)}}

+ +

Example

+ +
var pc = new RTCPeerConnection(configuration);
+
+/* ... */
+
+var connectionState = pc.connectionState;
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('WebRTC 1.0', '#widl-RTCPeerConnection-connectionState', 'RTCPeerConnection.connectionState') }}{{ Spec2('WebRTC 1.0') }}Initial specification.
+ +

Browser compatibility

+ + + +

{{Compat("api.RTCPeerConnection.connectionState")}}

+ +

See also

+ + diff --git a/files/pt-br/web/api/rtcpeerconnection/index.html b/files/pt-br/web/api/rtcpeerconnection/index.html new file mode 100644 index 0000000000..b7cd9c92fb --- /dev/null +++ b/files/pt-br/web/api/rtcpeerconnection/index.html @@ -0,0 +1,360 @@ +--- +title: RTCPeerConnection +slug: Web/API/RTCPeerConnection +translation_of: Web/API/RTCPeerConnection +--- +
{{APIRef('WebRTC')}}
+ +

A interface RTCPeerConnection cria uma conexão WebRTC entre um computador local e um ponto remoto. Esta interface fornece métodos que possibilitam a conexão a um ponto remoto, mantendo e monitorando a conexão, e fechando-a quando não for mais necessária.

+ +

{{InheritanceDiagram}}

+ +

{{InterfaceOverview("WebRTC")}}

+ +

Método obsoleto

+ +

O método a seugir está obsoleto há muito tempo e nunca foi implementado nos principais navegadores.

+ +
+
{{domxref("RTCPeerConnection.createDTMFSender()")}} {{obsolete_inline}}
+
Cria um novo {{domxref("RTCDTMFSender")}},associado ao específico {{domxref("MediaStreamTrack")}}, que irá permitir enviar {{Glossary("DTMF")}} sinal de telefone pela conexão
+
+ +

Eventos

+ +

Monitore esses eventos utilizando {{domxref("EventTarget.addEventListener", "addEventListener()")}} ou atribuindo um ouvinte de evento à propriedade oneventname dessa interface.

+ + + +
+
{{domxref("RTCPeerConnection.connectionstatechange_event", "connectionstatechange")}}
+
Enviado ao objeto RTCPeerConnection quando o status de conectividade geral do RTCPeerConnection é alterado.
+ Também disponível através da propriedade do manipulador de eventos {{domxref ("RTCPeerConnection.onconnectionstatechange", "onconnectionstatechange")}}.
+
+ + + + + +
+
{{domxref("RTCPeerConnection.datachannel_event", "datachannel")}}
+
Sent to the RTCPeerConnection object when the remote peer adds an {{domxref("RTCDataChannel")}} to the connection.
+ Also available through the {{domxref("RTCPeerConnection.ondatachannel", "ondatachannel")}} event handler property.
+
{{domxref("RTCPeerConnection.icecandidate_event", "icecandidate")}}
+
Sent to the object when a new ICE candidate arrives during negotiation.
+ Also available using the {{domxref("RTCPeerConnection.onicecandidate", "onicecandidate")}} event handler property.
+
{{domxref("RTCPeerConnection.iceconnectionstatechange_event", "iceconnectionstatechange")}}
+
Sent to the RTCPeerConnection when the state of the ICE connection changes, such as when it disconnects.
+ Also available using the {{domxref("RTCPeerConnection.oniceconnectionstatechange", "oniceconnectionstatechange")}} event handler property.
+
{{domxref("RTCPeerConnection.negotiationneeded_event", "negotiationneeded")}}
+
Sent to the RTCPeerConnection when it's time to perform ICE negotiation. This can happen both when first opening a connection as well as any time it's necessary to adapt to changing network conditions.
+ Also available using the {{domxref("RTCPeerConnection.onnegotiationneeded", "onnegotiationneeded")}} event handler property.
+
{{domxref("RTCPeerConnection.icecandidate_event", "icecandidate")}}
+
Sent to the peer connection to request that the specified candidate be transmitted to the remote peer.
+ Also available through the {{domxref("RTCPeerConnection.onicecandidate", "onicecandidate")}} event handler property.
+
{{domxref("RTCPeerConnection.negotiationneeded_event", "negotiationneeded")}}
+
Sent to the RTCPeerConnection when negotiation or renegotiation of the ICE connection needs to be performed. The receiver should respond by creating an offer and sending it to the other peer.
+ Also available as the {{domxref("RTCPeerConnection.onnegotiationneeded", "onnegotiationneeded")}} event handler property.
+
{{domxref("RTCPeerConnection.signalingstatechange_event", "signalingstatechange")}}
+
The signalingstatechange event is sent to the RTCPeerConnection when the connection's ICE signaling state changes.
+ Also available through the {{domxref("RTCPeerConnection.onsignalingstatechange", "onsignalingstatechange")}} event handler property.
+
{{domxref("RTCPeerConnection.track_event", "track")}}
+
The track event is sent after a new track has been added to one of the {{domxref("RTCRtpReceiver")}} instances which comprise the connection.
+ Available as the {{domxref("RTCPeerConnection.ontrack", "ontrack")}} event handler property.
+
+ +

Obsolete events

+ +
+
{{domxref("RTCPeerConnection.addstream_event", "addstream")}} {{obsolete_inline}}
+
Sent when a new {{domxref("MediaStream")}} has been added to the connection. Instead of watching for this obsolete event, you should watch each for {{domxref("RTCPeerConnection.track_event", "track")}} events; one is sent for each {{domxref("MediaStreamTrack")}} added to the connection.
+ Available as the {{domxref("RTCPeerConnection.onaddstream", "onaddstream")}} event handler property.
+
{{domxref("RTCPeerConnection.identityresult_event", "identityresult")}} {{obsolete_inline}}
+
In old versions of the WebRTC specification, this event was used to indicate that an identity assertion is available. Now, you should instead wait for a the promise returned by {{domxref("RTCPeerConnection.peerIdentity", "peerIdentity")}} to resolve with an identity.
+ Also available using the {{domxref("RTCPeerConnection.onidentityresult", "onidentityresult")}} event handler property.
+
{{domxref("RTCPeerConnection.idpassertionerror_event", "idpassertionerror")}} {{obsolete_inline}}
+
In old versions of the WebRTC specification, this event was used to indicate that an error occurred while attempting to generate an identity assertion. Now, you should instead wait for a the promise returned by {{domxref("RTCPeerConnection.peerIdentity", "peerIdentity")}} to be rejected with an error.
+ Also available as the {{domxref("RTCPeerConnection.onidpassertionerror", "onidpinsertionerror")}} event handler property.
+
{{domxref("RTCPeerConnection.idpvalidationerror_event", "idpvalidationerror")}} {{obsolete_inline}}
+
In old versions of the WebRTC specification, this event was used to indicate that an error occurred while attempting to validate an identity assertion. Now, you should instead wait for a the promise returned by {{domxref("RTCPeerConnection.peerIdentity", "peerIdentity")}} to be rejected with an error.
+ Also available using the {{domxref("RTCPeerConnection.onpeeridentity", "onpeerdentity")}} event handler property.
+
{{domxref("RTCPeerConnection.peeridentity_event", "peeridentity")}} {{obsolete_inline}}
+
In old versions of the WebRTC specification, this event was used to deliver a received identity. Now, you should instead wait for a the promise returned by {{domxref("RTCPeerConnection.peerIdentity", "peerIdentity")}} to resolve with an identity.
+
{{domxref("RTCPeerConnection.removestream_event", "removestream")}} {{obsolete_inline}}
+
Sent to the RTCPeerConnection when a {{domxref("MediaStream")}} is removed from the connection. Instead of watching for this obsolete event, you should watch each stream for {{domxref("MediaStream.removetrack_event", "removetrack")}} events on each stream within the RTCPeerConnection.
+ Also available as the {{domxref("RTCPeerConnection.onremovestream", "onaddstream")}} event handler property.
+
+ +

Constants

+ +

RTCBundlePolicy enum

+ +

The RTCBundlePolicy enum defines string constants which are used to request a specific policy for gathering ICE candidates if the remote peer isn't compatible with the SDP BUNDLE standard for bundling multiple media streams on a single transport link.

+ +
+

Note: In technical terms, a BUNDLE lets all media flow between two peers flow across a single 5-tuple; that is, from the same IP and port on one peer to the same IP and port on the other peer, using the same transport protocol.

+
+ + + + + + + + + + + + + + + + + + + + + + +
ConstantDescription
"balanced"On BUNDLE-aware connections, the ICE agent should gather candidates for all of the media types in use (audio, video, and data). Otherwise, the ICE agent should only negotiate one audio and video track on separate transports.
"max-compat"The ICE agent should gather candidates for each track, using separate transports to negotiate all media tracks for connections which aren't BUNDLE-compatible.
"max-bundle"The ICE agent should gather candidates for just one track. If the connection isn't BUNDLE-compatible, then the ICE agent should negotiate just one media track.
+ +

RTCIceConnectionState enum

+ +

The RTCIceConnectionState enum defines the string constants used to describe the current state of the ICE agent and its connection to the ICE server (that is, the {{Glossary("STUN")}} or {{Glossary("TURN")}} server).

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ConstantDescription
"new"The ICE agent is gathering addresses or is waiting to be given remote candidates through calls to {{domxref("RTCPeerConnection.addIceCandidate()")}} (or both).
"checking"The ICE agent has been given one or more remote candidates and is checking pairs of local and remote candidates against one another to try to find a compatible match, but has not yet found a pair which will allow the peer connection to be made. It's possible that gathering of candidates is also still underway.
"connected"A usable pairing of local and remote candidates has been found for all components of the connection, and the connection has been established. It's possible that gathering is still underway, and it's also possible that the ICE agent is still checking candidates against one another looking for a better connection to use.
"completed"The ICE agent has finished gathering candidates, has checked all pairs against one another, and has found a connection for all components.
"failed"The ICE candidate has checked all candidates pairs against one another and has failed to find compatible matches for all components of the connection. It is, however, possible that the ICE agent did find compatible connections for some components.
"disconnected"Checks to ensure that components are still connected failed for at least one component of the {{domxref("RTCPeerConnection")}}. This is a less stringent test than "failed" and may trigger intermittently and resolve just as spontaneously on less reliable networks, or during temporary disconnections. When the problem resolves, the connection may return to the "connected" state.
"closed"The ICE agent for this {{domxref("RTCPeerConnection")}} has shut down and is no longer handling requests.
+ +

RTCIceGatheringState enum

+ +

The RTCIceGatheringState enum defines string constants which reflect the current status of ICE gathering, as returned using the {{domxref("RTCPeerConnection.iceGatheringState")}} property. You can detect when this value changes by watching for an event of type {{event("icegatheringstatechange")}}.

+ + + + + + + + + + + + + + + + + + + + + + +
ConstantDescription
"new"The peer connection was just created and hasn't done any networking yet.
"gathering"The ICE agent is in the process of gathering candidates for the connection.
"complete"The ICE agent has finished gathering candidates. If something happens that requires collecting new candidates, such as a new interface being added or the addition of a new ICE server, the state will revert to "gathering" to gather those candidates.
+ +

RTCIceTransportPolicy enum

+ +

The RTCIceTransportPolicy enum defines string constants which can be used to limit the transport policies of the ICE candidates to be considered during the connection process.

+ + + + + + + + + + + + + + + + + + + + + + +
ConstantDescription
"all"All ICE candidates will be considered.
"public" {{obsolete_inline}}Only ICE candidates with public IP addresses will be considered. Removed from the specification's May 13, 2016 working draft.
"relay"Only ICE candidates whose IP addresses are being relayed, such as those being passed through a TURN server, will be considered.
+ +

RTCPeerConnectionState enum

+ +

The RTCPeerConnectionState enum defines string constants which describe states in which the RTCPeerConnection may be. These values are returned by the {{domxref("RTCPeerConnection.connectionState", "connectionState")}} property. This state essentially represents the aggregate state of all ICE transports (which are of type {{domxref("RTCIceTransport")}} or {{domxref("RTCDtlsTransport")}}) being used by the connection.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ConstantDescription
"new"At least one of the connection's ICE transports ({{domxref("RTCIceTransport")}}s or {{domxref("RTCDtlsTransport")}}s) are in the "new" state, and none of them are in one of the following states: "connecting", "checking", "failed", or "disconnected", or all of the connection's transports are in the "closed" state.
"connecting"One or more of the ICE transports are currently in the process of establishing a connection; that is, their RTCIceConnectionState is either "checking" or "connected", and no transports are in the "failed" state. <<< Make this a link once I know where that will be documented
"connected"Every ICE transport used by the connection is either in use (state "connected" or "completed") or is closed (state "closed"); in addition, at least one transport is either "connected" or "completed".
"disconnected"At least one of the ICE transports for the connection is in the "disconnected" state and none of the other transports are in the state "failed", "connecting", or "checking".
"failed"One or more of the ICE transports on the connection is in the "failed" state.
"closed" +

The RTCPeerConnection is closed.

+ +

This value was in the RTCSignalingState enum (and therefore found by reading the value of the {{domxref("RTCPeerConnection.signalingState", "signalingState")}}) property until the May 13, 2016 draft of the specification.

+
+ +

RTCRtcpMuxPolicy enum

+ +

The RTCRtcpMuxPolicy enum defines string constants which specify what ICE candidates are gathered to support non-multiplexed RTCP. <<<add a link to info about multiplexed RTCP.

+ + + + + + + + + + + + + + + + + + +
ConstantDescription
"negotiate"Instructs the ICE agent to gather both {{Glossary("RTP")}} and {{Glossary("RTCP")}} candidates. If the remote peer can multiplex RTCP, then RTCP candidates are multiplexed atop the corresponding RTP candidates. Otherwise, both the RTP and RTCP candidates are returned, separately.
"require"Tells the ICE agent to gather ICE candidates for only RTP, and to multiplex RTCP atop them. If the remote peer doesn't support RTCP multiplexing, then session negotiation fails.
+ +

RTCSignalingState enum

+ +

The RTCSignalingState enum specifies the possible values of {{domxref("RTCPeerConnection.signalingState")}}, which indicates where in the process of signaling the exchange of offer and answer the connection currently is.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ConstantDescription
"stable"There is no ongoing exchange of offer and answer underway. This may mean that the {{domxref("RTCPeerConnection")}} object is new, in which case both the {{domxref("RTCPeerConnection.localDescription", "localDescription")}} and {{domxref("RTCPeerConnection.remoteDescription", "remoteDescription")}} are null; it may also mean that negotiation is complete and a connection has been established.
"have-local-offer"The local peer has called {{domxref("RTCPeerConnection.setLocalDescription()")}}, passing in SDP representing an offer (usually created by calling {{domxref("RTCPeerConnection.createOffer()")}}), and the offer has been applied successfully.
"have-remote-offer"The remote peer has created an offer and used the signaling server to deliver it to the local peer, which has set the offer as the remote description by calling {{domxref("RTCPeerConnection.setRemoteDescription()")}}.
"have-local-pranswer"The offer sent by the remote peer has been applied and an answer has been created (usually by calling {{domxref("RTCPeerConnection.createAnswer()")}}) and applied by calling {{domxref("RTCPeerConnection.setLocalDescription()")}}. This provisional answer describes the supported media formats and so forth, but may not have a complete set of ICE candidates included. Further candidates will be delivered separately later.
"have-remote-pranswer"A provisional answer has been received and successfully applied in response to an offer previously sent and established by calling setLocalDescription().
"closed" {{obsolete_inline}} +

A conexão é fechada.

+ +
+

Note: This value moved into the RTCPeerConnectionState enum in the May 13, 2016 draft of the specification, as it reflects the state of the RTCPeerConnection, not the signaling connection. You now detect a closed connection by checking for {{domxref("RTCPeerConnection.connectionState", "connectionState")}} to be "closed" instead.

+
+
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebRTC 1.0', '#interface-definition', 'RTCPeerConnection')}}{{Spec2('WebRTC 1.0')}}Initial definition.
+ +

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git "a/files/pt-br/web/api/sele\303\247\303\243o/index.html" "b/files/pt-br/web/api/sele\303\247\303\243o/index.html" new file mode 100644 index 0000000000..9cac677942 --- /dev/null +++ "b/files/pt-br/web/api/sele\303\247\303\243o/index.html" @@ -0,0 +1,206 @@ +--- +title: Seleção +slug: Web/API/Seleção +tags: + - API + - Experimental + - Interface + - Referencia + - Seleção +translation_of: Web/API/Selection +--- +
{{ ApiRef("DOM") }}{{SeeCompatTable}}
+ +

Um objeto Selection representa um intervalo do texto selecionado pelo usuário ou a posição atual do cursor. Para obter o objeto Selection para inspecionar ou modificar, use {{DOMxRef("Window.getSelection()")}}.

+ +

O usuário pode fazer a seleção da esquerda para a direita (na orientação do documento) ou da direita para a esquerta (orientação inversa do documento). O atributo anchor (âncora) é onde o usuário iniciou a seleção e o atributo focus (foco) é onde o usuário terminou a seleção. Se você fizer a seleção utilizando um mouse no desktop, o anchor é definido onde você pressionou o botão do mouse e o focus é definido onde você soltou o botão do mouse. Anchor e focus não devem ser confundidos com a posição inicial e final da seleção, pois o anchor pode ser definido antes do focus ou vice versa, dependendo da direção em que você fez sua seleção.

+ +

Propriedades

+ +
+
{{DOMxRef("Selection.anchorNode")}}{{ReadOnlyInline}}
+
Retorna o {{DOMxRef("Node")}} onde a seleção começou.
+
{{DOMxRef("Selection.anchorOffset")}}{{ReadOnlyInline}}
+
Retorna um número representando o deslocamento do anchor dentro do elemento Se o elemento for do tipo text node, o número retornado será o número de caracteres no elemento que precedem o anchor (clique inicial da seleção). Se o elemento for do tipo element (qualquer tag html que não seja text node), o número retornado será o número de nós filhos do elemento que precedem o anchor.
+
{{DOMxRef("Selection.focusNode")}}{{ReadOnlyInline}}
+
Retorna o {{DOMxRef("Node")}} onde a seleção termina.
+
{{DOMxRef("Selection.focusOffset")}}{{ReadOnlyInline}}
+
Retorna um número representando o deslocamento do focus dentro do elemento Se o elemento for do tipo text node, o número retornado será o número de caracteres no elemento que precedem o focus (posição onde o mouse foi solto). Se o elemento for do tipo element (qualquer tag html que não seja text node), o número retornado será o número de nós filhos do elemento que precedem o focus.
+
{{DOMxRef("Selection.isCollapsed")}}{{ReadOnlyInline}}
+
Retorna um valor booleano indicando se o início e o final da seleção são a mesma posição, ou seja, começou e terminou no mesmo lugar.
+
{{DOMxRef("Selection.rangeCount")}}{{ReadOnlyInline}}
+
Retorna no número de intervalos da seleção.
+
{{DOMxRef("Selection.type")}}{{ReadOnlyInline}}
+
Retorna um {{DOMxRef("DOMString")}} descrevento o tipo da seleção atual.
+
+ +

Métodos

+ +
+
{{DOMxRef("Selection.addRange()")}}
+
Um objeto {{DOMxRef("Range")}} que será adicionado na seleção.
+
{{DOMxRef("Selection.collapse()")}}
+
Colapsa a seleção atual em um único ponto.
+
{{DOMxRef("Selection.collapseToEnd()")}}
+
Colapsa a seleção para o final do último intervalo na seleção.
+
{{DOMxRef("Selection.collapseToStart()")}}
+
Colapsa a seleção para o início do primeiro intervalo na seleção.
+
{{DOMxRef("Selection.containsNode()")}}
+
Indica se um certo nó é parte da seleção.
+
{{DOMxRef("Selection.deleteFromDocument()")}}
+
Apaga o conteúdo da seleção do documento.
+
{{DOMxRef("Selection.empty()")}}
+
Remove todos os intervalos da seleção. Este é um apelido para removeAllRanges() — Veja {{DOMxRef("Selection.removeAllRanges()")}} para mais detalhes.
+
{{DOMxRef("Selection.extend()")}}
+
Move o focus (final da seleção) para um ponto específico.
+
{{DOMxRef("Selection.getRangeAt()")}}
+
Retorna um objeto {{DOMxRef("Range")}} represetando um dos intervalos atualmente selecionados.
+
{{DOMxRef("Selection.modify()")}}{{Non-standard_Inline}}
+
Altera a seleção atual.
+
{{DOMxRef("Selection.removeRange()")}}
+
Remove um intervalo da seleção.
+
{{DOMxRef("Selection.removeAllRanges()")}}
+
Remove todos os intervalos da seleção.
+
{{DOMxRef("Selection.selectAllChildren()")}}
+
Adiciona todos os filhos do nó especificado para a seleção.
+
{{DOMxRef("Selection.setBaseAndExtent()")}}
+
Define que a seleção será um intervalo incluindo todos ou partes dos dois nós DOM especificados, e qualquer conteúdo entre esses nós.
+
{{DOMxRef("Selection.setPosition()")}}
+
Colapsa a seleção atual para um único ponto. Este é um apelido para collapse() — Veja {{DOMxRef("Selection.collapse()")}} para mais detalhes.
+
{{DOMxRef("Selection.toString()")}}
+
Retorna uma string atualmente representada pelo objeto selection, i.e. o texto atualmente selecionado.
+
+ +

Notas

+ +

Representação da seleção em formato de String

+ +

Chamando a função {{DOMxRef("Selection.toString()")}} retorna o texto selecionado, e.g.:

+ +
var selObj = window.getSelection();
+window.alert(selObj);
+
+ +

Perceba que usando um objeto selection como argumento de window.alert executará o metodo toString automaticamente.

+ +

Multiplos intervalos em uma seleção

+ +

Um objeto selection representa os {{DOMxRef("range","intervalos")}} que o usuário selecionou.
+ Normalmente é apenas um intervalo, acessado da seguinte forma:

+ +
+
var selObj = window.getSelection();
+var range  = selObj.getRangeAt(0);
+
+ + + +

Como consta nas Especificações da API de seleção, a API foi inicialmente criada pela Netscape e usados multiplos intervalos, por instância, para permitir ao usuário selecionar uma coluna de uma {{HTMLElement("table")}}. Outros navegadores como Gecko não implementaram multiplos intervalos, e a especificação exige que a seleção sempre tenha um único intervalo.

+ +

Seleção e foco de input

+ +

Seleção e foco de input (indicado por {{DOMxRef("Document.activeElement")}}) tem uma relação complexa, que depende do navegador. Para um código compatível com vários navegadores, o melhor é manter os códigos separados.

+ +

O Safari e o Chrome (ao contrário do Firefox) historicamente foca no elemento contendo a seleção quando a seleção é modificada programaticamente, mas isto pode mudar no futuro (veja W3C bug 14383 e {{WebKitBug("38696")}}).

+ +

Comportamento da API de Seleção em termos de edição e alterações de foco do host

+ +

A API de Seleção tem um comportamento comum (i.e. compartilhado entre navegadores) que define como o comportamento do foco muda para elemento editável, após alguns desses métodos serem executados.

+ +

Os comportamentos são que um elemento editado recebe o foco se anteriormente a seleção estiver fora dele, então um método da API de seleção é executado e causa uma nova seleção que será feita em um único intervalo dentro do elemento sendo editado. O foco então é movido para o final do elemento.

+ +
+

Nota: Os métodos da API de seleção, move o foco apenas para o elemento sendo editado, não para outro elemento que pode receber o foco (e.g. {{HTMLElement("a")}}).

+
+ +

O comportamento acima é aplicado para as seleções feitas usando os seguintes métodos:

+ + + +

e quando o intervalo é modificado usando os seguintes métodos:

+ + + +

Glossário

+ +

Outras palavras chaves usadas nesta seção.

+ +
+
anchor
+
O anchor de uma seleção é o ponto inicial da seleção. Quando a seleção é feita com um mouse, é onde o botão do mouse é inicialmente pressionado. Quando o usuário altera a seleção usando o mouse ou teclado, o anchor não move.
+
Elemento editável
+
Um elemento editável — i.e. um elemento HTML com o atributo {{htmlattrxref("contenteditable")}} definido, ou o HTML filho de um documento estiver com o {{DOMxRef("Document.designMode", "designMode")}} habilitado.
+
foco de uma seleção
+
O foco da seleção é o ponto final da seleção. Quando feita a seleção com um mouse, o focus é onde o botão do mouse foi solto. Quando o usuário muda a seleção usando o mouse ou teclado, o focus é o final da seleção que move. Nota: Não é o mesmo que o elemento selecionado do documento, como retornado em {{DOMxRef("document.activeElement")}}.
+
intervalo
+
Um intervalo é uma parte contínua do documento. Um intervalo pode conter nós inteiros ou partes de nós, como uma parte de um text node. Um usuário normalmente irá selecionar um único intervalo por vez, mas é possível que o usuário selecione multiplos intervalos (e.g. usando a tecla Control). Um intervalo pode ser obtido de uma seleção como um objeto {{DOMxRef("range")}}. Um objeto de intervalo pode ser criado no DOM e programaticamente adicionada ou removida de uma seleção.
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Selection API", "#selection-interface", "Seleção")}}{{Spec2("Selection API")}}A especificação da API de Seleção é baseada na especificação da API de edição HTML e focada na funcionalidade relacionada à seleção.
{{SpecName("HTML Editing", "#selection", "Seleção")}}{{Spec2("HTML Editing")}}Definição incial (antiga).
+ +

Compatibilidade de navegadores

+ + + +

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

+ +

Veja também

+ + + +

Notas da Gecko

+ + + +
+
diff --git a/files/pt-br/web/api/sensor/index.html b/files/pt-br/web/api/sensor/index.html new file mode 100644 index 0000000000..afc91f60d5 --- /dev/null +++ b/files/pt-br/web/api/sensor/index.html @@ -0,0 +1,89 @@ +--- +title: Sensor +slug: Web/API/Sensor +tags: + - API + - Generic Sensor API + - Interface + - NeedsTranslation + - Reference + - Sensor + - Sensor APIs + - Sensors + - TopicStub +translation_of: Web/API/Sensor +--- +
{{APIRef("Generic Sensor API")}}
+ +

The Sensor interface of the the Sensor APIs is the base class for all the other sensor interfaces. This interface cannot be used directly. Instead it provides properties, event handlers, and methods accessed by interfaces that inherit from it.

+ +

If a feature policy blocks use of a feature it is because your code is inconsistent with the policies set on your server. This is not something that would ever be shown to a user. See {{httpheader('Feature-Policy')}} for implementation instructions.

+ +

Interfaces based on Sensor

+ +

Below is a list of interfaces based on the Sensor interface.

+ +
+ +
+ +

Properties

+ +
+
{{domxref('Sensor.activated')}} {{readonlyinline}}
+
Returns a {{jsxref("Boolean")}} indicating whether the sensor is active.
+
{{domxref('Sensor.hasReading')}} {{readonlyinline}}
+
Returns a {{jsxref("Boolean")}} indicating whether the sensor has a reading.
+
{{domxref('Sensor.timestamp')}} {{readonlyinline}}
+
Returns the time stamp of the latest sensor reading.
+
+ +

Event handlers

+ +
+
{{domxref('Sensor.onerror')}}
+
Called when an error occurs on one of the child interfaces of the Sensor interface.
+
{{domxref('Sensor.onreading')}}
+
Called when a reading is taken on one of the child interfaces of the Sensor interface.
+
{{domxref('Sensor.onactivate')}}
+
Called when one of the Sensor interface's becomes active.
+
+ +

Methods

+ +
+
{{domxref('Sensor.start()')}}
+
Activates one of the sensors based on Sensor.
+
{{domxref('Sensor.stop()')}}
+
Deactivates one of the sensors based on Sensor.
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Generic Sensor','#the-sensor-interface','Sensor')}}{{Spec2('Generic Sensor')}}Initial definition.
+ +

Browser compatibility

+ + + +

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

diff --git a/files/pt-br/web/api/server-sent_events/index.html b/files/pt-br/web/api/server-sent_events/index.html new file mode 100644 index 0000000000..4a7f8eb1b7 --- /dev/null +++ b/files/pt-br/web/api/server-sent_events/index.html @@ -0,0 +1,79 @@ +--- +title: Server-sent events +slug: Web/API/Server-sent_events +tags: + - API + - NeedsTranslation + - Overview + - SSE + - Server-sent events + - TopicStub +translation_of: Web/API/Server-sent_events +--- +

{{DefaultAPISidebar("Server Sent Events")}}

+ +

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.

+ +

Concepts and usage

+ +

To learn how to use server-sent events, see our article Using server-sent events.

+ +

Interfaces

+ +
+
{{domxref("EventSource")}}
+
Defines all the features that handle connecting to a server, receiving events/data, errors, closing a connection, etc.
+
+ +

Examples

+ + + +

Specification

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#server-sent-events', 'Server-sent events')}}{{Spec2('HTML WHATWG')}} 
+ +

See also

+ +

Tools

+ + + + + + + +

Other resources

+ + diff --git a/files/pt-br/web/api/server-sent_events/using_server-sent_events/index.html b/files/pt-br/web/api/server-sent_events/using_server-sent_events/index.html new file mode 100644 index 0000000000..1a7b084ab6 --- /dev/null +++ b/files/pt-br/web/api/server-sent_events/using_server-sent_events/index.html @@ -0,0 +1,189 @@ +--- +title: Using server-sent events +slug: Web/API/Server-sent_events/Using_server-sent_events +translation_of: Web/API/Server-sent_events/Using_server-sent_events +--- +

{{DefaultAPISidebar("Server Sent Events")}}

+ +
+

É fácil desenvolver um aplicativo Web que usa server-sent events. Você precisára de um pouco de código no servidor para transmitir eventos para o front-end, mas o código do lado do cliente funciona quase de forma idêntica aos websockets em questão de tratamento de eventos recebidos. Essa é uma conexão unidirecional, portanto você não pode enviar eventos de um cliente para um servidor.

+
+ +

Receiving events from the server

+ +

The server-sent event API is contained in the {{domxref("EventSource")}} interface; to open a connection to the server to begin receiving events from it, create a new EventSource object with the URL of a script that generates the events. For example:

+ +
const evtSource = new EventSource("ssedemo.php");
+ +

If the event generator script is hosted on a different origin, a new EventSource object should be created with both the URL and an options dictionary. For example, assuming the client script is on example.com:

+ +
const evtSource = new EventSource("//api.example.com/ssedemo.php", { withCredentials: true } );
+ +

Once you've instantiated your event source, you can begin listening for messages from the server by attaching a handler for the {{event("message")}} event:

+ +
evtSource.onmessage = function(event) {
+  const newElement = document.createElement("li");
+  const eventList = document.getElementById("list");
+
+  newElement.innerHTML = "message: " + event.data;
+  eventList.appendChild(newElement);
+}
+
+ +

This code listens for incoming messages (that is, notices from the server that do not have an event field on them) and appends the message text to a list in the document's HTML.

+ +

You can also listen for events with addEventListener():

+ +
evtSource.addEventListener("ping", function(event) {
+  const newElement = document.createElement("li");
+  const time = JSON.parse(event.data).time;
+  newElement.innerHTML = "ping at " + time;
+  eventList.appendChild(newElement);
+});
+
+ +

This code is similar, except that it will be called automatically whenever the server sends a message with the event field set to "ping"; it then parses the JSON in the data field and outputs that information.

+ +
+

When not used over HTTP/2, SSE suffers from a limitation to the maximum number of open connections, which can be specially painful when opening various tabs as the limit is per browser and set to a very low number (6). The issue has been marked as "Won't fix" in Chrome and Firefox. This limit is per browser + domain, so that means that you can open 6 SSE connections across all of the tabs to www.example1.com and another 6 SSE connections to www.example2.com. (from Stackoverflow). When using HTTP/2, the maximum number of simultaneous HTTP streams is negotiated between the server and the client (defaults to 100).

+
+ +

Sending events from the server

+ +

The server-side script that sends events needs to respond using the MIME type text/event-stream. Each notification is sent as a block of text terminated by a pair of newlines. For details on the format of the event stream, see {{ anch("Event stream format") }}.

+ +

The {{Glossary("PHP")}} code for the example we're using here follows:

+ +
date_default_timezone_set("America/New_York");
+header("Cache-Control: no-cache");
+header("Content-Type: text/event-stream");
+
+$counter = rand(1, 10);
+while (true) {
+  // Every second, send a "ping" event.
+
+  echo "event: ping\n";
+  $curDate = date(DATE_ISO8601);
+  echo 'data: {"time": "' . $curDate . '"}';
+  echo "\n\n";
+
+  // Send a simple message at random intervals.
+
+  $counter--;
+
+  if (!$counter) {
+    echo 'data: This is a message at time ' . $curDate . "\n\n";
+    $counter = rand(1, 10);
+  }
+
+  ob_end_flush();
+  flush();
+  sleep(1);
+}
+
+ +

The code above generates an event every second, with the event type "ping". Each event's data is a JSON object containing the ISO 8601 timestamp corresponding to the time at which the event was generated. At random intervals, a simple message (with no event type) is sent.

+ +
+

Note: You can find a full example that uses the code shown in this article on GitHub — see Simple SSE demo using PHP.

+
+ +

Error handling

+ +

When problems occur (such as a network timeout or issues pertaining to access control), an error event is generated. You can take action on this programmatically by implementing the onerror callback on the EventSource object:

+ +
evtSource.onerror = function(err) {
+  console.error("EventSource failed:", err);
+};
+
+ +

Closing event streams

+ +

By default, if the connection between the client and server closes, the connection is restarted. The connection is terminated with the .close() method.

+ +
evtSource.close();
+ +

Event stream format

+ +

The event stream is a simple stream of text data which must be encoded using UTF-8. Messages in the event stream are separated by a pair of newline characters. A colon as the first character of a line is in essence a comment, and is ignored.

+ +
Note: The comment line can be used to prevent connections from timing out; a server can send a comment periodically to keep the connection alive.
+ +

Each message consists of one or more lines of text listing the fields for that message. Each field is represented by the field name, followed by a colon, followed by the text data for that field's value.

+ +

Fields

+ +

Each message received has some combination of the following fields, one per line:

+ +
+
event
+
A string identifying the type of event described. If this is specified, an event will be dispatched on the browser to the listener for the specified event name; the website source code should use addEventListener() to listen for named events. The onmessage handler is called if no event name is specified for a message.
+
data
+
The data field for the message. When the EventSource receives multiple consecutive lines that begin with data:, it will concatenate them, inserting a newline character between each one. Trailing newlines are removed.
+
id
+
The event ID to set the EventSource object's last event ID value.
+
retry
+
The reconnection time to use when attempting to send the event. This must be an integer, specifying the reconnection time in milliseconds. If a non-integer value is specified, the field is ignored.
+
+ +

All other field names are ignored.

+ +
Note: If a line doesn't contain a colon, the entire line is treated as the field name with an empty value string.
+ +

Examples

+ +

Data-only messages

+ +

In the following example, there are three messages sent. The first is just a comment, since it starts with a colon character. As mentioned previously, this can be useful as a keep-alive if messages may not be sent regularly.

+ +

The second message contains a data field with the value "some text". The third message contains a data field with the value "another message\nwith two lines". Note the newline special character in the value.

+ +
: this is a test stream
+
+data: some text
+
+data: another message
+data: with two lines
+
+ +

Named events

+ +

This example sends some named events. Each has an event name specified by the event field, and a data field whose value is an appropriate JSON string with the data needed for the client to act on the event. The data field could, of course, have any string data; it doesn't have to be JSON.

+ +
event: userconnect
+data: {"username": "bobby", "time": "02:33:48"}
+
+event: usermessage
+data: {"username": "bobby", "time": "02:34:11", "text": "Hi everyone."}
+
+event: userdisconnect
+data: {"username": "bobby", "time": "02:34:23"}
+
+event: usermessage
+data: {"username": "sean", "time": "02:34:36", "text": "Bye, bobby."}
+
+ +

Mixing and matching

+ +

You don't have to use just unnamed messages or typed events; you can mix them together in a single event stream.

+ +
event: userconnect
+data: {"username": "bobby", "time": "02:33:48"}
+
+data: Here's a system message of some kind that will get used
+data: to accomplish some task.
+
+event: usermessage
+data: {"username": "bobby", "time": "02:34:11", "text": "Hi everyone."}
+ +

Browser compatibility

+ +
+

EventSource

+ +
+ + +

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

+
+
diff --git a/files/pt-br/web/api/service_worker_api/index.html b/files/pt-br/web/api/service_worker_api/index.html new file mode 100644 index 0000000000..05ae2f90c8 --- /dev/null +++ b/files/pt-br/web/api/service_worker_api/index.html @@ -0,0 +1,322 @@ +--- +title: API do Service Worker +slug: Web/API/Service_Worker_API +translation_of: Web/API/Service_Worker_API +--- +

{{ServiceWorkerSidebar}}

+ +

Essencialmente, um service worker se comporta como um servidor proxy situado entre uma aplicação web, o navegador e a rede (quando esta estiver disponível). Eles servem, dentre outras coisas, para possibilitar a criação de experiências offline eficientes, interceptar requisições de rede – agindo adequadamente de acordo com o status atual da conexão – e atualizar os assets que residem no servidor. Service workers também permitem o acesso às APIs de push notification e background sync.

+ +

Service worker - Conceitos e uso

+ +

Um service worker é um tipo especial de worker baseado em eventos, o qual é registrado para um determinado path e origem. Na prática, ele é um arquivo JavaScript que pode controlar as páginas do site ao qual ele está associado, interceptando e modificando requisições e a navegação em si. Ele também faz cache dos recursos trafegados de maneira bastante granular, visando oferecer controle total sobre como a sua aplicação se comporta em determinadas situações (o exemplo mais óbvio, naturalmente, é quando não há conexão de rede disponível).

+ +

Assim como outros tipos de worker, um service worker é executado em um contexto isolado. Dessa forma, não tem acesso ao DOM e roda em uma thread completamente separada, sendo incapaz de realizar operações blocantes. Service workers foram projetados para ser totalmente assíncronos; como consequência disso, não permitem o acesso a APIs como XHR síncrono e localStorage.  

+ +

Por questões de segurança, service workers funcionam apenas em sites servidos via HTTPS. A possibilidade de modificar requisições em um domínio desprotegido contra ataques do tipo man-in-the-middle seria desastrosa. No Firefox, é vetado o acesso à API de service workers para sites abertos no Modo de navegação privativa.

+ +
+

Nota: Os service workers superaram tentativas anteriores de resolver problemas semelhantes, como o AppCache. Há uma explicação simples para eles terem sido bem-sucedidos: Service workers não tentam adivinhar o que você está tentando fazer e, muito menos, deixam de funcionar caso não tenham adivinhado corretamente. Pelo contrário, você tem o controle milimétrico de tudo.    

+
+ +
+

Nota: Service workers fazem uso intenso de promessas, uma vez que eles têm de esperar por respostas assíncronas para, após retornadas, poderem executar a ação apropriada (de sucesso ou erro). A arquitetura de promessas é ideal para esse tipo de cenário.

+
+ +

 

+ +

Registrando

+ +

O registro inicial de um service worker é feito através do método {{domxref("ServiceWorkerContainer.register()")}}. Se bem-sucedido, seu service worker será descarregado no cliente e então ocorrerá a tentativa de instalação/ativação para as URLs acessadas pelo usuário sob a origem registrada ou, caso deseje, apenas dentro de um subconjunto limitado por você.

+ +

Download, instalação e ativação

+ +

Nesse estágio, seu service worker seguirá o seguinte ciclo de vida:

+ +
    +
  1. Download
  2. +
  3. Instalação
  4. +
  5. Ativação
  6. +
+ +

Quando o usuário acessa pela primeira vez um site ou página controlado por um service worker, ele é descarregado imediatamente.

+ +

Após isso, serão feitos novos downloads em intervalos de aproximadamente 24 horas. O download pode ocorrer mais frequentemente, mas ele precisa ser feito a cada 24 horas para prevenir que scripts ruins sejam um problema por períodos muito extensos. 

+ +

A tentativa de instalação é feita sempre que o arquivo descarregado é identificado como novo – seja por diferir dos service workers pré-existentes (é feita uma comparação binária nessa etapa) ou por ser o primeiro descoberto para a página ou site em questão.

+ +

Na primeira vez que um service worker é disponibilizado, é feita a tentativa de instalação. Se bem-sucedida, ele é ativado.

+ +

Se, por outro lado, já existe um service worker pré-instalado para uma página ou site e for disponibilizada uma nova versão, ela será descarregada, mas não imediatamente ativada. Isso é chamado de worker em espera. Só será efetuada a ativação da versão atualizada quando não houver mais páginas utilizando a anterior. Após isso, ele passa a ser o worker ativo. Caso necessário, é possível pular a etapa de espera com o método {{domxref("ServiceWorkerGlobalScope.skipWaiting()")}}. Em seguida, o novo worker ativo pode reivindicar as páginas existentes usando {{domxref("Clients.claim()")}}. 

+ +

Você pode adicionar um listener para o evento {{domxref("InstallEvent")}}. Uma ação padrão, quando esse evento é disparado, é preparar o seu service worker para ser utilizado (por exemplo: criado um cache usando a API de storage nativa e armazenando nela os assets que você quer que permaneçam disponíveis caso a aplicação fique offline).

+ +

Há também o evento activate. O momento em que ele é disparado é geralmente o ideal para limpar caches antigos e outras coisas associadas com a versão anterior do seu service worker.

+ +

Seu service worker pode responder a requisições usando o {{domxref("FetchEvent")}}. Você pode manipular a resposta a essas requisições da maneira que quiser, através do método {{domxref("FetchEvent.respondWith")}}.

+ +
+

Nota: Como oninstall e onactivate podem demorar a serem concluídos, a especificação de service workers disponibiliza um método waitUntil. Ele recebe como parâmetro uma promessa, notificando o navegador que há trabalho em andamento até que aquela promessa seja resolvida. O navegador, portanto, não deverá encerrar o service worker durante esse período de espera. 

+
+ +

Para um tutorial completo, mostrando como construir seu primeiro exemplo do zero, leia Usando Service Workers.

+ +

Outras ideias de usos possíveis

+ + + +

No futuro, service workers serão capazes de fazer várias outras coisas úteis para a plataforma web, deixando-a mais próxima de apps nativos em.

+ +

É interessante mencionar que outras especificações podem e irão passar a usar o contexto de service workers, por exemplo:

+ + + +

Interfaces

+ +
+
{{domxref("Cache")}}
+
Representa o armazenamento para os pares de objeto {{domxref("Request")}} e {{domxref("Response")}}, os quais são cacheados como parte do ciclo de vida do {{domxref("ServiceWorker")}}.
+
{{domxref("CacheStorage")}}
+
Representa o armazenamento para objetos {{domxref("Cache")}}. Ele disponibiliza um diretório-mestre com todos os caches nomeados que um {{domxref("ServiceWorker")}} pode acessar, mantendo o mapeamento de nomes para os objetos {{domxref("Cache")}} correspondentes.
+
{{domxref("Client")}}
+
Representa o escopo do cliente de um service worker. Um cliente pode ser um documento no contexto de um navegador ou um {{domxref("SharedWorker")}}, o qual é controlado por um worker ativo.
+
{{domxref("Clients")}}
+
Representa o container para uma lista de objetos {{domxref("Client")}}. É a principal forma de acessar os clientes na origem atual para o service worker ativo.
+
{{domxref("ExtendableEvent")}}
+
Estende a vida dos eventos install e activate disparados no {{domxref("ServiceWorkerGlobalScope")}}, como parte do ciclo de vida do service worker. Isso garante que qualquer evento funcional (como o {{domxref("FetchEvent")}}) não seja despachado para o {{domxref("ServiceWorker")}} até que ele conclua as ações em andamento, como por exemplo: atualizar esquemas de banco de dados, apagar caches defasados, etc.
+
{{domxref("ExtendableMessageEvent")}}
+
O objeto de evento do {{event("message_(ServiceWorker)","message")}}, o qual é disparado em um service worker (quando uma mensagem de canal é recebida no {{domxref("ServiceWorkerGlobalScope")}} a partir de outro contexto) — estende o tempo de vida desses eventos.
+
{{domxref("FetchEvent")}}
+
O parâmetro recebido no handler  {{domxref("ServiceWorkerGlobalScope.onfetch")}}. O FetchEvent representa uma ação de descarregamento que é despachada no {{domxref("ServiceWorkerGlobalScope")}} de um  {{domxref("ServiceWorker")}}. Ele contém informações sobre a requisição e a resposta resultante, além de disponibilizar o método {{domxref("FetchEvent.respondWith", "FetchEvent.respondWith()")}}, o qual nos permite devolver uma resposta customizada para a página que está sendo controlada.
+
{{domxref("InstallEvent")}}
+
O parâmetro recebido no handler  {{domxref("ServiceWorkerGlobalScope.oninstall", "oninstall")}}. A interface InstallEvent representa uma ação de instalação que é despachada no {{domxref("ServiceWorkerGlobalScope")}} de um  {{domxref("ServiceWorker")}}. Como deriva do {{domxref("ExtendableEvent")}}, ele assegura que eventos funcionais, como o {{domxref("FetchEvent")}}, não sejam despachados durante a instalação. 
+
{{domxref("NavigationPreloadManager")}}
+
Disponibiliza métodos para gerenciar o pré-carregamento de recursos com um service worker. 
+
{{domxref("Navigator.serviceWorker")}}
+
Retornar um objeto {{domxref("ServiceWorkerContainer")}}, o qual permite accesso ao registro, remoção, atualização e comunicação com os objetos {{domxref("ServiceWorker")}} para o documento associado.
+
{{domxref("NotificationEvent")}}
+
O parâmetro recebido no handler  {{domxref("ServiceWorkerGlobalScope.onnotificationclick", "onnotificationclick")}}. A interface NotificationEvent representa um evento de click em uma notificação que é despachado no {{domxref("ServiceWorkerGlobalScope")}} de um {{domxref("ServiceWorker")}}.
+
{{domxref("ServiceWorker")}}
+
Representa um service worker. Diferentes contextos de navegação (ex: páginas, workers, etc.) podem ser associados com o mesmo objeto ServiceWorker.
+
{{domxref("ServiceWorkerContainer")}}
+
Disponibiliza um objeto representando o service worker como uma unidade global no ecossistema de rede, incluindo métodos para registrar, desregistrar e atualizar service workers, além de poder acessar o status de cada worker e seus registros.
+
{{domxref("ServiceWorkerGlobalScope")}}
+
Representa o contexto de execução global de um service worker.
+
{{domxref("ServiceWorkerMessageEvent")}} {{deprecated_inline}}
+
Representa uma mensagem enviada a um {{domxref("ServiceWorkerGlobalScope")}}. Vale ressaltar que essa interface está defasada em navegadores modernos. As mensagens de service worker agora usam a interface {{domxref("MessageEvent")}} para manter consistência com outras funcionalidades de messageria da web.
+
{{domxref("ServiceWorkerRegistration")}}
+
Representa o registro de um service worker.
+
{{domxref("ServiceWorkerState")}} {{experimental_inline}}
+
Associado com o estado do ServiceWorker.
+
{{domxref("SyncEvent")}} {{non-standard_inline}}
+
+

A interface SyncEvent representa uma ação de sincronização que é despachada no {{domxref("ServiceWorkerGlobalScope")}} de um ServiceWorker. 

+
+
{{domxref("SyncManager")}} {{non-standard_inline}}
+
Disponibiliza uma interface para registrar e listar registros de sincronização.
+
{{domxref("WindowClient")}}
+
Representa o escopo de um cliente de service worker que é um documento em um contexto de navegador, o qual é controlado por um worker ativo. Esse é um tipo especial de objeto {{domxref("Client")}}, como alguns métodos e propriedades adicionais disponíveis.
+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('Service Workers')}}{{Spec2('Service Workers')}}Initial definition.
+ +

Compatibilidade de Navegador

+ +

{{ CompatibilityTable() }}

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
RecursoChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico{{CompatChrome(40)}}{{CompatNo}}[1]{{ CompatGeckoDesktop("44.0") }}[2]{{ CompatNo() }}24{{ CompatNo() }}[3]
Eventos install/activate{{ CompatChrome(40) }}{{CompatNo}}[1]{{ CompatGeckoDesktop("44.0") }}[2]{{ CompatNo() }}{{ CompatVersionUnknown() }}{{ CompatNo() }}
Evento fetch/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")}} defasado em favor {{domxref("MessageEvent")}} +

{{CompatChrome(57)}}

+
{{ CompatNo() }}{{ CompatGeckoDesktop("55.0") }}[2]{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
NavigationPreloadManager{{CompatChrome(59)}}{{ CompatNo() }} {{ CompatNo() }}{{CompatOpera(46)}}{{ CompatNo() }}
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
RecursosAndroid WebviewChrome for AndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Suporte básico{{ CompatNo() }}{{CompatChrome(40)}}{{CompatNo}}[1]{{ CompatGeckoMobile("44.0") }}{{ CompatNo() }}{{ CompatVersionUnknown() }}{{ CompatNo() }}[3]
Eventos install/activate{{ CompatNo() }}{{CompatChrome(40)}}{{CompatNo}}[1]{{ CompatGeckoMobile("44.0") }}{{ CompatNo() }}{{ CompatVersionUnknown() }}{{ CompatNo() }}
Evento fetch/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")}} defasado em favor de {{domxref("MessageEvent")}}{{ CompatNo() }} +

{{CompatChrome(57)}}

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

[1] Esse recurso ainda não é suportado, apesar de já estar em desenvolvimento.

+ +

[2] Service workers (e Push) foram desabilitados no Firefox, nas versões 45 & 52 Extended Support Releases (ESR.)

+ +

[3] Esse recurso ainda não é suportado, apesar de já estar em desenvolvimento.

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/service_worker_api/using_service_workers/index.html b/files/pt-br/web/api/service_worker_api/using_service_workers/index.html new file mode 100644 index 0000000000..983b352d82 --- /dev/null +++ b/files/pt-br/web/api/service_worker_api/using_service_workers/index.html @@ -0,0 +1,522 @@ +--- +title: Usando Service Workers +slug: Web/API/Service_Worker_API/Using_Service_Workers +translation_of: Web/API/Service_Worker_API/Using_Service_Workers +--- +

{{ServiceWorkerSidebar}}

+ +

{{ SeeCompatTable() }}

+ +
+

Esse artigo contém informações de como começar com service workers, incluindo a arquitetura básica, registro de um service worker, o processo de instalação e ativação de um novo service worker, atualização de seu service worker, controle de cache e respostas customizadas, tudo isso no contexto de um simples app com a funcionalidade offline.

+
+ +

A premissa dos Service Workers

+ +

O principal problema que os usuários da web sofreram durante anos foi a perda de conexão. Até mesmo melhor web app do mundo terá uma péssima experiência de usuário se você não conseguir baixa-lá. Houveram várias tentativas de criar tecnologias para resolver esse problema, como mostra nossa página Offline, e algumas questões foram resolvidas. Mas o maior problema é que, no geral, ainda não há um bom mecanismo de controle para caching de assets e requisições de rede personalizadas.
+
+ A tentativa anterior — AppCache — parecia uma boa ideia, pois permitia especificar facilmente os assets para cache. Porém, fazia várias suposições sobre o que você estava tentando fazer e depois quebrava horrivelmente quando seu app não seguia exatamente tais suposições. Leia Application Cache is a Douchebag de Jake Archibald para mais detalhes.

+ +
+

Nota: A partir do Firefox 44, quando AppCache é usado para fornecer suporte offline  uma página, um aviso é exibido no console para que os desenvolvedores usem Service workers ({{bug("1204581")}}.)

+
+ +

Service workers devem finalmente corrigir esses problemas. A sintaxe do service worker é mais complexa do que a do AppCache, mas a vantagem é que você pode usar Javascript para controlar os comportamentos implícitos do AppCache com um bom grau de granularidade, permitindo que você lide com esse problema e muitos outros. Usando Service Worker você pode facilmente configurar um app para usar primeiro assets em cache, provendo uma experiência padronizada mesmo que esteja offline, antes de obter mais dados da rede (mais conhecido como Offline First). Isso já está disponível em apps nativos, que é uma das principais razões pelas quais apps nativos são frequentemente mais escolhidos do que web apps.

+ +

Configuração para usar service workers

+ +

Várias características de service workers estão habilitadas por padrão em versões mais recentes dos navegadores suportados. Se, no entanto, encontrar um código de demonstração que não está funcionando na suas versões instaladas, você precisará habilitar essa preferência:

+ + + +

Você também precisa fornecer seu código via HTTPS — Service workers estão restritos a rodar apenas via HTTPS por motivos de segurança. GitHub serve como um bom host para os experimentos, pois suporta HTTPS. Para facilitar o desenvolvimento local, localhost também é considerado uma origem segura pelos navegadores. 

+ +

Arquitetura Básica

+ +

Com service workers, os seguintes passos geralmente são observados como configuração básica:

+ +
    +
  1. A URL do service worker é buscada e registrada via {{domxref("serviceWorkerContainer.register()")}}.
  2. +
  3. Em caso de sucesso, o service worker é executado em um {{domxref("ServiceWorkerGlobalScope") }}; isto é basicamente um tipo especial de contexto do worker, que é executado fora da thread de execução do script principal, sem acesso ao DOM.
  4. +
  5. O service worker agora está pronto para processar eventos.
  6. +
  7. A tentativa de instalação do worker acontece quando as páginas controladas pelo service worker são acessadas. O evento de instalação é sempre o primeiro a ser enviado ao service worker (isto pode ser usado para iniciar o processode preencher um IndexedDB, e armazenar em cache os assets do site). Este é realmente o mesmo tipo de procedimento para instalação de um aplicativo nativo ou do Firefox OS — disponibilizando tudo offline.
  8. +
  9. Quando o manipulador oninstall estiver completo, considera-se que o service worker está instalado.
  10. +
  11. O próximo é a ativação. Quando um service worker é instalado, ele recebe um evento de ativação. O uso primário do onactivate é para limpeza de recursos usado em versões anterioires do script de um Service worker.
  12. +
  13. O Service worker agora vai controlar páginas, mas apenas aquelas abertas após o register() tiver sido bem-sucedido. Isto é, um documento inicia a vida com ou sem Service worker e mantém isso durante seu tempo de vida. Logo, documentos terão de ser recarregados para serem controlados.
  14. +
+ +

+ +

O gráfico abaixo mostra um resumo dos eventos de service worker disponíveis:

+ +

install, activate, message, fetch, sync, push

+ +

Promises

+ +

Promises são um ótimo mecanismo para executar operações assíncronas, onde o sucesso de uma depende do sucesso das outras. Isto é o fundamento para o modo como os service workers trabalham.
+
+ Promises pode fazer uma variedade de coisas, mas tudo o que precisa saber agora é que, se algo retorna uma promise, você pode inserir .then() ao final e incluir dentro dela callback para casos de sucesso ou poder inserir .catch() ao final, se quiser incluir um callback para falha.

+ +

Vamos comparar a estrutura de um callback tradicional síncrono para uma promise assíncrona equivalente.

+ +

sync

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

async

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

No primeiro exemplo, temos que esperar myFunction() executar e retornar value antes que qualquer código adicional possa ser executado. No segundo exemplo, myFunction() retorna uma promessa para value, então o resto do código pode ser executado logo em seguida. Quando a promessa é atendida, o código dentro do método then será executado, assincronamente.
+
+ Agora para um exemplo real — e se quiséssemos carregar imagens dinamicamente, mas quiséssemos ter certeza que as imagens estão carregadas antes de tentar mostrá-las? É uma coisa padrão que estamos querendo fazer, mas pode ser um pouco complicado. Podemos usar .onload para somente mostrar a imagem após ela ter carregado, mas e para os eventos que aconteceram antes de começarmos a ouvi-los? Podemos tentar contornar isso usando .complete, mas ainda não é a prova de falhas, e para várias imagens? E, ummm, ainda é síncrono, portanto bloqueia a thread principal.
+
+ Ao invés disso, podemos contruir nossa própria promessa para lidar com casos deste tipo. (Veja o exemplo Promises test para o código fonte, ou veja rodando live.)

+ +

{{note("Uma implementação real de service worker usaria caching e onfetch ao invés da depreciada XMLHttpRequest API. Estes features não são usados aqui para que você foque em entender Promises.")}}

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

Retornamos uma nova promise usando o Promise() constructor, o qual tem uma função callback como argumento com os parâmetros resolve ereject. Em algum lugar na função, precisamos definir o que acontece para que a promessa ser resolvida com sucesso ou ser rejeitada — neste caso, retornar um status 200 OK ou não — e então chamar resolve em caso de sucesso, ou reject em caso de falha. O resto do conteúdo desta função é XHR padrão, então, não vamos nos preocupar com isso agora.

+ +

Quando chamamos a função imgLoad(), chamamos com a url para a imagem que queremos carregar, como seria de se esperar, mas o resto do código é um pouco diferente:

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

No fim da chamada da função, encadeamos o método then() da promisse, o qual contém duas funções — a primeira é executada quando a promisse é resolvida com sucesso, e a segunda é chamada quando a promise é rejeitada. Caso seja resolvida, exibimos a imagem dentro de myImage e a acrescentamos ao corpo (cujo argument é o request.response contido dentro do método resolve da promise); no caso de rejeição, nos retornamos um erro ao console.

+ +

Tudo isto acontece assincronamente.

+ +
+

Nota: Você também pode encadear chamadas de promises, por exemplo:
+ myPromise().then(success, failure).then(success).catch(failure);

+
+ +
+

Nota: Você pode encontrar muito mais informações sobre promises lendo o excelente JavaScript Promises: there and back again de Jake Archibald.

+
+ +

Demonstração de Service workers

+ +

Para demonstrar apenas o básico de registro e instalação de um service worker, criamos uma simples demonstração chamada sw-test, que é uma simples galeria de imagens de Star Wars Lego. Usa uma função ativada por promise para ler dados de imagem a partir de um objeto JSON e carrega as imagens usando Ajax, antes de exibir as imagens em uma linha ao longo da página. Mantivemos as coisas estáticas e simples por enquanto. Também registra, instala e ativa um service worker, e quando mais especificações são suportadas pelos navegadores, armazena em cache todos os arquivos necessários para que funcione offline!

+ +


+
+
+ Você pode ver o código-fonte no GitHub, e ver um exemplo vivo. A parte que mencionaremos aqui é a promise (veja app.js linhas 22-47), que é uma versão modificada do que você leu a respeito acima, em Promises test demo. É diferente das seguintes formas:

+ +
    +
  1. No original, passamos somente uma URL para uma image que queríamos carregar. Nesta versão, passamos um fragmento de um JSON contendo todos os dados de uma única imagem (veja como se parecem em image-list.js). Isto porque todos os dados para cada resolução de promise precisam ser transmitidos com a promise, pois é assíncrona. Se você passou apenas a url, e depois tentou acessar os outros itens no JSON separadamente, quando o laço de repetição for() estivesse sendo iterado posteriormente, não funcionaria, pois a promise não se resolveria ao mesmo tempo que as iterações estão sendo feitas (isso é um processo síncrono).
  2. +
  3. Na verdade, resolvemos a promise como uma matriz, pois queremos tornar o blob da imagem carregada disponível para a função de resolução mais adiante no código, além do nome da imagem, créditos e texto alternativo (veja app.js linhas 31-34). Promises resolverão somente com um único argumento, então, se você quiser resolver múltiplos valores, precisará usar uma matriz/objeto..
  4. +
  5. Para acessar os valores da promise resolvida, acessamos esta função como esperado (veja app.js linhas 60-64). Pode parecer um pouco estranho no começo, mas é assim que as promises funcionam.
  6. +
+ +

Inserir service workers

+ +

Agora vamos aos service workers!

+ +

Registrando seu worker

+ +

O primeiro bloco de código do nosso arquivo do app JavaScript — app.js — é conforme segue. Este é nosso entry point para usar service workers.

+ +
if ('serviceWorker' in navigator) {
+  navigator.serviceWorker.register('/sw-test/sw.js', {scope: '/sw-test/'})
+  .then(function(reg) {
+    // registration worked
+    console.log('Registration succeeded. Scope is ' + reg.scope);
+  }).catch(function(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 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 support")}} 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:

+ +
this.addEventListener('install', function(event) {
+  event.waitUntil(
+    caches.open('v1').then(function(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 this), 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.

+ +
this.addEventListener('fetch', function(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:

+ +
this.addEventListener('fetch', function(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 reject and we would just come up against a network error when a match isn’t found.

+ +

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

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

If the resources isn't in the cache, it is 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:

+ +
this.addEventListener('fetch', function(event) {
+  event.respondWith(
+    caches.match(event.request).then(function(resp) {
+      return resp || fetch(event.request).then(function(response) {
+        return caches.open('v1').then(function(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:

+ +
this.addEventListener('fetch', function(event) {
+  event.respondWith(
+    caches.match(event.request).then(function(resp) {
+      return resp || fetch(event.request).then(function(response) {
+        caches.open('v1').then(function(cache) {
+          cache.put(event.request, response.clone());
+        });
+        return response;
+      });
+    }).catch(function() {
+      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):

+ +
this.addEventListener('install', function(event) {
+  event.waitUntil(
+    caches.open('v2').then(function(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.

+ +
this.addEventListener('activate', function(event) {
+  var cacheWhitelist = ['v2'];
+
+  event.waitUntil(
+    caches.keys().then(function(keyList) {
+      return Promise.all(keyList.map(function(key) {
+        if (cacheWhitelist.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

+
+ +

Specifications

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

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(40.0)}}{{ CompatGeckoDesktop("33.0") }}[1]{{CompatNo}}24{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatChrome(40.0)}}{{ CompatVersionUnknown }}{{ CompatVersionUnknown }}{{CompatNo}}{{ CompatVersionUnknown() }}{{CompatNo}}
+
+ +

[1] Service workers (and Push) have been disabled in the Firefox 45 Extended Support Release (ESR.)

+ +

See also

+ + diff --git a/files/pt-br/web/api/serviceworkercontainer/index.html b/files/pt-br/web/api/serviceworkercontainer/index.html new file mode 100644 index 0000000000..45a4406e9d --- /dev/null +++ b/files/pt-br/web/api/serviceworkercontainer/index.html @@ -0,0 +1,175 @@ +--- +title: ServiceWorkerContainer +slug: Web/API/ServiceWorkerContainer +tags: + - API + - Draft + - Interface + - NeedsTranslation + - Offline + - Reference + - Service Workers + - Service worker API + - ServiceWorkerContainer + - TopicStub + - Workers +translation_of: Web/API/ServiceWorkerContainer +--- +

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

+ +

ServiceWorkerContainer é a interface de ServiceWorker API 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.

+ +

Most importantly, it exposes the {{domxref("ServiceWorkerContainer.register", "ServiceWorkerContainer.register()")}} method used to register service workers, and the {{domxref("ServiceWorkerContainer.controller")}} property used to determine whether or not the current page is actively controlled.

+ +

Properties

+ +
+
{{domxref("ServiceWorkerContainer.controller")}} {{readonlyinline}}
+
Returns a {{domxref("ServiceWorker")}} object if its state is activated (the same object returned by {{domxref("ServiceWorkerRegistration.active")}}). This property returns null during a force-refresh request (Shift + refresh) or if there is no active worker.
+
+ +
+
{{domxref("ServiceWorkerContainer.ready")}} {{readonlyinline}}
+
Provides a way of delaying code execution until a service worker is active. It returns a {{jsxref("Promise")}} that will never reject, and which waits indefinitely until the {{domxref("ServiceWorkerRegistration")}} associated with the current page has an {{domxref("ServiceWorkerRegistration.active")}} worker. Once that condition is met, it resolves with the {{domxref("ServiceWorkerRegistration")}}.
+
+ +

Event handlers

+ +
+
{{domxref("ServiceWorkerContainer.oncontrollerchange")}}
+
Fired whenever a {{Event("controllerchange")}} event occurs — when the document's associated {{domxref("ServiceWorkerRegistration")}} acquires a new {{domxref("ServiceWorkerRegistration.active","active")}} worker.
+
{{domxref("ServiceWorkerContainer.onerror")}}
+
Fired whenever an {{Event("error")}} event occurs in the associated service workers.
+
{{domxref("ServiceWorkerContainer.onmessage")}}
+
Fired whenever a {{Event("message")}} event occurs — when incoming messages are received to the {{domxref("ServiceWorkerContainer")}} object (e.g. via a {{domxref("MessagePort.postMessage()")}} call.)
+
+ +

Methods

+ +
+
{{domxref("ServiceWorkerContainer.register", "ServiceWorkerContainer.register()")}} 
+
Creates or updates a {{domxref("ServiceWorkerRegistration")}} for the given scriptURL.
+
{{domxref("ServiceWorkerContainer.getRegistration()")}}
+
Gets a {{domxref("ServiceWorkerRegistration")}} object whose scope matches the provided document URL.  If the method can't return a {{domxref("ServiceWorkerRegistration")}}, it returns a Promise
+
{{domxref("ServiceWorkerContainer.getRegistrations()")}}
+
Returns all {{domxref("ServiceWorkerRegistration")}} objects associated with a ServiceWorkerContainer in an array.  If the method can't return {{domxref("ServiceWorkerRegistration")}} objects, it returns a Promise
+
+ +

Examples

+ +

The example below first checks to see if the browser supports service workers. If supported, the code registers the service worker and determines if the page is actively controlled by the service worker. If it isn't, it prompts the user to reload the page so the service worker can take control. The code also reports any registration failures.

+ +
if ('serviceWorker' in navigator) {
+  // Register a service worker hosted at the root of the
+  // site using the default scope.
+  navigator.serviceWorker.register('/sw.js').then(function(registration) {
+    console.log('Service worker registration succeeded:', registration);
+
+    // At this point, you can optionally do something
+    // with registration. See https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerRegistration
+  }).catch(function(error) {
+    console.log('Service worker registration failed:', error);
+  });
+
+  // Independent of the registration, let's also display
+  // information about whether the current page is controlled
+  // by an existing service worker, and when that
+  // controller changes.
+
+  // First, do a one-off check if there's currently a
+  // service worker in control.
+  if (navigator.serviceWorker.controller) {
+    console.log('This page is currently controlled by:', navigator.serviceWorker.controller);
+  }
+
+  // Then, register a handler to detect when a new or
+  // updated service worker takes control.
+  navigation.serviceWorker.oncontrollerchange = function() {
+    console.log('This page is now controlled by:', navigator.serviceWorker.controller);
+  };
+} else {
+  console.log('Service workers are not supported.');
+}
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Service Workers', '#service-worker-container', 'ServiceWorkerContainer')}}{{Spec2('Service Workers')}}Initial definition.
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(40)}}{{ CompatGeckoDesktop("44.0") }}[1]{{CompatNo}}{{CompatOpera(27)}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support{{CompatChrome(40)}}{{CompatChrome(40)}}{{ CompatGeckoMobile("44.0") }}{{ CompatVersionUnknown }}{{CompatNo}}{{CompatOperaMobile(27)}}{{CompatNo}}
+
+ +

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

+ +

See also

+ + diff --git a/files/pt-br/web/api/serviceworkercontainer/register/index.html b/files/pt-br/web/api/serviceworkercontainer/register/index.html new file mode 100644 index 0000000000..cb27ddc843 --- /dev/null +++ b/files/pt-br/web/api/serviceworkercontainer/register/index.html @@ -0,0 +1,140 @@ +--- +title: ServiceWorkerContainer.register() +slug: Web/API/ServiceWorkerContainer/register +translation_of: Web/API/ServiceWorkerContainer/register +--- +
{{SeeCompatTable}}{{APIRef("Service Workers API")}}
+ +

O método register()da interface {{domxref("ServiceWorkerContainer")}} cria ou atualiza um {{domxref("ServiceWorkerRegistration")}} passado em scriptURL.

+ +

Em caso de sucesso, um registro de service worker vincula o URL do script fornecido ao escopo, que é usado posteriormente para a navegação correspondente. Você pode chamar esse método incondicionalmente da página controlada. Ou seja, você não precisa primeiro verificar se há um registro ativo.

+ +

Há uma frequente confusão em relação ao significado e uso do escopo. Uma vez que um service worker não pode ter um escopo mais amplo do que sua própria localização, use apenas a opção `scope` quando precisar de um escopo mais limitado do que o padrão.

+ +

Síntaxe

+ +
ServiceWorkerContainer.register(scriptURL, options)
+  .then(function(ServiceWorkerRegistration) { ... });
+ +

Parâmetros

+ +
+
scriptURL
+
A URL do script service worker.
+
options {{optional_inline}}
+
Um objeto contendo as opções do registro. Atualmente as opções disponíveis são: +
    +
  • scope: Uma {{domxref("USVString")}} representando uma URL que define o registro do escopo de um service worker's ; ou seja, o alcance das URLs que o service worker pode controlar. É geralmente uma URL relativa. O valor padrão é o URL que você obtém se você resolvesse './' usando a localização da página web como  base.  Não é, como customa-se acreditar, relativo à localização do service worker. Veja as seções de Exemplos para mais informações sobre como isso funciona.
  • +
+
+
+ +

Valor retornado

+ +

Um {{domxref("Promise")}} que resolve com um objeto {{domxref("ServiceWorkerRegistration")}}.

+ +

Exemplos

+ +

Os exemplos descritos escrito aqui deve ser tomado em conjunto para obter um melhor entendimento de como escopos do service workers são aplicados a uma página. 

+ +

O exemplo a seguir usa o valor padrão descope (ao omití-lo). O service worker neste caso irá controlarexample.com/index.html bem como páginas abaixo, como example.com/product/description.html.

+ +
if ('serviceWorker' in navigator) {
+  // Registra um service worker hospeadado na raiz do
+  // site usando o escopo padrão
+  navigator.serviceWorker.register('/sw.js').then(function(registration) {
+    console.log('Service worker  registrado com sucesso:', registration);
+  }).catch(function(error) {
+    console.log('Falha ao Registrar o Service Worker:', error);
+  });
+} else {
+  console.log('Service workers não suportado!');
+}
+ +

O código a seguir,  se incluído em uma página na raiz de um site, seria aplicado  exatamente às mesmas páginas, como no exemplo acima. Lembre-se de que o escopo, quando incluído, usa a localização da página como base. Alternativamente, se esse código foi incluído em uma página example.com/product/description.html,  o escopo de'./' significa que o escopo que o service worker seria aplicado somente  aos recursos deexample.com/product.  Se precisassemos de registrar um service worker em example.com/product/description.html aplicado a todoo example.com, deixaríamos o escopo acima.

+ +
if ('serviceWorker' in navigator) {
+  // Registre um service worker hospeado na raiz do
+  // site usando um escopo mais restritivo.
+  navigator.serviceWorker.register('/sw.js', {scope: './'}).then(function(registration) {
+    console.log('Service worker registrado com sucesso:', registration);
+  }).catch(function(error) {
+    console.log('Service worker falhou ao registrar:', error);
+  });
+} else {
+  console.log('Service workers não é suportado pelo navegador!.');
+}
+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('Service Workers', '#service-worker-container', 'ServiceWorkerContainer')}}{{Spec2('Service Workers')}}Initial definition.
+ +

Compatibilidade com Navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(40)}}{{ CompatGeckoDesktop("44.0") }}[1]{{CompatNo}}{{CompatOpera(27)}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support{{CompatChrome(40)}}{{CompatChrome(40)}}{{ CompatGeckoMobile("44.0") }}{{ CompatVersionUnknown }}{{CompatNo}}{{CompatOperaMobile(27)}}{{CompatNo}}
+
+ +

[1] Os Service workers (e Push) foram desativados no Firefox 45 e 52 Extended Support Releases (ESR.)

diff --git a/files/pt-br/web/api/serviceworkerglobalscope/clients/index.html b/files/pt-br/web/api/serviceworkerglobalscope/clients/index.html new file mode 100644 index 0000000000..6792b3b96c --- /dev/null +++ b/files/pt-br/web/api/serviceworkerglobalscope/clients/index.html @@ -0,0 +1,63 @@ +--- +title: ServiceWorkerGlobalScope.clients +slug: Web/API/ServiceWorkerGlobalScope/clients +tags: + - API + - Clients + - Service Worker + - Service Workers + - ServiceWorker + - ServiceWorkerGlobalScope + - ServiceWorkers +translation_of: Web/API/ServiceWorkerGlobalScope/clients +--- +

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

+ +

A propriedade somente-leitura clients da interface {{domxref("ServiceWorkerGlobalScope")}} retorna os objetos dos Clients associatos ao service worker.

+ +

Sintaxe

+ +
swClients = self.clients
+
+ +

Valor

+ +

O objeto {{domxref("Clients")}} associado ao service worker específico.

+ +

Especificações

+ +
 
+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Service Workers', '#service-worker-global-scope-clients', 'ServiceWorkerRegistration.clients')}}{{Spec2('Service Workers')}}Initial definition.
+  
+ +

Compatibilidade

+ +
+ + +

{{Compat("api.ServiceWorkerGlobalScope.clients")}}

+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/serviceworkerglobalscope/index.html b/files/pt-br/web/api/serviceworkerglobalscope/index.html new file mode 100644 index 0000000000..3f4115cbab --- /dev/null +++ b/files/pt-br/web/api/serviceworkerglobalscope/index.html @@ -0,0 +1,152 @@ +--- +title: ServiceWorkerGlobalScope +slug: Web/API/ServiceWorkerGlobalScope +tags: + - API + - Draft + - Interface + - NeedsTranslation + - Offline + - Reference + - Service Workers + - ServiceWorkerGlobalScope + - TopicStub + - Workers +translation_of: Web/API/ServiceWorkerGlobalScope +--- +
{{SeeCompatTable}}{{APIRef("Service Workers API")}}
+ +

The ServiceWorkerGlobalScope interface of the ServiceWorker API represents the global execution context of a service worker.

+ +

Developers should keep in mind that the ServiceWorker state is not persisted across the termination/restart cycle, so each event handler should assume it's being invoked with a bare, default global state.

+ +

Once successfully registered, a service worker can and will be terminated when idle to conserve memory and processor power. An active service worker is automatically restarted to respond to events, such as {{domxref("ServiceWorkerGlobalScope.onfetch")}} or {{domxref("ServiceWorkerGlobalScope.onmessage")}}.

+ +

Additionally, synchronous requests are not allowed from within a service worker — only asynchronous requests, like those initiated via the {{domxref("GlobalFetch.fetch", "fetch()")}} method, can be used.

+ +

This interface inherits from the {{domxref("WorkerGlobalScope")}} interface, and its parent {{domxref("EventTarget")}}, and therefore implements properties from {{domxref("WindowTimers")}}, {{domxref("WindowBase64")}}, and {{domxref("WindowEventHandlers")}}.

+ +

{{InheritanceDiagram(700, 85, 20)}}

+ +

Properties

+ +
+
{{domxref("ServiceWorkerGlobalScope.clients")}} {{readonlyinline}}
+
Contains the {{domxref("Clients")}} object associated with the service worker.
+
{{domxref("ServiceWorkerGlobalScope.registration")}} {{readonlyinline}}
+
Contains the {{domxref("ServiceWorkerRegistration")}} object that represents the service worker's registration.
+
{{domxref("ServiceWorkerGlobalScope.caches")}} {{readonlyinline}}
+
Contains the {{domxref("CacheStorage")}} object associated with the service worker.
+
+ +

Events

+ +
+
activate
+
Occurs when a {{domxref("ServiceWorkerRegistration")}} acquires a new {{domxref("ServiceWorkerRegistration.active")}} worker.
+ Also available via the {{domxref("ServiceWorkerGlobalScope.onactivate")}} property.
+
fetch
+
Occurs when a {{domxref("GlobalFetch.fetch", "fetch()")}} is called.
+ Also available via the {{domxref("ServiceWorkerGlobalScope.onfetch")}} property.
+
install
+
Occurs when a {{domxref("ServiceWorkerRegistration")}} acquires a new {{domxref("ServiceWorkerRegistration.installing")}} worker.
+ Also available via the {{domxref("ServiceWorkerGlobalScope.oninstall")}} property.
+
message
+
Occurs when incoming messages are received. Controlled pages can use the {{domxref("MessagePort.postMessage()")}} method to send messages to service workers. The service worker can optionally send a response back via the {{domxref("MessagePort")}} exposed in event.data.port, corresponding to the controlled page.
+ Also available via the {{domxref("ServiceWorkerGlobalScope.onmessage")}} property.
+
notificationclick
+
Occurs when a user clicks on a displayed notification.
+ Also available via the {{domxref("ServiceWorkerGlobalScope.onnotificationclick")}} property.
+
notificationclose
+
Occurs — when a user closes a displayed notification.
+ Also available via the {{domxref("ServiceWorkerGlobalScope.onnotificationclose")}} property.
+
push
+
Occurs when a server push notification is received.
+ Also available via the {{domxref("ServiceWorkerGlobalScope.onpush")}} property.
+
pushsubscriptionchange
+
Occurs when a push subscription has been invalidated, or is about to be invalidated (e.g. when a push service sets an expiration time).
+ Also available via the {{domxref("ServiceWorkerGlobalScope.onpushsubscriptionchange")}} property.
+
sync
+
Triggered when a call to {{domxref("SyncManager.register")}} is made from a service worker client page. The attempt to sync is made either immediately if the network is available or as soon as the network becomes available. 
+ Also available via the {{domxref("ServiceWorkerGlobalScope.onsync")}} property.
+
+ +

Methods

+ +
+
{{domxref("ServiceWorkerGlobalScope.skipWaiting()")}}
+
Allows the current service worker registration to progress from waiting to active state while service worker clients are using it.
+
+ +

ServiceWorkerGlobalScope implements {{domxref("WorkerGlobalScope")}} — which implements {{domxref("WindowOrWorkerGlobalScope")}}. Therefore it also has the following property available to it:

+ +
+
{{domxref("GlobalFetch.fetch()")}}
+
Starts the process of fetching a resource. This returns a promise that resolves to the {{domxref("Response")}} object representing the response to your request. This algorithm is the entry point for the fetch handling handed to the service worker context.
+
+ +

Examples

+ +

This code snippet is from the service worker prefetch sample (see prefetch example live.) The {{domxref("ServiceWorkerGlobalScope.onfetch")}} event handler listens for the fetch event. When fired, the code returns a promise that resolves to the first matching request in the {{domxref("Cache")}} object. If no match is found, the code fetches a response from the network.

+ +

The code also handles exceptions thrown from the {{domxref("GlobalFetch.fetch", "fetch()")}} operation. Note that an HTTP error response (e.g., 404) will not trigger an exception. It will return a normal response object that has the appropriate error code set.

+ +
self.addEventListener('fetch', function(event) {
+  console.log('Handling fetch event for', event.request.url);
+
+  event.respondWith(
+    caches.match(event.request).then(function(response) {
+      if (response) {
+        console.log('Found response in cache:', response);
+
+        return response;
+      }
+      console.log('No response found in cache. About to fetch from network...');
+
+      return fetch(event.request).then(function(response) {
+        console.log('Response from network is:', response);
+
+        return response;
+      }, function(error) {
+        console.error('Fetching failed:', error);
+
+        throw error;
+      });
+    })
+  );
+});
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Service Workers', '#serviceworkerglobalscope-interface', 'ServiceWorkerGlobalScope')}}{{Spec2('Service Workers')}}Initial definition
+ +

Browser compatibility

+ +
+ + +

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

+
+ +

See also

+ + diff --git a/files/pt-br/web/api/sharedworker/index.html b/files/pt-br/web/api/sharedworker/index.html new file mode 100644 index 0000000000..6aa6257435 --- /dev/null +++ b/files/pt-br/web/api/sharedworker/index.html @@ -0,0 +1,188 @@ +--- +title: SharedWorker +slug: Web/API/SharedWorker +tags: + - API + - Interface + - NeedsTranslation + - Reference + - SharedWorker + - TopicStub + - Web Workers + - Workers +translation_of: Web/API/SharedWorker +--- +
{{APIRef("Web Workers API")}}
+ +

The SharedWorker interface represents a specific kind of worker that can be accessed from several browsing contexts, such as several windows, iframes or even workers. They implement an interface different than dedicated workers and have a different global scope, {{domxref("SharedWorkerGlobalScope")}}.

+ +
+

Note: If SharedWorker can be accessed from several browsing contexts, all those browsing contexts must share the exact same origin (same protocol, host and port).

+
+ +
+

Note: In Firefox, shared workers cannot be shared between private (i.e. browsing in a private window) and non-private documents (see {{bug(1177621)}}.)

+
+ +

Constructors

+ +
+
{{domxref("SharedWorker.SharedWorker", "SharedWorker()")}}
+
Creates a shared web worker that executes the script at the specified URL.
+
+ +

Properties

+ +

Inherits properties from its parent, {{domxref("EventTarget")}}, and implements properties from {{domxref("AbstractWorker")}}.

+ +
+
{{domxref("AbstractWorker.onerror")}}
+
Is an {{domxref("EventListener")}} that is called whenever an {{domxref("ErrorEvent")}} of type error bubbles through the worker.
+
{{domxref("SharedWorker.port")}} {{readonlyInline}}
+
Returns a {{domxref("MessagePort")}} object used to communicate and control the shared worker.
+
+ +
+
+ +

Methods

+ +

Inherits methods from its parent, {{domxref("EventTarget")}}, and implements methods from {{domxref("AbstractWorker")}}.

+ +

Example

+ +

In our Basic shared worker example (run shared worker), we have two HTML pages, each of which uses some JavaScript to perform a simple calculation. The different scripts are using the same worker file to perform the calculation — they can both access it, even if their pages are running inside different windows.

+ +

The following code snippet shows creation of a SharedWorker object using the {{domxref("SharedWorker.SharedWorker", "SharedWorker()")}} constructor. Both scripts contain this:

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

Both scripts then access the worker through a {{domxref("MessagePort")}} object created using the {{domxref("SharedWorker.port")}} property. If the onmessage event is attached using addEventListener, the port is manually started using its start() method:

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

When the port is started, both scripts post messages to the worker and handle messages sent from it using port.postMessage() and port.onmessage, respectively:

+ +
first.onchange = function() {
+  myWorker.port.postMessage([first.value,second.value]);
+  console.log('Message posted to worker');
+}
+
+second.onchange = function() {
+  myWorker.port.postMessage([first.value,second.value]);
+  console.log('Message posted to worker');
+}
+
+myWorker.port.onmessage = function(e) {
+  result1.textContent = e.data;
+  console.log('Message received from worker');
+}
+ +

Inside the worker we use the {{domxref("SharedWorkerGlobalScope.onconnect")}} handler to connect to the same port discussed above. The ports associated with that worker are accessible in the {{event("connect")}} event's ports property — we then use {{domxref("MessagePort")}} start() method to start the port, and the onmessage handler to deal with messages sent from the main threads.

+ +
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(); // Required when using addEventListener. Otherwise called implicitly by onmessage setter.
+}
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "#sharedworker", "SharedWorker")}}{{Spec2('HTML WHATWG')}}No change from {{SpecName("Web Workers")}}.
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Support{{CompatChrome(4)}}{{CompatGeckoDesktop(29.0)}}{{CompatNo}}{{CompatOpera(10.60)}}5
+ {{CompatNo}} 6.1
Constructor name option{{CompatVersionUnknown}}{{CompatGeckoDesktop(55)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Support{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("33.0")}}{{CompatNo}}11.55.1
+ {{CompatNo}} 7.1
Constructor name option{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile(55)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

See also

+ + diff --git a/files/pt-br/web/api/sharedworker/port/index.html b/files/pt-br/web/api/sharedworker/port/index.html new file mode 100644 index 0000000000..248878949c --- /dev/null +++ b/files/pt-br/web/api/sharedworker/port/index.html @@ -0,0 +1,111 @@ +--- +title: SharedWorker.port +slug: Web/API/SharedWorker/port +translation_of: Web/API/SharedWorker/port +--- +
{{APIRef("Web Workers API")}}
+ +

A propriedade port do {{domxref ("SharedWorker")}} retorna um objeto {{domxref ("MessagePort")}} usado para comunicar e controlar o shared worker.

+ +

 

+ +

Sintaxe

+ +
myWorker.port;
+ +

Valor

+ +

Um objeto {{domxref("MessagePort")}}.

+ +

Exemplo

+ +

O snippet de código a seguir mostra a criação de um objeto SharedWorker usando o construtor {{domxref ("SharedWorker.SharedWorker", "SharedWorker ()")}} . Vários scripts podem acessar o worker através de um objeto do tipo {{domxref ("MessagePort")}} , usando a propriedade SharedWorker.port  — A porta é iniciada usando o método start() .

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

Veja um exemplo completo Basic shared worker example (run shared worker.)

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "#dom-sharedworker-port", "AbstractWorker.onerror")}}{{Spec2('HTML WHATWG')}}No change from {{SpecName("Web Workers")}}.
{{SpecName('Web Workers', "#dom-sharedworker-port", "AbstractWorker.onerror")}}{{Spec2('Web Workers')}}Initial definition
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Support{{CompatChrome(4)}}{{CompatGeckoDesktop(29.0)}}{{CompatNo}}{{CompatOpera(10.60)}}5
+ {{CompatNo}} 6.1
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)Firefox OS (Gecko)IE MobileOpera MobileSafari Mobile
Support{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("33.0")}}2.1{{CompatNo}}11.55.1
+ {{CompatNo}} 7.1
+
+ +

See also

+ + diff --git a/files/pt-br/web/api/speechgrammar/index.html b/files/pt-br/web/api/speechgrammar/index.html new file mode 100644 index 0000000000..c1a3aac1cf --- /dev/null +++ b/files/pt-br/web/api/speechgrammar/index.html @@ -0,0 +1,79 @@ +--- +title: SpeechGrammar +slug: Web/API/SpeechGrammar +tags: + - API + - Experimental + - Fala + - Interface + - Referencia + - SpeechGrammar + - Web Speech API + - reconhecimento +translation_of: Web/API/SpeechGrammar +--- +

{{APIRef("Web Speech API")}}{{SeeCompatTable}}

+ +

A interface SpeechGrammar da Web Speech API representa um conjunto de palavras ou padrões de palavras, os quais, nós queremos que o serviço de reconhecimento reconheça.

+ +

A gramática é definida usando JSpeech Grammar Format (JSGF.) Outros formatos podem ser suportados no futuro.

+ +

Construtor

+ +
+
{{domxref("SpeechGrammar.SpeechGrammar()")}}
+
Cria um novo objeto SpeechGrammar.
+
+ +

Propriedades

+ +
+
{{domxref("SpeechGrammar.src")}}
+
Define e retorna a string contendo a gramática contida na instância do objeto SpeechGrammar.
+
{{domxref("SpeechGrammar.weight")}} {{optional_inline}}
+
Define e retorna o peso do objeto SpeechGrammar.
+
+ +

Exemplos

+ +
var grammar = '#JSGF V1.0; grammar colors; public <color> = aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;'
+var recognition = new SpeechRecognition();
+var speechRecognitionList = new SpeechGrammarList();
+speechRecognitionList.addFromString(grammar, 1);
+recognition.grammars = speechRecognitionList;
+
+
+console.log(speechRecognitionList[0].src); // deveria retornar o mesmo conteúdo da variável grammar
+console.log(speechRecognitionList[0].weight); // deveria retornar 1 - o mesmo peso definido na linha 4.
+
+ +

Especificações

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Speech API', '#speechreco-speechgrammar', 'SpeechGrammar')}}{{Spec2('Web Speech API')}} 
+ +

Compatibilidade com os navegadores

+ +
+ + +

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

+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/speechsynthesis/index.html b/files/pt-br/web/api/speechsynthesis/index.html new file mode 100644 index 0000000000..889e129516 --- /dev/null +++ b/files/pt-br/web/api/speechsynthesis/index.html @@ -0,0 +1,194 @@ +--- +title: SpeechSynthesis +slug: Web/API/SpeechSynthesis +tags: + - API + - Elocução + - Experimental + - Fala + - Interface + - Referencia + - SpeechSynthesis + - Web Speech API + - sintetização +translation_of: Web/API/SpeechSynthesis +--- +

{{APIRef("Web Speech API")}}{{SeeCompatTable}}

+ +

A interface SpeechSynthesis da Web Speech API é a interface controladora para o serviço de fala; este pode ser usado para obter informações sobre as vozes sintetizadas disponíveis no dispositivo, reproduzir e pausar uma elocução, além de outros comandos.

+ +

Propriedades

+ +

SpeechSynthesis também herda propriedades da sua interface pai, {{domxref("EventTarget")}}.

+ +
+
{{domxref("SpeechSynthesis.paused")}} {{readonlyinline}}
+
Um {{domxref("Boolean")}} que retorna true se o objeto SpeechSynthesis está em estado de pausa.
+
{{domxref("SpeechSynthesis.pending")}} {{readonlyinline}}
+
Um {{domxref("Boolean")}} que retorna true se a fila de elocuções contém falas que ainda não foram reproduzidas.
+
{{domxref("SpeechSynthesis.speaking")}} {{readonlyinline}}
+
Um {{domxref("Boolean")}} que retorna true se uma elocução está sendo reproduzida atualmente — mesmo que SpeechSynthesis esteja em estado de pausa.
+
+ +

Tratamento de eventos

+ +
+
{{domxref("SpeechSynthesis.onvoiceschanged")}}
+
Disparado quando a lista de objetos {{domxref("SpeechSynthesisVoice")}} que pode ser retornada pelo método {{domxref("SpeechSynthesis.getVoices()")}} mudou.
+
+ +

Métodos

+ +

SpeechSynthesis também herda métodos da sua interface pai, {{domxref("EventTarget")}}.

+ +
+
{{domxref("SpeechSynthesis.cancel()")}}
+
Remove todas as elocuções da fila para reprodução.
+
{{domxref("SpeechSynthesis.getVoices()")}}
+
Retorna uma lista de objetos {{domxref("SpeechSynthesisVoice")}} representando todas as vozes disponíveis no dispositivo atuall
+
{{domxref("SpeechSynthesis.pause()")}}
+
Deixa o objeto SpeechSynthesis em estado de pausa.
+
{{domxref("SpeechSynthesis.resume()")}}
+
Retira o estado de pausa do objeto SpeechSynthesis: retoma a reprodução se ele estiver pausado.
+
{{domxref("SpeechSynthesis.speak()")}}
+
Adiciona uma {{domxref("SpeechSynthesisUtterance", "utterance")}} à fila de reprodução; ela será reproduzida assim que todas as elocuções enfileiradas anteriormente tenham sido reproduzidas.
+
+ +

Exemplos

+ +

Na nossa demonstração básica Speech synthesiser demo, nós primeiro pegamos uma referência para o controlador SpeechSynthesis usando window.speechSynthesis. Após definir algumas variáveis necessárias, nós obtemos uma lista de vozes disponíveis usando o método {{domxref("SpeechSynthesis.getVoices()")}} usando-as para popular um menu de seleção de forma que o usuário possa escolher a voz que desejar.

+ +

Dentro do tratamento inputForm.onsubmit, nós impedimos a submissão do formulário com preventDefault(),  instanciamos uma {{domxref("SpeechSynthesisUtterance")}} contendo o texto presente no {{htmlelement("input")}}, atribuímos a voz da elocução para a voz selecionada no elemento {{htmlelement("select")}}, e iniciamos a reprodução da elocução através do método {{domxref("SpeechSynthesis.speak()")}}.

+ +
var synth = window.speechSynthesis;
+
+var inputForm = document.querySelector('form');
+var inputTxt = document.querySelector('.txt');
+var voiceSelect = document.querySelector('select');
+
+var pitch = document.querySelector('#pitch');
+var pitchValue = document.querySelector('.pitch-value');
+var rate = document.querySelector('#rate');
+var rateValue = document.querySelector('.rate-value');
+
+var voices = [];
+
+function populateVoiceList() {
+  voices = synth.getVoices();
+
+  for(i = 0; i < voices.length ; i++) {
+    var option = document.createElement('option');
+    option.textContent = voices[i].name + ' (' + voices[i].lang + ')';
+
+    if(voices[i].default) {
+      option.textContent += ' -- DEFAULT';
+    }
+
+    option.setAttribute('data-lang', voices[i].lang);
+    option.setAttribute('data-name', voices[i].name);
+    voiceSelect.appendChild(option);
+  }
+}
+
+populateVoiceList();
+if (speechSynthesis.onvoiceschanged !== undefined) {
+  speechSynthesis.onvoiceschanged = populateVoiceList;
+}
+
+inputForm.onsubmit = function(event) {
+  event.preventDefault();
+
+  var utterThis = new SpeechSynthesisUtterance(inputTxt.value);
+  var selectedOption = voiceSelect.selectedOptions[0].getAttribute('data-name');
+  for(i = 0; i < voices.length ; i++) {
+    if(voices[i].name === selectedOption) {
+      utterThis.voice = voices[i];
+    }
+  }
+  utterThis.pitch = pitch.value;
+  utterThis.rate = rate.value;
+  synth.speak(utterThis);
+
+  inputTxt.blur();
+}
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoSituaçãoComentários
{{SpecName('Web Speech API', '#tts-section', 'SpeechSynthesis')}}{{Spec2('Web Speech API')}} 
+ +

Compatibilidade de Navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico{{CompatChrome(33)}}{{CompatVersionUnknown}}{{CompatGeckoDesktop(49)}}{{CompatNo}}{{CompatUnknown}}7
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChromeEdgeFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}2.0{{CompatNo}}{{CompatNo}}7.1
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/speechsynthesisutterance/index.html b/files/pt-br/web/api/speechsynthesisutterance/index.html new file mode 100644 index 0000000000..96c51a0c87 --- /dev/null +++ b/files/pt-br/web/api/speechsynthesisutterance/index.html @@ -0,0 +1,177 @@ +--- +title: SpeechSynthesisUtterance +slug: Web/API/SpeechSynthesisUtterance +tags: + - API + - Experimental + - Interface + - NeedsTranslation + - Reference + - SpeechSynthesisUtterance + - TopicStub + - Web Speech API + - speech + - synthesis +translation_of: Web/API/SpeechSynthesisUtterance +--- +

{{APIRef("Web Speech API")}}{{SeeCompatTable}}

+ +

The SpeechSynthesisUtterance interface of the Web Speech API represents a speech request. It contains the content the speech service should read and information about how to read it (e.g. language, pitch and volume.)

+ +

Constructor

+ +
+
{{domxref("SpeechSynthesisUtterance.SpeechSynthesisUtterance()")}}
+
Returns a new SpeechSynthesisUtterance object instance.
+
+ +

Properties

+ +

SpeechSynthesisUtterance also inherits properties from its parent interface, {{domxref("EventTarget")}}.

+ +
+
{{domxref("SpeechSynthesisUtterance.lang")}}
+
Gets and sets the language of the utterance.
+
{{domxref("SpeechSynthesisUtterance.pitch")}}
+
Gets and sets the pitch at which the utterance will be spoken at.
+
{{domxref("SpeechSynthesisUtterance.rate")}}
+
Gets and sets the speed at which the utterance will be spoken at.
+
{{domxref("SpeechSynthesisUtterance.text")}}
+
Gets and sets the text that will be synthesised when the utterance is spoken.
+
{{domxref("SpeechSynthesisUtterance.voice")}}
+
Gets and sets the voice that will be used to speak the utterance.
+
{{domxref("SpeechSynthesisUtterance.volume")}}
+
Gets and sets the volume that the utterance will be spoken at.
+
+ +

Event handlers

+ +
+
{{domxref("SpeechSynthesisUtterance.onboundary")}}
+
Fired when the spoken utterance reaches a word or sentence boundary.
+
{{domxref("SpeechSynthesisUtterance.onend")}}
+
Fired when the utterance has finished being spoken.
+
{{domxref("SpeechSynthesisUtterance.onerror")}}
+
Fired when an error occurs that prevents the utterance from being succesfully spoken.
+
{{domxref("SpeechSynthesisUtterance.onmark")}}
+
Fired when the spoken utterance reaches a named SSML "mark" tag.
+
{{domxref("SpeechSynthesisUtterance.onpause")}}
+
Fired when the utterance is paused part way through.
+
{{domxref("SpeechSynthesisUtterance.onresume")}}
+
Fired when a paused utterance is resumed.
+
{{domxref("SpeechSynthesisUtterance.onstart")}}
+
Fired when the utterance has begun to be spoken.
+
+ +

Examples

+ +

In our basic Speech synthesiser demo, we first grab a reference to the SpeechSynthesis controller using window.speechSynthesis. After defining some necessary variables, we retrieve a list of the voices available using {{domxref("SpeechSynthesis.getVoices()")}} and populate a select menu with them so the user can choose what voice they want.

+ +

Inside the inputForm.onsubmit handler, we stop the form submitting with preventDefault(),  use the {{domxref("SpeechSynthesisUtterance.SpeechSynthesisUtterance()", "constructor")}} to create a new utterance instance containing the text from the text {{htmlelement("input")}}, set the utterance's {{domxref("SpeechSynthesisUtterance.voice","voice")}} to the voice selected in the {{htmlelement("select")}} element, and start the utterance speaking via the {{domxref("SpeechSynthesis.speak()")}} method.

+ +
var synth = window.speechSynthesis;
+
+var inputForm = document.querySelector('form');
+var inputTxt = document.querySelector('input');
+var voiceSelect = document.querySelector('select');
+
+var voices = synth.getVoices();
+
+for(i = 0; i < voices.length ; i++) {
+  var option = document.createElement('option');
+  option.textContent = voices[i].name + ' (' + voices[i].lang + ')';
+  option.setAttribute('data-lang', voices[i].lang);
+  option.setAttribute('data-name', voices[i].name);
+  voiceSelect.appendChild(option);
+}
+
+inputForm.onsubmit = function(event) {
+  event.preventDefault();
+
+  var utterThis = new SpeechSynthesisUtterance(inputTxt.value);
+  var selectedOption = voiceSelect.selectedOptions[0].getAttribute('data-name');
+  for(i = 0; i < voices.length ; i++) {
+    if(voices[i].name === selectedOption) {
+      utterThis.voice = voices[i];
+    }
+  }
+  synth.speak(utterThis);
+  inputTxt.blur();
+}
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Speech API', '#utterance-attributes', 'SpeechSynthesisUtterance')}}{{Spec2('Web Speech API')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(33)}}{{CompatGeckoDesktop(49)}}{{CompatNo}}{{CompatUnknown}}7
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChromeFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}2.0{{CompatNo}}{{CompatNo}}7.1
+
+ +

See also

+ + diff --git a/files/pt-br/web/api/speechsynthesisutterance/voice/index.html b/files/pt-br/web/api/speechsynthesisutterance/voice/index.html new file mode 100644 index 0000000000..22f884d58b --- /dev/null +++ b/files/pt-br/web/api/speechsynthesisutterance/voice/index.html @@ -0,0 +1,130 @@ +--- +title: SpeechSynthesisUtterance.voice +slug: Web/API/SpeechSynthesisUtterance/voice +tags: + - API + - Experimental + - Fala + - SpeechSynthesisUtterance + - Voz + - Web Speech API +translation_of: Web/API/SpeechSynthesisUtterance/voice +--- +
{{APIRef("Web Speech API")}}{{SeeCompatTable}}
+ +

A propriedade voice  da interface {{domxref("SpeechSynthesisUtterance")}} retorna e configura a voz que será usada para a fala.

+ +

Essa propriedade deve ser configurada para um dos objetos {{domxref("SpeechSynthesisVoice")}} retornado por {{domxref("SpeechSynthesis.getVoices()")}}. Se não for configurada no momento da fala, a voz usada será a determinada como default na propriedade {{domxref("SpeechSynthesisUtterance.lang","lang")}}.

+ +

Sintaxe

+ +
var myVoice = speechSynthesisUtteranceInstance.voice;
+speechSynthesisUtteranceInstance.voice = speechSynthesisVoiceInstance;
+
+ +

Valor

+ +

Um objeto {{domxref("SpeechSynthesisVoice")}}.

+ +

Examplo

+ +
var synth = window.speechSynthesis;
+
+var inputForm = document.querySelector('form');
+var inputTxt = document.querySelector('input');
+var voiceSelect = document.querySelector('select');
+
+var voices = synth.getVoices();
+
+  ...
+
+inputForm.onsubmit = function(event) {
+  event.preventDefault();
+
+  var utterThis = new SpeechSynthesisUtterance(inputTxt.value);
+  var selectedOption = voiceSelect.selectedOptions[0].getAttribute('data-name');
+  for(i = 0; i < voices.length ; i++) {
+    if(voices[i].name === selectedOption) {
+      utterThis.voice = voices[i];
+    }
+  }
+  synth.speak(utterThis);
+  inputTxt.blur();
+}
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('Web Speech API', '#dfn-utterancevoice', 'voice')}}{{Spec2('Web Speech API')}} 
+ +

Compatiblidade dos navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(33)}}{{CompatGeckoDesktop(49)}}{{CompatNo}}{{CompatUnknown}}7
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChromeFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}2.0{{CompatNo}}{{CompatNo}}7.1
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/storage/clear/index.html b/files/pt-br/web/api/storage/clear/index.html new file mode 100644 index 0000000000..7542b3873a --- /dev/null +++ b/files/pt-br/web/api/storage/clear/index.html @@ -0,0 +1,131 @@ +--- +title: Storage.clear() +slug: Web/API/Storage/clear +tags: + - API + - Armazenamento + - Armazenamento web + - Referencia + - metodo +translation_of: Web/API/Storage/clear +--- +

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

+ +

O método clear() da interface {{domxref("Storage")}}, quando realizado uma chamada, todas as chaves do armazenamento são esvaziadas.

+ +

Syntaxe

+ +
storage.clear();
+ +

Parametros

+ +

Nenhum parametro..

+ +

Retorno

+ +

Nenhum retorno.

+ +

 

+ +

Exemplo

+ +

 

+ +

A função abaixo cria três itens e armazenam localmente, depois remove todos utilizando a função clear().

+ +
function populateStorage() {
+  localStorage.setItem('bgcolor', 'red');
+  localStorage.setItem('font', 'Helvetica');
+  localStorage.setItem('image', 'myCat.png');
+
+  localStorage.clear();
+}
+ +
+

Nota: Para visualizar um exemplo real, veja nossa seção Demonstração de Web Storage.

+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('Web Storage', '#dom-storage-clear', 'clear()')}}{{Spec2('Web Storage')}} 
+ +

Compatibilidade de navegador

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
localStorage43.5810.504
sessionStorage52810.504
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FuncionalidadeAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support2.1{{ CompatUnknown }}811iOS 3.2
+
+ +

Todos os navegadores possuem diferentes capacidades tanto para o localSotrage quanto para sessionSotrage. Você pode verificar uma lista detalhada de capacidades de diversos navegadores.

+ +
+

Nota: a versão iOS 5.1, Safari Mobile utiliza a pasta cache para armazenar os dados do localStorage, onde possivelmente podem perder os dados quando ocorrer pouco espaço no SO.

+
+ +

Veja também

+ +

Utilizando a API Web Storage

diff --git a/files/pt-br/web/api/storage/getitem/index.html b/files/pt-br/web/api/storage/getitem/index.html new file mode 100644 index 0000000000..46c49c6e0c --- /dev/null +++ b/files/pt-br/web/api/storage/getitem/index.html @@ -0,0 +1,79 @@ +--- +title: localStorage.getItem() +slug: Web/API/Storage/getItem +translation_of: Web/API/Storage/getItem +--- +

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

+ +

Passar o nome da chave para o método getItem() da interface {{domxref("Storage")}} retornará o seu valor.

+ +

Sintaxe

+ +
var aValue = localStorage.getItem(keyName);
+
+ +

Parâmetros

+ +
+
keyName
+
Um {{domxref("DOMString")}} contendo o nome da chave cujo valor você quer obter.
+
+ +

Retorno

+ +

Um {{domxref("DOMString")}} contendo o valor da chave. Se a chave não existe, é retornado null.

+ +

Exemplo

+ +

A função seguinte recupera três itens armazenados no local storage e usa-os para definir estilos customizados em uma página.

+ +
function setStyles() {
+  var currentColor = localStorage.getItem('bgcolor');
+  var currentFont = localStorage.getItem('font');
+  var currentImage = localStorage.getItem('image');
+
+  document.getElementById('bgcolor').value = currentColor;
+  document.getElementById('font').value = currentFont;
+  document.getElementById('image').value = currentImage;
+
+  htmlElem.style.backgroundColor = '#' + currentColor;
+  pElem.style.fontFamily = currentFont;
+  imgElem.setAttribute('src', currentImage);
+}
+ +
+

Nota: Para ver essa funcionalidade aplicada a um exemplo real, veja nossa Web Storage Demo.

+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComment
{{SpecName('Web Storage', '#dom-storage-getitem', 'getItem()')}}{{Spec2('Web Storage')}}
+ +

Compatibilidade

+ +
{{Compat("api.Storage.getItem")}}
+ +
+ +

Os níveis de compatibilidade podem variar em todos os navegadores, tanto para o localStorage quanto para o sessionStorage. Aqui temos estatísticas detalhadas dos níveis de compatibilidade para vários navegadores.

+ +
+

Nota: A partir da versão 5.1 do iOS, o Safari Mobile armazena os dados do localStorage na pasta do cache, sujeito a ser apagado em caso de espaço insificiente.

+
+ +

Veja também

+ +

Usando a API Web Storage

diff --git a/files/pt-br/web/api/storage/index.html b/files/pt-br/web/api/storage/index.html new file mode 100644 index 0000000000..e500e88cfa --- /dev/null +++ b/files/pt-br/web/api/storage/index.html @@ -0,0 +1,119 @@ +--- +title: Storage +slug: Web/API/Storage +tags: + - API + - Interface + - NeedsTranslation + - Reference + - Storage + - TopicStub + - Web Storage + - data +translation_of: Web/API/Storage +--- +

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

+ +

A interface de Armazenamento da Web Storage API fornece acesso ao armazenamento de sessão ou armazenamento local para um domínio específico, permitindo que você, por exemplo, adicione, modifique ou exclua itens de dados armazenados.

+ +

Se você quiser manipular o armazenamento de sessão para um domínio, você chama o método {{domxref ("Window.sessionStorage")}}; Se você quiser manipular o armazenamento local para um domínio, você chama {{domxref ("Window.localStorage")}}.

+ +

Propriedades

+ +
+
{{domxref("Storage.length")}} {{readonlyInline}}
+
Retorna um número inteiro que representa o número de itens de dados armazenados no objeto Storage.
+
+ +

Métodos

+ +
+
{{domxref("Storage.key()")}}
+
Quando passado um número n, este método retornará o nome da n-ésima chave no armazenamento..
+
+ +
+
{{domxref("Storage.getItem()")}}
+
Quando passado um nome de chave, retornará o valor dessa chave.
+
{{domxref("Storage.setItem()")}}
+
Quando passado um nome de chave e valor, irá adicionar essa chave para o armazenamento, ou atualizar o valor dessa chave, se já existir.
+
{{domxref("Storage.removeItem()")}}
+
Quando passado um nome de chave, irá remover essa chave do armazenamento.
+
{{domxref("Storage.clear()")}}
+
Quando chamado, irá esvaziar todas as chaves fora do armazenamento.
+
+ +

Exemplos

+ +

Aqui acessamos um objeto Storage chamando localStorage. Primeiro testamos se o armazenamento local contém itens de dados usando! localStorage.getItem ('bgcolor'). Se isso acontecer, executaremos uma função chamada setStyles () que agarra os itens de dados usando {{domxref("localStorage.getItem()")}} E usa esses valores para atualizar estilos de página. Se não, executamos outra função, populateStorage (), que usa {{domxref("localStorage.setItem()")}} Para definir os valores do item, em seguida, executa setStyles ().

+ +
if(!localStorage.getItem('bgcolor')) {
+  populateStorage();
+} else {
+  setStyles();
+}
+
+function populateStorage() {
+  localStorage.setItem('bgcolor', document.getElementById('bgcolor').value);
+  localStorage.setItem('font', document.getElementById('font').value);
+  localStorage.setItem('image', document.getElementById('image').value);
+
+  setStyles();
+}
+
+function setStyles() {
+  var currentColor = localStorage.getItem('bgcolor');
+  var currentFont = localStorage.getItem('font');
+  var currentImage = localStorage.getItem('image');
+
+  document.getElementById('bgcolor').value = currentColor;
+  document.getElementById('font').value = currentFont;
+  document.getElementById('image').value = currentImage;
+
+  htmlElem.style.backgroundColor = '#' + currentColor;
+  pElem.style.fontFamily = currentFont;
+  imgElem.setAttribute('src', currentImage);
+}
+ +
+

Nota: Para ver isso funcionando como um exemplo completo de trabalho, consulte nossa Demonstração de armazenamento na Web.

+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('Web Storage', '#the-storage-interface', 'Storage')}}{{Spec2('Web Storage')}} 
+ +

Compatibilidade com navegadores

+ +

 

+ + + +

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

+ +

 

+ +
 
+ +

[1] Desde o iOS 5.1, o Safari Mobile armazena os dados localStorage na pasta de cache, que está sujeita a limpeza ocasional a pedido do sistema operacional, normalmente se o espaço for curto.

+ +

Todos os navegadores têm diferentes níveis de capacidade para o localStorage e sessionStorage. Aqui está um resumo detalhado de todas as capacidades de armazenamento para vários navegadores.

+ +

Veja também

+ +

Using the Web Storage API

diff --git a/files/pt-br/web/api/storage/key/index.html b/files/pt-br/web/api/storage/key/index.html new file mode 100644 index 0000000000..9ed50459ad --- /dev/null +++ b/files/pt-br/web/api/storage/key/index.html @@ -0,0 +1,72 @@ +--- +title: Storage.key() +slug: Web/API/Storage/key +translation_of: Web/API/Storage/key +--- +
{{APIRef("Web Storage API")}}
+ +

O método key() da interface {{domxref("Storage")}}, quando passado um número n, retorna o nome da n-ésima chave no dado objeto Storage. A ordem das chaves é definida pelo user-agent, então não deve-se confiar nela.

+ +

Syntax

+ +
var aKeyName = storage.key(index);
+ +

Parâmetros

+ +
+
index
+
Um inteiro representando o número da chave que deseja obter. Esse é um índice que começa em zero.
+
+ +

Retorno

+ +

Uma {{domxref("DOMString")}} contendo o nome da chave. Se o index não existir, retornará null.

+ +

Exemplos

+ +

A função a seguir itera sobre as chaves do armazenamento local:

+ +
function forEachKey(callback) {
+  for (var i = 0; i < localStorage.length; i++) {
+    callback(localStorage.key(i));
+  }
+}
+ +

A função a seguir itera sobre as chaves do armazenamento local e obtém o valor de cada chave:

+ +
for(var i =0; i < localStorage.length; i++){
+  console.log(localStorage.getItem(localStorage.key(i)));
+}
+ +
+

Nota: Pra ver um exemplo real, consulte nossa Demonstração de armazenamento na Web.

+
+ +

Especificações

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

Compatibilidade com navegadores

+ + + +

{{Compat("api.Storage.key")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/storage/length/index.html b/files/pt-br/web/api/storage/length/index.html new file mode 100644 index 0000000000..fad990d9a8 --- /dev/null +++ b/files/pt-br/web/api/storage/length/index.html @@ -0,0 +1,130 @@ +--- +title: Storage.length +slug: Web/API/Storage/length +tags: + - API + - Armazenamento + - Armazenamento web + - Propriedade + - Referencia + - Somente Leitura + - Web Storage +translation_of: Web/API/Storage/length +--- +

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

+ +

A propriedade length, que é somente leitura, da interface {{domxref("Storage")}} retorna um inteiro que representa o número de itens armazenados no objeto Storage.

+ +

Sintaxe

+ +
var aLength = storage.length;
+ +

Retorno

+ +

Um inteiro

+ +

Exemplo

+ +

A função a seguir adiciona três itens ('bgcolor', 'font' e 'image') ao local storage do domínio atual, em seguida retorna o número de itens no storage:

+ +
function populateStorage() {
+  localStorage.setItem('bgcolor', 'yellow');
+  localStorage.setItem('font', 'Helvetica');
+  localStorage.setItem('image', 'cats.png');
+
+  localStorage.length; // should return 3
+}
+ +
+

Nota: Para um exemplo do mundo real, veja nosso Web Storage Demo.

+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('Web Storage', '#dom-storage-length', 'length')}}{{Spec2('Web Storage')}} 
+ +

Compatibilidade com browsers

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
localStorage4{{CompatVersionUnknown}}3.5810.504
sessionStorage5{{CompatUnknown}}2810.504
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support2.1{{CompatVersionUnknown}}{{ CompatUnknown }}811iOS 3.2
+
+ +

Cada browser tem uma capacidade variada para localStorage e sessionStorage. Aqui existe um tabela detalhada sobre a capacidade de armazenamento de cada browser.

+ +
+

Nota: desde o iOS 5.1, o Safari Mobile armazena os dados do localStorage no folder de cache, que está sujeito a uma limpeza ocasional baseada em regras do SO, tipicamente, quando o espaço está se esgotando.

+
+ +

Veja também

+ +

Usando a API Web Storage

diff --git a/files/pt-br/web/api/storage/removeitem/index.html b/files/pt-br/web/api/storage/removeitem/index.html new file mode 100644 index 0000000000..851f926173 --- /dev/null +++ b/files/pt-br/web/api/storage/removeitem/index.html @@ -0,0 +1,124 @@ +--- +title: Storage.removeItem() +slug: Web/API/Storage/removeItem +translation_of: Web/API/Storage/removeItem +--- +

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

+ +

O método removeItem() da interface {{domxref("Storage")}}, quando passado um nome de chave, irá remover essa chave do armazenamento.

+ +

Syntax

+ +
storage.removeItem(keyName);
+ +

Parâmetros

+ +
+
keyName
+
A {{domxref("DOMString")}} contendo o nome da chave que você deseja remover.
+
+ +

Retorno

+ +

Nenhum valor de retorno.

+ +

Exemplo

+ +

A função a seguir cria três itens de dados no armazenamento local, em seguida, remove o item "image".

+ +
function populateStorage() {
+  localStorage.setItem('bgcolor', 'red');
+  localStorage.setItem('font', 'Helvetica');
+  localStorage.setItem('image', 'myCat.png');
+
+  localStorage.removeItem('image');
+}
+ +
+

Nota: Para ver o uso em um exemplo prático veja nosso Web Storage Demo.

+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentários
{{SpecName('Web Storage', '#dom-storage-removeitem', 'removeItem()')}}{{Spec2('Web Storage')}} 
+ +

Compatibilidade

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
localStorage43.5810.504
sessionStorage52810.504
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support2.1{{ 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.

+ +
+

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

+
+ +

Veja também

+ +

Usando a API Web Storage

diff --git a/files/pt-br/web/api/storage/setitem/index.html b/files/pt-br/web/api/storage/setitem/index.html new file mode 100644 index 0000000000..90a964fbc8 --- /dev/null +++ b/files/pt-br/web/api/storage/setitem/index.html @@ -0,0 +1,131 @@ +--- +title: Storage.setItem() +slug: Web/API/Storage/setItem +tags: + - Referencia +translation_of: Web/API/Storage/setItem +--- +

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

+ +

O método setItem() da interface {{domxref("Storage")}}, quando passado 'chave' e 'valor', irá adicionar esta chave ao storage, ou atualizar o valor caso a chave já exista.

+ +

Syntax

+ +
storage.setItem(keyName, keyValue);
+ +

Parâmetros

+ +
+
keyName
+
Um {{domxref("DOMString")}} contendo o nome da chave que você deseja criar ou alterar.
+
keyValue
+
Um {{domxref("DOMString")}} contendo o valor da chave que você está criando ou atualizando.
+
+ +

Retornos

+ +

Sem retorno.

+ +

Exceções

+ +

setItem() poderá lançar uma exceção caso o storage esteja cheio. Particularmente, no Safari Mobile (desde o iOS 5) sempre irá lançar quando o usuário entrar em modo privado (Safari define a quota para 0 bytes no modo privado ao contrário de outros navegadores que permitem o armazenamento em modo privado, usando recipientes de dados separados).
+ Assim os desenvolvedores devem certificar-se de sempre tratar as possíveis exceções do setItem().

+ +

Exemplo

+ +

A função abaixo irá criar três dados dentro do local storage.

+ +
function populateStorage() {
+  localStorage.setItem('bgcolor', 'red');
+  localStorage.setItem('font', 'Helvetica');
+  localStorage.setItem('image', 'myCat.png');
+}
+ +
+

Nota: Para ver ele sendo usado em um exemplo real, consulte nosso Web Storage Demo.

+
+ +

Especificações

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Storage', '#dom-storage-setitem', 'setItem()')}}{{Spec2('Web Storage')}} 
+ + + +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
localStorage43.5810.504
sessionStorage52810.504
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support2.1{{ CompatUnknown }}811iOS 3.2
+
+ +

Todos os navegadores têm diferentes níveis de capacidade para tanto localStorage e sessionStorage. Aqui você encontra uma detalhada capacidade detalhada para vários browsers.

+ +
+

Nota: desde a versão iOS 5.1, Mobile Safari os dados na pasta 'cache' estão sujeito a limpezas ocasionais devido ao pouco espaço disponível.

+
+ +

Veja também

+ +

Usando a Web Storage API

diff --git a/files/pt-br/web/api/storagemanager/index.html b/files/pt-br/web/api/storagemanager/index.html new file mode 100644 index 0000000000..30be398f06 --- /dev/null +++ b/files/pt-br/web/api/storagemanager/index.html @@ -0,0 +1,53 @@ +--- +title: StorageManager +slug: Web/API/StorageManager +tags: + - API + - Interface + - Persistence + - Quotas + - Reference + - Secure context + - Storage + - Storage API + - StorageManager + - Usage +translation_of: Web/API/StorageManager +--- +

{{securecontext_header}}{{SeeCompatTable}}{{APIRef("Storage")}}

+ +

StorageManager é uma inteface da Storage API que fornece uma interface para controlar as permissões de gravações e estima o espaço disponível. Você pode obter a referência desta interface usando {{domxref("navigator.storage")}} ou {{domxref("WorkerNavigator.storage")}}.

+ +

Métodos

+ +
+
{{domxref("StorageManager.estimate()")}} {{securecontext_inline}}
+
Retorna um objeto {{domxref("StorageEstimate")}} contendo números de uso e cota para sua origem.
+
{{domxref("StorageManager.persist()")}} {{securecontext_inline}}
+
Retorna uma {{jsxref('Promise')}} que resolve como true se o agente de usuário for capaz de gravar o armazenamento do seu site.
+
{{domxref("StorageManager.persisted()")}} {{securecontext_inline}}
+
Retorna uma {{jsxref('Promise')}} que resolve como true se alguma gravação já foi concedida para o armazenamento do seu site.
+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('Storage','#storagemanager','StorageManger')}}{{Spec2('Storage')}}Definição inicial.
+ +

Compatibilidade entre navegadores

+ + + +

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

diff --git a/files/pt-br/web/api/streams_api/concepts/index.html b/files/pt-br/web/api/streams_api/concepts/index.html new file mode 100644 index 0000000000..575d59cf67 --- /dev/null +++ b/files/pt-br/web/api/streams_api/concepts/index.html @@ -0,0 +1,121 @@ +--- +title: Conceitos da API Stream +slug: Web/API/Streams_API/Concepts +tags: + - API + - Streams + - conceitos +translation_of: Web/API/Streams_API/Concepts +--- +
{{apiref("Streams")}}
+ +

Streams API adiciona conjunto muito útil de ferramentas à plataforma web, provendo objetos que permitem ao JavaScript acessar via programação dados de stream recebidos pela rede e processá-los conforme desejado pelo desenvolvedor. Alguns conceitos e terminologias associadas a streams podem ser novos pra você - este artigo explicará tudo o que você precisa saber.

+ +

Readable streams

+ +

Um readable stream pode ser representado em JavaScript por um objeto {{domxref("ReadableStream")}} que flui de uma underlying source - é um recurso em algum lugar na rede ou outro lugar no domínio do qual deseja obter dados..

+ +

Há dois tipos de fontes subjacentes:

+ + + +

O dado é lido sequencialmente em pequenos blocos de informação chamado chunks. Um chunk por ser um simples byte, ou, pode ser algo maior como um typed array de um certo tamanho.
+ Um simples stream pode conter chunks de diferentes tamanhos e tipos.
+

+ +

Os chunks alocados em um stream são ditos enqueued (enfileirados) — isto significa que eles estão aguardando em uma fila prontos para serem lidos. Uma internal queue rastreia os chunks que ainda não foram lidos (veja filas internas e estratégias de enfileiramento na sessão abaixo).

+ +

Os chunks dentro de um stream são lidos por um reader — este processa o dado de um chunk por vez, permitindo fazer qualquer tipo de operação que desejar .O reader com mais outro código de processamento junto é chamado consumer.

+ +

Há também uma construção que você usará chamada controller — cada reader tem um controller associado que lhe permite controlar o stream (por exemplo, cancelá-lo se desejar).

+ +

Apenas um reader pode ler um stream por vez; quando um reader é criado e inicia a leitura de um stream (um active reader), dizemos que ele está atrelado a ele. Se você deseja outro reader para iniciar a leitura de seu stream, você precisa tipicamente cancelar o primeiro reader antes de fazer qualquer coisa (embora você possa usar um stream tee, veja Teeing na sessão abaixo)

+ +

Observe que há dois tipos diferentes de readable streams. Assim como um readable stream convencional há um tipo chamado byte stream - este é uma versão extendida de um stream convencional para leitura de underlying byte sources (de outra forma conhecido como BYOB, ou "bring your own buffer"). Estes permitem que streams sejam lidos diretamente em um buffer fornecido pelo desenvolvedor, minimizando a cópia necessária. Tal underlying stream (e por extensão, reader e controller) seu código dependerá em primeiro lugar de como o stream foi criado (veja o {{domxref("ReadableStream.ReadableStream()")}} construtor de página).

+ +
+

Importante: Bytes streams não estão implementados ainda em algum lugar, e foram levantadas questões sobre se os detalhes de especificação estão em condições para serem implementados. Isto pode mudar com o tempo.

+
+ +

Você pode fazer uso dos stream readers já implementados via mecanismos como {{domxref("Response.body")}} como uma requisição, ou com seus próprios streams usando o {{domxref("ReadableStream.ReadableStream()")}} como construtor.

+ +

Teeing

+ +

Embora um único reader possa ler um stream por vez, é possível dividir um stream em duas cópias idênticas, que podem então serem lidas por dois readers distintos. Isto é chamado teeing. 

+ +

Em JavaScript, isto pode ser alcançado pelo método {{domxref("ReadableStream.tee()")}} — ele retorna um array contendo duas cópias idêniticas o readable stream original, o qual pode então ser lido independentemente por dois readers separados.

+ +

Você deve fazê-lo por exemplo em um ServiceWorker se deseja pegar a resposta de um servidor e disponibilizar via stream no navegador, mas, também disponibilizá-lo via cache do ServiceWorker. Uma vez que o corpo da resposta não pode ser consumido mais que uma vez, e um stream não pode ser lido por mais de um reader por vez, você precisaria de duas cópias para fazer isto.

+ +

+ +

Writable streams

+ +

Um writable stream é o destino o qual você pode escrever dados, representado em JavaScript pelo objeto {{domxref("WritableStream")}}. Ele serve como uma camada de abstração sobre um underlying sink — um I/O de baixo-nivel que sincroniza quais dados brutos são escritos.

+ +

O dado é escrito para o stream via um writer, um chunk por vez. Um chunk pode ter uma infinidade de formas, assim como os chunk em um reader. Você pode usar qualquer código que desejar para produzir chunks prontos para escrever, mais o código associado ao producer.

+ +

Quando um writer é criado e inicia a escrita para um stream (um active writer), dizemos estar locked (atrelado) a este. Apenas um writer opde escrever em um writable stream por vez. Se deseja outro writer iniciar a escrita em seu stream, você deve tipicamente abortá-lo antes de anexar outro write à ele.

+ +

Uma internal queue mantém os chunks que foram escritos por um stream mas não foram ainda processados por underlying sink.

+ +

Há uma construção que você usará chamada controller — cada writer tem um controller associado que permite a você controlar o stream (por exemplo, abortá-lo se desejado).

+ +

+ +

Você pode fazer uso de writable streams usando o construtor 

+ +

You can make use of writable streams using the {{domxref("WritableStream.WritableStream()")}}. Estes atualmente possuem uma disponibilidade limitada nos navegadores.

+ +

Pipe chains

+ +

A API de Streams torna possível encadear streams (ou pelo menos irá fazer quando os navegadores implementarem a funcionalidade relevante para tal) usando uma estrutura chamada pipe chain. Há dois métodos disponíveis na especificação para facilitá-lo:

+ + + +

Para iniciar um pipe chain é chamado o original source, e no final é chamado ultimate sink.

+ +

+ +
+

Nota: Esta funcionalidade não está totalmente pensada ainda, embora disponível em muitos navegadores. Até certo ponto espero que a especificação dos writers pode contribuir para algo como uma clase TransformStream para criar facilmente transform stream.

+
+ +

Backpressure

+ +

Um importante conceito sobre streams é backpressure — é um processo pelo qual um stream simples ou uma pipe chain ajusta a velocidade de leitura/escrita. Quando um stream mais tarde na conrrente continua ocupado e não está ainda pronto para aceitar mais chunks, ele envia um sinal de volta através da corrente informar mais tarde o transform stream (ou a fonte original) para diminuir a velocidade de entrega conforme apropriado tal que você não precise terminar com um gargalo em algum lugar.

+ +

Para usar backpressure em um ReadableStream, podemos perguntar ao controller pelo tamanho do chunk desejado pelo consumer consultando o atributo {{domxref("ReadableStreamDefaultController.desiredSize")}} no controller. Se estiver muito baixo, nosso ReadableStream pode informar sua underlying source de dados e o backpressure junto a cadeira de stream.

+ +

Se mais tarde o consumer novamente deseja receber dados, podemos usar o método pull no stream para informar nossa underlying source para alimentar nosso stream com dados.

+ +

Internal queues and queuing strategies

+ +

Como mencionado antes, os chunks de um stream que não foram ainda processados e finalizados são mantidos por uma internal queue (fila interna).

+ + + +

Filas internas trabalham com uma queuing strategy, o qual dita informar a backpressure baseado na internal queue state.

+ +

Em geral, a estratégia compara o tamanho dos chunks na fila com o valor chamado no high water mark, o qual é o total do maior valor de chunk que a fila pode gerenciar de modo realista.

+ +

O cálculo realizado é

+ +
high water mark - total size of chunks in queue = desired size
+ +

O desired size é o tamanho de chunks que um stream ainda pode aceitar para manter o fluxo do stream menor que o high water mark. Após o cálculo ser efetuado, a geração de chunks terá sua velocidade reduzida ou aumentada conforme apropriado para manter o fluxo do stream o mais rápido possível enquanto mantém o tamanho desejado acima de zero. Se o valor cair para zero (ou menor no caso de writable streams), significa que os chunks estão sendo gerados mais rápido que o stream pode lidar, o qual resulta em problemas.

+ +
+

Nota: O que ocorre no caso em que valor desejado for zero ou negativo não foi definido na especificação até o momento. Paciência é uma virtude. 

+
+ +

Como um exemplo, vamos pegar um chunk de tamanho 1, e uma high water mark de 3. Isto significa que até 3 chunks podem ser enfileirados antes que a high water mark seja alcançada e o  backpressure aplicado.

diff --git a/files/pt-br/web/api/streams_api/index.html b/files/pt-br/web/api/streams_api/index.html new file mode 100644 index 0000000000..c382b3e7f8 --- /dev/null +++ b/files/pt-br/web/api/streams_api/index.html @@ -0,0 +1,157 @@ +--- +title: Streams API +slug: Web/API/Streams_API +tags: + - API + - Experimental + - Landing + - NeedsTranslation + - Reference + - Streams + - TopicStub +translation_of: Web/API/Streams_API +--- +
{{SeeCompatTable}}{{APIRef("Streams")}}
+ +
A API Streams permite que o JavaScript acesse programaticamente fluxos de dados recebidos pela rede e os processe conforme desejado pelo desenvolvedor.
+ +

+ +

Conceitos e Uso

+ + + +

O streaming envolve a divisão de um recurso que você deseja receber pela rede em pequenos blocos e, em seguida, processa esses blocos aos poucos. Isso é algo que os navegadores fazem de qualquer maneira ao receber recursos para serem exibidos em páginas da web — o buffer de vídeos e mais está gradualmente disponível para reprodução, e às vezes você verá imagens sendo exibidas gradualmente conforme mais é carregado.

+ +

Mas isto nunca esteve disponível para JavaScript antes. Anteriormente, se quiséssemos processar um recurso de algum tipo (seja ele um vídeo, ou um arquivo de texto, etc.), Teríamos que baixar o arquivo inteiro, espera até que seja desserializado em um formato adequado, então processa todo o lote após ser totalmente recebido.

+ +

Com o Streams disponível para JavaScript, tudo isso muda - agora você pode começar a processar dados brutos com JavaScript bit a bit assim que estiverem disponíveis no lado do cliente, sem a necessidade de gerar um buffer, string ou blob.

+ +

+ + + +

Também há mais vantagens - você pode detectar quando os fluxos começam ou terminam, encadeia os fluxos juntos, trata os erros e cancela os fluxos quando necessário e reage à velocidade em que o fluxo está sendo lido.

+ +

O uso básico de Streams gira em torno de tornar as respostas disponíveis como streams. Por exemplo, a resposta {{domxref("Body")}} retornada com sucesso de uma fetch request pode ser exposta como um {{domxref("ReadableStream")}}, e você pode lê-lo usando um leitor criado com {{domxref("ReadableStream.getReader()")}}, cancela-lo com {{domxref("ReadableStream.cancel()")}}, etc.

+ + + +

Usos mais complicados envolvem a criação de seu próprio fluxo usando o contrutor {{domxref("ReadableStream.ReadableStream", "ReadableStream()")}}, por exemplo para processar dados dentro de um service worker.

+ +

Você também pode gravar dados em streams usando {{domxref("WritableStream")}}.

+ +
+

Note: Você pode encontrar muito mais detalhes sobre a teoria e prática de streams em nossos artigos — Streams API concepts, Using readable streams, e Using writable streams.

+
+ +

Stream interfaces

+ +

Readable streams

+ +
+
{{domxref("ReadableStream")}}
+
Represents a readable stream of data. It can be used to handle response streams of the Fetch API, or developer-defined streams (e.g. a custom {{domxref("ReadableStream.ReadableStream", "ReadableStream()")}} constructor).
+
{{domxref("ReadableStreamDefaultReader")}}
+
Represents a default reader that can be used to read stream data supplied from a network (e.g. a fetch request).
+
{{domxref("ReadableStreamDefaultController")}}
+
Represents a controller allowing control of a {{domxref("ReadableStream")}}'s state and internal queue. Default controllers are for streams that are not byte streams.
+
+ +

Writable streams

+ +
+
{{domxref("WritableStream")}}
+
Provides a standard abstraction for writing streaming data to a destination, known as a sink. This object comes with built-in backpressure and queuing.
+
{{domxref("WritableStreamDefaultWriter")}}
+
Represents a default writable stream writer that can be used to write chunks of data to a writable stream.
+
{{domxref("WritableStreamDefaultController")}}
+
Represents a controller allowing control of a {{domxref("WritableStream")}}'s state. When constructing a WritableStream, the underlying sink is given a corresponding WritableStreamDefaultController instance to manipulate.
+
+ + + +
+
{{domxref("ByteLengthQueuingStrategy")}}
+
Provides a built-in byte length queuing strategy that can be used when constructing streams.
+
{{domxref("CountQueuingStrategy")}}
+
Provides a built-in chunk counting queuing strategy that can be used when constructing streams.
+
+ +

Extensions to other APIs

+ +
+
{{domxref("Request")}}
+
When a new Request object is constructed, you can pass it a {{domxref("ReadableStream")}} in the body property of its RequestInit dictionary.  This Request could then be passed to a {{domxref("WindowOrWorkerGlobalScope.fetch()")}} to commence fetching the stream.
+
{{domxref("Body")}}
+
The response {{domxref("Body")}} returned by a successful fetch request is exposed by default as a {{domxref("ReadableStream")}}, and can have a reader attached to it, etc.
+
+ + + +
+

Important: these are not implemented anywhere as yet, and questions have been raised as to whether the spec details are in a finished enough state for them to be implemented. This may change over time.

+
+ +
+
{{domxref("ReadableStreamBYOBReader")}}
+
Represents a BYOB ("bring your own buffer") reader that can be used to read stream data supplied by the developer (e.g. a custom {{domxref("ReadableStream.ReadableStream", "ReadableStream()")}} constructor).
+
{{domxref("ReadableByteStreamController")}}
+
Represents a controller allowing control of a {{domxref("ReadableStream")}}'s state and internal queue. Byte stream controllers are for byte streams.
+
{{domxref("ReadableStreamBYOBRequest")}}
+
Represents a pull into request in a {{domxref("ReadableByteStreamController")}}.
+
+ +

Examples

+ +

We have created a directory of examples to go along with the Streams API documentation — see mdn/dom-examples/streams. The examples are as follows:

+ + + +

Examples from other developers:

+ + + +

Specifications

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

Browser compatibility

+ + + +

WritableStream

+ +

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

+ +

See also

+ + diff --git a/files/pt-br/web/api/subtlecrypto/derivekey/index.html b/files/pt-br/web/api/subtlecrypto/derivekey/index.html new file mode 100644 index 0000000000..16f39fb7e1 --- /dev/null +++ b/files/pt-br/web/api/subtlecrypto/derivekey/index.html @@ -0,0 +1,270 @@ +--- +title: SubtleCrypto.deriveKey() +slug: Web/API/SubtleCrypto/deriveKey +tags: + - API + - Criptografía + - Crypto + - Referencia + - SubtleCrypto + - Web + - metodo +translation_of: Web/API/SubtleCrypto/deriveKey +--- +

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

+ +

O método SubtleCrypto.deriveKey() retorna como {{jsxref("Promise")}} de um recentemente gerado {{domxref("CryptoKey")}} derivada de uma master key e um algoritmo específico dados como parâmetro.

+ +

Sintaxe

+ +
var result = crypto.subtle.deriveKey(algorithm, masterKey, derivedKeyAlgorithm, extractable, keyUsages);
+
+ +

Parâmetros

+ + + +

Valor de retorno

+ + + +

Exceções

+ +

A promise é rejeitada quando uma das seguintes exceções é encontrada:

+ + + +

Exemplo

+ +

Aqui está um exemplo de como usar deriveKey() para criar uma Secure Remote Password (também nomeado de Proof of Secret) da password de um usuário.

+ +
// salt deve ser Uint8Array ou ArrayBuffer
+var saltBuffer = Unibabel.hexToBuffer('e85c53e7f119d41fd7895cdc9d7bb9dd');
+
+// não use métodos naïve para conversão de texto, senão caracteres
+// internacionais não terão a sequência correta de byte. Use o TextEncoder quando
+// possível ou então use polyfills relevantes
+var passphraseKey = Unibabel.utf8ToBuffer("I hëart årt and £$¢!");
+
+// Você deve primeiramente importar sua passphrase Uint8array em uma CryptoKey
+window.crypto.subtle.importKey(
+  'raw',
+  passphraseKey,
+  {name: 'PBKDF2'},
+  false,
+  ['deriveBits', 'deriveKey']
+).then(function(key) {
+
+  return window.crypto.subtle.deriveKey(
+    { "name": 'PBKDF2',
+      "salt": saltBuffer,
+      // não seja muito ambicioso, ou pelo menos tenha em mente
+      // que celulares com baixo poder de processamento vão acessar o seu app
+      "iterations": 100,
+      "hash": 'SHA-256'
+    },
+    key,
+
+    // Nota: para essa demo nós não vamos precisar de uma cipher suite,
+    // mas a API exige que a mesma seja especificada.
+
+    // Para AES o comprimento requerido é de 128 ou 256 bits (não bytes)
+    { "name": 'AES-CBC', "length": 256 },
+
+    // Independente da resposta a key é extraível (menos seguro) ou não extraível (mais seguro),
+    // quando falso, a key pode ser entregue apenas como um objeto crypto web, não inspecionado
+    true,
+
+    // esse objeto crypto web será permitido para apenas essas funções:
+    [ "encrypt", "decrypt" ]
+  )
+}).then(function (webKey) {
+
+  return crypto.subtle.exportKey("raw", webKey);
+
+}).then(function (buffer) {
+
+    var proofOfSecret = Unibabel.bufferToHex(buffer);
+    // esta proof-of-secret / password remota-segura
+    // pode agora ser enviada no lugar da password do usuário
+});
+ +

Nota: Por conta de não haver ferramentas nativas que convertam entre Uint8Array, Unicode, hex, e base64, você provavelmente vai querer utilizar algo como o Unibabel ou Buffer para converter entre eles.

+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{ SpecName('Web Crypto API', '#dfn-SubtleCrypto-method-deriveKey', 'SubtleCrypto.deriveKey()') }}{{ Spec2('Web Crypto API') }}Definição inicial.
+ +

Compatibilidade de Browser

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{ CompatChrome(37) }}{{CompatVersionUnknown}}{{ CompatGeckoDesktop(34) }}{{ CompatNo() }}{{ CompatUnknown() }}{{ CompatSafari(11) }}
PBKDF2{{ CompatChrome(42) }}{{CompatUnknown}}{{ CompatGeckoDesktop(34) }}{{ CompatNo() }}{{ CompatUnknown() }}{{ CompatSafari(11) }}
HKDF-CTR{{ CompatChrome(42) }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatUnknown() }}
DH{{ CompatNo() }}{{CompatUnknown}}{{ CompatGeckoDesktop(35) }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidEdgeChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}37{{ CompatGeckoMobile(34) }}{{ CompatNo }}{{ CompatUnknown() }}{{ CompatNo }}
PBKDF2{{CompatVersionUnknown}}{{CompatUnknown}}42{{ CompatGeckoMobile(34) }}{{ CompatNo }}{{ CompatUnknown() }}{{ CompatNo }}
HKDF-CTR{{CompatVersionUnknown}}{{CompatUnknown}}42{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
DH{{ CompatNo() }}{{CompatUnknown}}{{ CompatNo() }}{{ CompatGeckoMobile(35) }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +

Veja também

+ + + +

Dicionário:

+ +

"Key" = "Chave"

+ +

"Master key" = "Chave mestre"

+ +

"Proof-of-secret" = "Prova de segredo ou Atestado de sigilo"

+ +

"Password" = "Palavra passe ou Senha"

diff --git a/files/pt-br/web/api/subtlecrypto/generatekey/index.html b/files/pt-br/web/api/subtlecrypto/generatekey/index.html new file mode 100644 index 0000000000..0b2c8a8bb0 --- /dev/null +++ b/files/pt-br/web/api/subtlecrypto/generatekey/index.html @@ -0,0 +1,197 @@ +--- +title: SubtleCrypto.generateKey() +slug: Web/API/SubtleCrypto/GenerateKey +tags: + - API + - Referencia + - SubtleCrypto + - Web Crypto API + - metodo +translation_of: Web/API/SubtleCrypto/generateKey +--- +

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

+ +

O método SubtleCrypto.generateKey() retorna como {{jsxref("Promise")}} de uma recentemente gerada {{domxref("CryptoKey")}}, para algoritmos simétricos, ou uma {{domxref("CryptoKeyPair")}}, contendo duas keys recentemente geradas, para algoritmos assimétricos, que combina com o algoritmo, o uso e a extractividade são dados como parâmetro.

+ +

Sintaxe

+ +
var result = crypto.subtle.generateKey(algo, extractable, keyUsages);
+
+ +

Parâmetros

+ + + +

Valor de retorno

+ + + +

Exceções

+ +

A {{jsxref("Promise")}} é rejeitada quando a seguinte exceção é encontrada:

+ + + +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusCommentário
{{ SpecName('Web Crypto API', '#dfn-SubtleCrypto-method-generateKey', 'SubtleCrypto.generateKey()') }}{{ Spec2('Web Crypto API') }}Definição inicial.
+ +

Compatibilidade de Browser

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticasChromeEdgeFirefox (Gecko)Internet ExplorerEdgeOperaSafari
Suporte básico{{ CompatChrome(37) }}{{CompatVersionUnknown}}{{ CompatGeckoDesktop(34) }}{{ CompatNo() }}13{{ CompatNo }}
ECDSA{{CompatVersionUnknown}}{{CompatUnknown}}{{ CompatGeckoDesktop(36) }}{{ CompatNo() }}{{ CompatUnknown() }}{{ CompatNo() }}
DH{{ CompatNo() }}{{CompatUnknown}}{{ CompatGeckoDesktop(35) }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticasAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}37{{CompatVersionUnknown}}{{ CompatGeckoMobile(34) }}{{ CompatNo }}{{ CompatUnknown() }}{{ CompatNo }}
ECDSA{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{ CompatGeckoMobile(36) }}{{ CompatNo }}{{ CompatUnknown() }}{{ CompatNo }}
DH{{ CompatNo() }}{{CompatVersionUnknown}}{{CompatUnknown}}{{ CompatGeckoMobile(35) }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +

Veja também

+ + + +

Dicionário:

+ +

"Key" = "Chave"

diff --git a/files/pt-br/web/api/subtlecrypto/importkey/index.html b/files/pt-br/web/api/subtlecrypto/importkey/index.html new file mode 100644 index 0000000000..15c4102162 --- /dev/null +++ b/files/pt-br/web/api/subtlecrypto/importkey/index.html @@ -0,0 +1,169 @@ +--- +title: SubtleCrypto.importKey() +slug: Web/API/SubtleCrypto/importKey +tags: + - API + - Criptografía + - Referencia + - SubtleCrypto + - Web Crypto API + - metodo +translation_of: Web/API/SubtleCrypto/importKey +--- +

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

+ +

O método SubtleCrypto.importKey() retorna como {{jsxref("Promise")}} de uma {{domxref("CryptoKey")}} de uma informção dada como parâmetro.

+ +

Sintaxe

+ +
var result = crypto.subtle.importKey(format, keyData, algo, extractable, usages);
+
+ +

Parâmetros

+ + + +

Valor de retorno

+ + + +

Exceções

+ +

A promise é rejeitada quando umas das seguintes exceções é encontrada:

+ + + +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{ SpecName('Web Crypto API', '#dfn-SubtleCrypto-method-importKey', 'SubtleCrypto.importKey()') }}{{ Spec2('Web Crypto API') }}Definição inicial.
+ +

Compatibilidade de Browser

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticasChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{ CompatChrome(37) }}{{CompatVersionUnknown}}{{ CompatGeckoDesktop(34) }}{{ CompatNo() }}{{ CompatUnknown() }}{{ CompatNo }}
ECDH{{ CompatUnknown() }}{{CompatUnknown}}{{ CompatGeckoDesktop(41) }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticasAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}37{{CompatVersionUnknown}}{{ CompatGeckoMobile(34) }}{{ CompatNo }}{{ CompatUnknown() }}{{ CompatNo }}
ECDH{{ CompatUnknown() }}{{ CompatUnknown() }}{{CompatUnknown}}{{ CompatGeckoDesktop(41) }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

Veja também

+ + + +

Dicionário:

+ +

"Key" = "Chave"

+ +

 

diff --git a/files/pt-br/web/api/subtlecrypto/index.html b/files/pt-br/web/api/subtlecrypto/index.html new file mode 100644 index 0000000000..a949d1cfa5 --- /dev/null +++ b/files/pt-br/web/api/subtlecrypto/index.html @@ -0,0 +1,83 @@ +--- +title: SubtleCrypto +slug: Web/API/SubtleCrypto +tags: + - API + - Interface + - NeedsTranslation + - Referencia + - TopicStub + - Web Crypto API +translation_of: Web/API/SubtleCrypto +--- +

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

+ +

A interface SubtleCrypto representa um conjunto de criptografias primitivas. E está disponível via propriedades {{domxref("Crypto.subtle")}} disponíveis em uma janela de contexto (via {{domxref("Window.crypto")}}).

+ +
+

Por especificação: "Desenvolvedores fazendo uso da interface SubtleCrypto devem estar cientes das preocupações associadas com o design e a implementação de vários algoritmos providos. Os algoritmos brutos são providos em ordem para permitir aos desenvolvedores uma felixibilidade máxima na implementação de uma variedade de protocolos e aplicações, cada um deve representar a composição e os parâmetros de segurança em uma maneira única que necessita do uso de algoritmos brutos."

+
+ +

Propriedades

+ +

Esta interface não herda e nem implementa nenhuma propriedade.

+ +

Métodos

+ +

Esta interface não herda nenhum método

+ +
+
{{domxref("SubtleCrypto.encrypt()")}}
+
Retorna uma {{jsxref("Promise")}} da informação criptografada correspondente com o texto, algoritmo e chave key dados como parâmetros.
+
{{domxref("SubtleCrypto.decrypt()")}}
+
Retorna uma {{jsxref("Promise")}} da informação correspondente ao texto encriptografado, algoritmo e key dados como parâmetros.
+
{{domxref("SubtleCrypto.sign()")}}
+
Retorna uma {{jsxref("Promise")}} de uma assinatura correspondente ao texto, algoritmo e key dados como parâmetros.
+
{{domxref("SubtleCrypto.verify()")}}
+
Retorna uma {{jsxref("Promise")}} de um valor {{jsxref("Boolean")}} indicando se a assinatura dada como parâmetro combina com o texto, algoritmo e key também dados como parâmetros.
+
{{domxref("SubtleCrypto.digest()")}}
+
Retorna uma {{jsxref("Promise")}} de um resumo gerado a partir do algoritmo e texto dados como parâmetros.
+
{{domxref("SubtleCrypto.generateKey()")}}
+
Retorna uma {{jsxref("Promise")}} de uma recentemente gerada {{domxref("CryptoKey")}}, para algoritmos simétricos, ou uma {{domxref("CryptoKeyPair")}}, contendo duas novas keys simétricas, para algoritmos assimétricos, que combina com o algoritmo, os usos e a extrabilidade dados como parâmetros.
+
{{domxref("SubtleCrypto.deriveKey()")}}
+
Retorna uma {{jsxref("Promise")}} de uma recentemente gerada {{domxref("CryptoKey")}} derivada de uma master key e um algoritmo específico dados como parâmetros.
+
{{domxref("SubtleCrypto.deriveBits()")}}
+
Retorna uma {{jsxref("Promise")}} de um buffer recentemente gerado de bits pseudo-randômicos derivados de uma master key e um algoritmo específico dados como parâmetros.
+
{{domxref("SubtleCrypto.importKey()")}}
+
Retorna uma {{jsxref("Promise")}} de uma {{domxref("CryptoKey")}} correspondente ao formato, o algoritmo, a informação da key bruta, o uso e a extrabilidade dados como parâmetros.
+
{{domxref("SubtleCrypto.exportKey()")}}
+
Retorna uma {{jsxref("Promise")}} deu uma buffer contendo a key no formato requisitado.
+
{{domxref("SubtleCrypto.wrapKey()")}}
+
Retorna uma {{jsxref("Promise")}} de uma key envolvida simetricamente para uso (transferência, armazenamento) em ambientes não seguros. O buffer envolvido retornado será no formato dado nos parâmetros, e contém a key envolvida com a key envolvendo e o algoritmo dado.
+
{{domxref("SubtleCrypto.unwrapKey()")}}
+
Retorna uma {{jsxref("Promise")}} de uma {{domxref("CryptoKey")}} correspondente à key envolvida dada como parâmetro.
+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{ SpecName('Web Crypto API', '#subtlecrypto-interface', 'SubtleCrypto') }}{{ Spec2('Web Crypto API') }}Definição inicial.
+ +

Compatibilidade de Browser

+ + + +

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

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/svgaelement/index.html b/files/pt-br/web/api/svgaelement/index.html new file mode 100644 index 0000000000..687b067178 --- /dev/null +++ b/files/pt-br/web/api/svgaelement/index.html @@ -0,0 +1,74 @@ +--- +title: SVGAElement +slug: Web/API/SVGAElement +tags: + - Imagem vetorial + - Vetores +translation_of: Web/API/SVGAElement +--- +
{{APIRef("SVG")}}
+ +
SVGAElement interface fornece acesso as propriedades do elemento {{SVGElement("a")}}, bem como metodos para manipula-los.
+ +

Propriedades

+ +

Esta interface também herda propriedades de sua interface pai,{{domxref("SVGGraphicsElement")}}, e implementa propriedades de {{domxref("SVGURIReference")}} e de {{domxref("HTMLHyperlinkElementUtils")}}.

+ +
+
{{domxref("SVGAElement.target")}} {{readonlyInline}}
+
It corresponds to the {{SVGAttr("target")}} attribute of the given element.
+
+ +

Metodos

+ +

Esta interface não tem metodos próprios, porém herda metodos da interface {{domxref("SVGGraphicsElement")}}.

+ +

Exemplos

+ +

No exemplo abaixo, o {{SVGAttr("target")}} atributo do elemento {{SVGElement("a")}} recebe o valor _blank e quando o link for clicado, ele notifica se a condição é verdadeira ou falsa.

+ +
var linkRef = document.querySelector("a");
+linkRef.target = "_self";
+
+linkRef.onclick = function(){
+  if (linkRef.target === "_blank") {
+    console.log("BLANK!");
+    linkRef.target = "_self";
+  } else {
+    console.log("SORRY! not _blank");
+  }
+} 
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName("SVG2", "linking.html#InterfaceSVGAElement")}}{{Spec2("SVG2")}}Replaced inheritance from {{domxref("SVGElement")}} by {{domxref("SVGGraphicsElement")}} and removed the interface implementations of {{domxref("SVGTests")}}, {{domxref("SVGLangSpace")}}, {{domxref("SVGExternalResourcesRequired")}}, {{domxref("SVGStylable")}}, and {{domxref("SVGTransformable")}} by {{domxref("HTMLHyperlinkElementUtils")}}
{{SpecName("SVG1.1", "linking.html#InterfaceSVGAElement")}}{{Spec2("SVG1.1")}}Definição inicial
+ +

Compatibilidade com o Navegador

+ + + +

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

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/svgaelement/svgalement.target/index.html b/files/pt-br/web/api/svgaelement/svgalement.target/index.html new file mode 100644 index 0000000000..ebd533b068 --- /dev/null +++ b/files/pt-br/web/api/svgaelement/svgalement.target/index.html @@ -0,0 +1,105 @@ +--- +title: SVGAElement.target +slug: Web/API/SVGAElement/SVGAlement.target +tags: + - Imagem vetorial + - Vetores +translation_of: Web/API/SVGAElement/target +--- +

{{APIRef("SVGAElement")}}

+ +

SVGAElement.target propriedade somente ler de {{domxref("SVGAElement")}} retorna um objeto {{domxref("SVGAnimatedString")}} que especifica a porção de um alvo sendo ele "window", "frame" ou "pane" no qual um documento será aberto quando o link for acionado.

+ +

Esta propriedade é usada quando existem dois ou mais possiveis alvos(destinos) para o documento, por exemplo, quando o documento pai é um arquivo .html ou .xhtml com varias telas (multi-frame).

+ +

Sintaxe

+ +
myLink.target = 'value';
+ +

Valor

+ +

Um {{domxref("SVGAnimatedString")}} indica o destino final do recurso que abre o documento assim que o link é acionado.

+ +

Valores para {{domxref("target")}} você pode ver aqui.

+ +

Exemplo

+ +

O código é foi retirado de "SVGAElement example code"

+ +
...
+var linkRef = document.querySelector('a');
+linkRef.target ='_blank';
+...
+ +

Especificações

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('SVG1.1', 'text.html#InterfaceSVGAElement', 'target')}}{{Spec2('SVG1.1')}} 
+ +

Compatibilidade com o navegador

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}9.0{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}{{ CompatVersionUnknown() }}{{ CompatUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/svganimatetransformelement/index.html b/files/pt-br/web/api/svganimatetransformelement/index.html new file mode 100644 index 0000000000..2dddfa5f0b --- /dev/null +++ b/files/pt-br/web/api/svganimatetransformelement/index.html @@ -0,0 +1,48 @@ +--- +title: SVGAnimateTransformElement +slug: Web/API/SVGAnimateTransformElement +translation_of: Web/API/SVGAnimateTransformElement +--- +
{{APIRef("SVG")}}
+ +

A interface SVGAnimateTransformElement corresponde ao elemento {{SVGElement("animateTransform")}}.

+ +

{{InheritanceDiagram(600, 140)}}

+ +

Propriedades

+ +

Essa interface não possui propriedades próprias mas as herda do seu pai,       {{domxref("SVGAnimationElement")}}.

+ +

Métodos

+ +

Essa interface não possui métodos próprios mas os herda do seu pai, {{domxref("SVGAnimationElement")}}.

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName("SVG Animations 2", "#InterfaceSVGAnimateTransformElement", "SVGAnimateTransformElement")}}{{Spec2("SVG Animations 2")}}No change
{{SpecName("SVG1.1", "animate.html#InterfaceSVGAnimateTransformElement", "SVGAnimateTransformElement")}}{{Spec2("SVG1.1")}}Initial definition
+ +

Compatibilidade

+ + + + + +

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

diff --git a/files/pt-br/web/api/url/createobjecturl/index.html b/files/pt-br/web/api/url/createobjecturl/index.html new file mode 100644 index 0000000000..430b49c457 --- /dev/null +++ b/files/pt-br/web/api/url/createobjecturl/index.html @@ -0,0 +1,42 @@ +--- +title: URL.createObjectURL() +slug: Web/API/URL/createObjectURl +translation_of: Web/API/URL/createObjectURL +--- +

{{ApiRef("URL API")}}{{SeeCompatTable}}

+ +

Resumo

+ +

Cria um novo objeto URL, cujo tempo de vida está ligado ao {{domxref("document")}} na janela na qual este objeto foi criado. O novo objeto URL representa o objeto {{domxref("File")}} ou o objeto {{domxref("Blob")}} passado como argumento.

+ +

Sintaxe

+ +
objetoURL = window.URL.createObjectURL(blob);
+
+ + + +

Exemplo

+ +

Veja Using object URLs to display images.

+ +

Notas

+ +

Cada vez que a função createObjectURL() é chamada, um novo objeto URL é criado, mesmo se você já tiver criado um objeto URL para esse mesmo arquivo. Cada objeto URL criado precisa ser liberado por meio de uma chamada a {{domxref("window.URL.revokeObjectURL()")}} quando este não for mais necessário. Os navegadores liberarão os objetos URL criados automaticamente quando o documento for descarregado; no entanto, para um desempenho e um gerenciamento de memória ótimos, se houver algum momento em que você puder liberar estes recursos explicitamente, você deveria fazê-lo.

+ +

Compatibilidade de navegadores

+ + + +

{{Compat("api.URL.createObjectURL")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/url/index.html b/files/pt-br/web/api/url/index.html new file mode 100644 index 0000000000..6e24c8efe7 --- /dev/null +++ b/files/pt-br/web/api/url/index.html @@ -0,0 +1,113 @@ +--- +title: URL +slug: Web/API/URL +translation_of: Web/API/URL +--- +
{{ApiRef("URL API")}} {{SeeCompatTable}}
+ +

The URL interface represent an object providing static methods used for creating object URLs.

+ +

When using a user agent where no constructor has been implemented yet, it is possible to access such an object using the non-standard {{domxref("Window.URL")}} properties (prefixed with Webkit- and Blink-based browser as Window.webkitURL).

+ +

Properties

+ +

Implements properties defined in {{domxref("URLUtils")}}.

+ +
+
{{domxref("URLUtils.href")}}
+
Is a {{domxref("DOMString")}} containing the whole URL.
+
{{domxref("URLUtils.protocol")}}
+
Is a {{domxref("DOMString")}} containing the protocol scheme of the URL, including the final ':'.
+
{{domxref("URLUtils.host")}}
+
Is a {{domxref("DOMString")}} containing the host, that is the hostname, a ':', and the port of the URL.
+
{{domxref("URLUtils.hostname")}}
+
Is a {{domxref("DOMString")}} containing the domain of the URL.
+
{{domxref("URLUtils.port")}}
+
Is a {{domxref("DOMString")}} containing the port number of the URL.
+
{{domxref("URLUtils.pathname")}}
+
Is a {{domxref("DOMString")}} containing an initial '/' followed by the path of the URL.
+
{{domxref("URLUtils.search")}}
+
Is a {{domxref("DOMString")}} containing a '?' followed by the parameters of the URL.
+
{{domxref("URLUtils.hash")}}
+
Is a {{domxref("DOMString")}} containing a '#' followed by the fragment identifier of the URL.
+
{{domxref("URLUtils.username")}}
+
Is a {{domxref("DOMString")}} containing the username specified before the domain name.
+
{{domxref("URLUtils.password")}}
+
Is a {{domxref("DOMString")}} containing the password specified before the domain name.
+
{{domxref("URLUtils.origin")}} {{readonlyInline}}
+
Returns a {{domxref("DOMString")}} containing the origin of the URL, that is its scheme, its domain and its port.
+
+ +
+
{{domxref("URLUtils.searchParams")}}
+
Returns a {{domxref("URLSearchParams")}} object allowing to access the GET query arguments contained in the URL.
+
+ +

Constructor

+ +
+
{{domxref("URL.URL", "URL()")}}
+
Creates and return a URL object composed from the given parameters.
+
+ +

Methods

+ +

The URL interface implements methods defined in {{domxref("URLUtils")}}.

+ +
+
{{domxref("URLUtils.toString()")}}
+
Returns a {{domxref("DOMString")}} containing the whole URL. It is a synonym for {{domxref("URLUtils.href")}}, though it can't be used to modify the value.
+
+ +

Static methods

+ +
+
{{ domxref("URL.createObjectURL()") }}
+
Returns a {{domxref("DOMString")}} containing a unique blob URL, that is a URL with blob: as its scheme, followed by an opaque string uniquely identifying the object in the browser.
+
{{ domxref("URL.revokeObjectURL()") }}
+
Revokes an object URL previously created using {{ domxref("URL.createObjectURL()") }}.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('File API', '#creating-revoking', 'URL')}}{{Spec2('File API')}}Added the static methods URL.createObjectURL() and URL.revokeObjectURL().
{{SpecName('URL', '#api', 'Node')}}{{Spec2('URL')}}Initial definition (implements URLUtils).
+ +

Browser compatibility

+ +

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

+ +

[1] From Gecko 2 (Firefox 4) to Gecko 18 included, Gecko supported this interface with the non-standard nsIDOMMozURLProperty internal type. As the only to access such an object was through {{domxref("window.URL")}}, in practice, this didn't make any difference.

+ +

Chrome Code - Scope Availability

+ +

To use from chrome code, JSM and Bootstrap scope, you have to import it like this:

+ +
Cu.importGlobalProperties(['URL']);
+
+ +

URL is available in Worker scopes.

+ +

See also

+ + diff --git a/files/pt-br/web/api/url/revokeobjecturl/index.html b/files/pt-br/web/api/url/revokeobjecturl/index.html new file mode 100644 index 0000000000..1a6c34027d --- /dev/null +++ b/files/pt-br/web/api/url/revokeobjecturl/index.html @@ -0,0 +1,107 @@ +--- +title: URL.revokeObjectURL() +slug: Web/API/URL/revokeObjectURL +translation_of: Web/API/URL/revokeObjectURL +--- +

{{ApiRef("URL")}}{{SeeCompatTable}}

+ +

Resumo

+ +

O método estático URL.revokeObjectURL() libera um objeto URL que foi criado préviamente chamando {{domxref("URL.createObjectURL()") }}.  Utilize este método quando terminar de usar um objeto URL, para informar o navegador que não é mais necessário manter a referência para o arquivo.

+ +

{{AvailableInWorkers}}

+ +

Sintaxe

+ +
window.URL.revokeObjectURL(objectURL);
+
+ +
+
objectURL
+
é um {{domxref("DOMString")}} representando o objeto URL que foi criado chamando {{domxref("URL.createObjectURL()") }}.
+
+ + + +

Exemplo

+ +

Veja Using object URLs to display images.

+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('File API', '#dfn-revokeObjectURL', 'URL')}}{{Spec2('File API')}}Initial definition
+ +

Compatibilidade de Navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support8.0[1]{{CompatGeckoDesktop(2.0)}}10.015.06.0[1]
+ 7.0
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}[1]{{CompatGeckoMobile(14.0)}}{{CompatVersionUnknown}}15.06.0[1]
+ 7.0
+
+ +

[1] Implementado com prefixo de URL como webkitURL.

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/url/searchparams/index.html b/files/pt-br/web/api/url/searchparams/index.html new file mode 100644 index 0000000000..a711b85fa2 --- /dev/null +++ b/files/pt-br/web/api/url/searchparams/index.html @@ -0,0 +1,45 @@ +--- +title: URL.searchParams +slug: Web/API/URL/searchParams +translation_of: Web/API/URL/searchParams +--- +

{{APIRef("")}}

+ +

A propriedade searchParams da interface {{domxref("URL")}} retorna um objeto {{domxref("URLSearchParams")}} permitindo acesso aos parâmetros enviados via GET que uma URL possui.

+ +

Sintaxe

+ +
var urlSearchParams = URL.searchParams;
+ +

Valor

+ +

Um objeto {{domxref("URLSearchParams")}}.

+ +

Exemplo

+ +

Se a URL da sua página é https://example.com/?name=Jonathan&age=18 você pode parsear os parametros 'name' e 'age' usando:

+ +
let params = (new URL(document.location)).searchParams;
+let name = params.get("name"); // é a string "Jonathan"
+let age = parseInt(params.get("age")); // é o número 18
+ +

Especificações

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('URL', '#dom-url-searchparams', 'searchParams')}}{{Spec2('URL')}}Definição inicial.
+ +

Browser compatibility

+ +

{{Compat("api.URL.searchParams")}}

diff --git a/files/pt-br/web/api/urlsearchparams/get/index.html b/files/pt-br/web/api/urlsearchparams/get/index.html new file mode 100644 index 0000000000..7a89676a9a --- /dev/null +++ b/files/pt-br/web/api/urlsearchparams/get/index.html @@ -0,0 +1,109 @@ +--- +title: URLSearchParams.get() +slug: Web/API/URLSearchParams/get +translation_of: Web/API/URLSearchParams/get +--- +

{{ApiRef("URL API")}}{{SeeCompatTable}} 

+ +

O métod get()  da interface {{domxref("URLSearchParams")}},  retorna o primeiro valor associado ao parametro de busca fornecido.

+ +

Syntax

+ +
URLSearchParams.get(name)
+ +

Parâmetros

+ +
+
name
+
O nome do parâmetro à ser retornado.
+
+ +

Retorno

+ +

Um {{domxref("USVString")}} se o parâmetro de pesquisa for encontrado; Caso contrário, null.

+ +

Exemplo

+ +

Se a URL da sua página é https://example.com/?name=Jonathan&age=18 você pode obter o parâmetro 'name' e 'age'  usando:

+ +
let params = new URLSearchParams(document.location.search.substring(1));
+let name = params.get("name"); // retorna a string "Jonathan"
+let age = parseInt(params.get("age"), 10); // retorna o número 18
+
+ +

Buscar um  parâmetro que não esteja presente na string de pesquisa, retornará  null:

+ +
let address = params.get("address"); // null
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComment
{{SpecName('URL', '#dom-urlsearchparams-get', "get()")}}{{Spec2('URL')}}Definição inicial.
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(49.0)}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatChrome(49.0)}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatChrome(49.0)}}
+
diff --git a/files/pt-br/web/api/urlsearchparams/index.html b/files/pt-br/web/api/urlsearchparams/index.html new file mode 100644 index 0000000000..00080b0ae5 --- /dev/null +++ b/files/pt-br/web/api/urlsearchparams/index.html @@ -0,0 +1,177 @@ +--- +title: URLSearchParams +slug: Web/API/URLSearchParams +tags: + - API + - API de URL + - Experimental + - Interface + - Referencia +translation_of: Web/API/URLSearchParams +--- +

{{ApiRef("URL API")}}

+ +

A interface URLSearchParams define métodos de utilização para trabalhar com query string de uma URL.

+ +

Uma implementação do objeto URLSearchParams pode diretamente ser usado em uma estrutura {{jsxref("Statements/for...of", "for...of")}}, em vez de {{domxref('URLSearchParams.entries()', 'entries()')}}: for (var p of mySearchParams) é equivalente de for (var p of mySearchParams.entries()).

+ +

Construtor

+ +
+
{{domxref("URLSearchParams.URLSearchParams", 'URLSearchParams()')}}
+
Construtor retorna um objeto URLSearchParams.
+
+ +

Propriedades

+ +

Esta interface não herda nenhuma propriedade.

+ +

Métodos

+ +

Esta interface não herda nenhum método.

+ +
+
{{domxref("URLSearchParams.append()")}}
+
Acrescenta um par de chave/valor específica com um novo parâmetro de busca.
+
{{domxref("URLSearchParams.delete()")}}
+
Exclui o parâmetro de busca informado, e seu valor associado, da lista de parâmetros de busca.
+
{{domxref("URLSearchParams.entries()")}}
+
Retorna um {{jsxref("Iteration_protocols","iterator")}} permitindo obter por todos os pares de chave/valor contidos neste objeto.
+
{{domxref("URLSearchParams.get()")}}
+
Retorna o primeiro valor associado ao parâmetro de busca informado.
+
{{domxref("URLSearchParams.getAll()")}}
+
Retorna todos os valores associados com o parâmetro de busca encontrado.
+
{{domxref("URLSearchParams.has()")}}
+
Retorna um {{jsxref("Boolean")}} indicando se cada um dos parâmetros de busca existe.
+
{{domxref("URLSearchParams.keys()")}}
+
Retorna um {{jsxref("Iteration_protocols", "iterator")}} permitindo obter todas as chaves dos pares de chave/valor contido neste objeto.
+
{{domxref("URLSearchParams.set()")}}
+
Define o valor associado ao parâmetro de busca com o valor informado. Se tiver mutios valores, exclua os outros.
+
{{domxref("URLSearchParams.toString()")}}
+
Retorna uma string contendo uma query string adequada pra usar numa URL.
+
{{domxref("URLSearchParams.values()")}}
+
Retorna um {{jsxref("Iteration_protocols", "iterator")}} permitindo obter todos os valores dos pares de chave/valor contido neste objeto.
+
+ +

Exemplo

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

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoSituaçãoComentário
{{SpecName('URL', '#urlsearchparams', "URLSearchParams")}}{{Spec2('URL')}}Initial definition.
+ +

Compatibilidade do navegador

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatChrome(49)}}{{CompatGeckoDesktop("29.0")}}{{CompatNo}}36{{CompatNo}}
entries(), keys(), values(), e suporte de for...of{{CompatChrome(49)}}{{CompatGeckoDesktop("44.0")}}{{CompatNo}}36{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Suporte básico{{CompatNo}}{{CompatChrome(49)}}{{CompatGeckoMobile("29.0")}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatChrome(49)}}
entries(), keys(), values(), e suporte de for...of{{CompatNo}}{{CompatChrome(49)}}{{CompatGeckoMobile("44.0")}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatChrome(49)}}
+
+ +

Veja também

+ + + +
+
diff --git a/files/pt-br/web/api/urlsearchparams/values/index.html b/files/pt-br/web/api/urlsearchparams/values/index.html new file mode 100644 index 0000000000..0bb1b06ff3 --- /dev/null +++ b/files/pt-br/web/api/urlsearchparams/values/index.html @@ -0,0 +1,112 @@ +--- +title: URLSearchParams.values() +slug: Web/API/URLSearchParams/values +translation_of: Web/API/URLSearchParams/values +--- +

{{APIRef("URL API")}}

+ +

O método URLSearchParams.values()retorna um {{jsxref("Iteration_protocols",'iterator')}} que permite passar por todos os valores do objeto. Os valores são objetos {{domxref("USVString")}}.

+ +
+

Nota: Esse método está disponível no Web Workers.

+
+ +

Sintaxe

+ +
searchParams.values();
+ +

Valor de retorno

+ +

Retorna um  {{jsxref("Iteration_protocols","iterator")}}.

+ +

Exemplo

+ +
// Cria um objeto URLSearchParams
+var searchParams = new URLSearchParams("key1=value1&key2=value2");
+
+// Mostra os pares de chave/valor
+for(var value of searchParams.values()) {
+  console.log(value);
+}
+ +

O resultado é:

+ +
value1
+value2
+ +

Especificações

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('URL', '#urlsearchparams','values() (as iterator<>)')}}{{Spec2('URL')}}Definição inicial.
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatNo}}{{CompatGeckoDesktop(44)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile(44)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatNo}}{{CompatNo}}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/validitystate/index.html b/files/pt-br/web/api/validitystate/index.html new file mode 100644 index 0000000000..e5bba7b7fb --- /dev/null +++ b/files/pt-br/web/api/validitystate/index.html @@ -0,0 +1,85 @@ +--- +title: ValidityState +slug: Web/API/ValidityState +tags: + - API + - Forms + - HTML DOM + - HTML5 + - Interface + - Validation +translation_of: Web/API/ValidityState +--- +
{{APIRef("HTML DOM")}} {{gecko_minversion_header("2.0")}}
+ +

A interface ValidityState representa os estados de validação que um elemento 
+ pode conter de acordo com as propriedades de validação abaixo. Juntas, elas podem explicar porque um elemento é inválido (caso seja) ao ser validado.

+ +

Propriedades

+ +

Para cada uma das propriedades Booleanas abaixo, caso retorne true, isso indica a razão específica porque a validação falhou, exceto no caso da propriedade valid, que retorna true no caso do elemento ser completamente válido e false caso contrário.

+ +
+
{{domxref("ValidityState.badInput")}} {{ReadOnlyInline}}
+
É um {{jsxref("Boolean")}} informando se o usuário inseriu um valor que o navegador é incapaz de converter.
+
{{domxref("ValidityState.customError")}} {{ReadOnlyInline}}
+
É um {{jsxref("Boolean")}} informando se o elemento possui uma mensagem de validação definida por setCustomValidity() para um valor não vázio.
+
{{domxref("ValidityState.patternMismatch")}} {{ReadOnlyInline}}
+
É um {{jsxref("Boolean")}} informando se o valor não combina com o padrão ({{htmlattrxref("pattern", "input")}}) especificado.
+
{{domxref("ValidityState.rangeOverflow")}} {{ReadOnlyInline}}
+
É um {{jsxref("Boolean")}} informando se o valor é maior do que o máximo especificado pelo atributo {{htmlattrxref("max", "input")}}.
+
{{domxref("ValidityState.rangeUnderflow")}} {{ReadOnlyInline}}
+
É um {{jsxref("Boolean")}} informando se o valor é menor do que o mínimo especificado pelo atributo {{htmlattrxref("min", "input")}}.
+
{{domxref("ValidityState.stepMismatch")}} {{ReadOnlyInline}}
+
É um {{jsxref("Boolean")}} informando se o valor não segue a regra definida pelo atributo {{htmlattrxref("step", "input")}}.
+
{{domxref("ValidityState.tooLong")}} {{ReadOnlyInline}}
+
É um {{jsxref("Boolean")}} informando se o valor ultrapassa o especificado pelo atributo maxlength para {{domxref("HTMLInputElement")}} ou {{domxref("HTMLTextAreaElement")}}. OBS: Isso nunca será true em navegadores como o Firefox, pois a inserção de valores não é permitida ao alcançar o valor definido em maxlength.
+
{{domxref("ValidityState.tooShort")}} {{ReadOnlyInline}}
+
É um {{jsxref("Boolean")}} informando se o valor não corresponde ao especificado no atributo minlength para {{domxref("HTMLInputElement")}} ou {{domxref("HTMLTextAreaElement")}}.
+
{{domxref("ValidityState.typeMismatch")}} {{ReadOnlyInline}}
+
É um {{jsxref("Boolean")}} informando se o valor não corresponde ao tipo de entrada definida. (Um exemplo é quando {{htmlattrxref("type", "input")}} é email ou url).
+
{{domxref("ValidityState.valid")}} {{ReadOnlyInline}}
+
É um {{jsxref("Boolean")}} informando se o elemento é completamente válido.
+
{{domxref("ValidityState.valueMissing")}} {{ReadOnlyInline}}
+
É um {{jsxref("Boolean")}} informando que o elemento tem o atributo {{htmlattrxref("required", "input")}}, mas não tem {{htmlattrxref("value", "input")}}.
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{ SpecName('HTML WHATWG', 'forms.html#the-constraint-validation-api', 'ValidityState') }}{{Spec2('HTML WHATWG')}}Live Standard
{{ SpecName('HTML5.1', '#the-constraint-validation-api', 'ValidityState') }}{{Spec2('HTML5.1')}}No change from the previous snapshot {{SpecName('HTML5 W3C')}}.
{{ SpecName('HTML5 W3C', 'forms.html#the-constraint-validation-api', 'ValidityState') }}{{Spec2('HTML5 W3C')}}First snapshot of  {{SpecName('HTML WHATWG')}} containing this interface.
+ +

Compatibilidade com navegadores

+ + + +

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

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/web_animations_api/index.html b/files/pt-br/web/api/web_animations_api/index.html new file mode 100644 index 0000000000..c18d6fec70 --- /dev/null +++ b/files/pt-br/web/api/web_animations_api/index.html @@ -0,0 +1,86 @@ +--- +title: Web Animations API +slug: Web/API/Web_Animations_API +tags: + - API + - Animation + - Landing + - NeedsTranslation + - Reference + - TopicStub + - Web Animations +translation_of: Web/API/Web_Animations_API +--- +

{{DefaultAPISidebar("Web Animations")}}

+ +

The Web Animations API allows for synchronizing and timing changes to the presentation of a Web page, i.e. animation of DOM elements. It does so by combining two models: the Timing Model and the Animation Model.

+ +

Concepts and usage

+ +

The Web Animations API provides a common language for browsers and developers to describe animations on DOM elements. To get more information on the concepts behind the API and how to use it, read Using the Web Animations API.

+ +

Web Animations interfaces

+ +
+
{{domxref("Animation")}}
+
Provides playback controls and a timeline for an animation node or source. Can take an object created with the {{domxref("KeyframeEffect.KeyframeEffect", "KeyframeEffect()")}} constructor.
+
{{domxref("KeyframeEffect")}}
+
Describes sets of animatable properties and values, called keyframes and their timing options. These can then be played using the {{domxref("Animation.Animation", "Animation()")}} constructor.
+
{{domxref("AnimationTimeline")}}
+
Represents the timeline of animation. This interface exists to define timeline features (inherited by {{domxref("DocumentTimeline")}} and future timeline objects) and is not itself accessed by developers.
+
{{domxref("AnimationEvent")}}
+
Actually part of CSS Animations.
+
{{domxref("DocumentTimeline")}}
+
Represents animation timelines, including the default document timeline (accessed using the {{domxref("Document.timeline")}} property).
+
{{domxref("EffectTiming")}}
+
{{domxref("Element.animate()")}}, {{domxref("KeyframeEffectReadOnly.KeyframeEffectReadOnly()")}}, and {{domxref("KeyframeEffect.KeyframeEffect()")}} all accept an optional dictionary object of timing properties.
+
+ +

Extensions to other interfaces

+ +

The Web Animations API adds some new features to {{domxref("document")}} and {{domxref("element")}}.

+ +

Extensions to the Document interface

+ +
+
{{domxref("document.timeline")}}
+
The DocumentTimeline object representing the default document timeline.
+
{{domxref("document.getAnimations()")}}
+
Returns an Array of {{domxref("Animation")}} objects currently in effect on elements in the document.
+
+

Extensions to the Element interface

+
+
{{domxref("Element.animate()")}}
+
A shortcut method for creating and playing an animation on an element. It returns the created {{domxref("Animation")}} object instance.
+
{{domxref("Element.getAnimations()")}}
+
Returns an Array of {{domxref("Animation")}} objects currently affecting an element or which are scheduled to do so in future.
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Animations')}}{{Spec2('Web Animations')}}Initial definition
+ +

See also

+ + diff --git a/files/pt-br/web/api/web_animations_api/usando_a_web_animations_api/index.html b/files/pt-br/web/api/web_animations_api/usando_a_web_animations_api/index.html new file mode 100644 index 0000000000..2743f68d65 --- /dev/null +++ b/files/pt-br/web/api/web_animations_api/usando_a_web_animations_api/index.html @@ -0,0 +1,358 @@ +--- +title: Usando a Web Animations API +slug: Web/API/Web_Animations_API/Usando_a_Web_Animations_API +tags: + - Alice + - Animação + - CSS + - Guía + - Iniciante + - JavaScript + - Timing + - Tutorial + - animar + - duration + - keyframes + - pausar + - pause + - play + - quadro-chave + - reverse + - web animations api +translation_of: Web/API/Web_Animations_API/Using_the_Web_Animations_API +--- +

{{DefaultAPISidebar("Web Animations")}}

+ +

A Web Animations API nos possibilita criar animações e controlar sua reprodução pelo JavaScript. Esse artigo vai te demonstrar esses conceitos com demonstrações e tutoriais com o temática de Alice no País das Maravilhas.

+ +

Conhecendo a Web Animations API

+ +

A Web Animations API abre a engine de animação do browser para os desenvolvedores manipularem via JavaScript. Esta API foi construída para se basear nas implementações das Animações CSS e Transições CSS, e deixam a porta aberta para futuros efeitos de animação. É um dos métodos mais performáticos para se animar na Web, permitindo que o browser faça internamente suas próprias otimizações, sem precisar depender de hacks, coerções ou {{domxref("Window.requestAnimationFrame()")}}.

+ +

Com a Web Animations API, podemos transferir as animações interativas das folhas de estilo para o JavaScript, separando comportamento de apresentação. Não vamos precisar mais depender de técnicas muito dependentes do DOM como propriedades do CSS e escopo de classes para controlar a direção da reprodução. E diferente de CSS puro e declarativo, JavaScript também te possibilita definir dinâmicamente valores: de propriedades à duração. Para criar bibilotecas de animação à criar animações interativas, a Web Animations API pode ser a ferramenta perfeita para o trabalho. Vamos ver o que ela pode fazer!

+ +

Suporte de Navegadores

+ +

O suporte básico para as funcionalidades da Web Animations API discutidas neste artigo estão disponíveis no Firefox 48+, Chrome 36+ e Safari 13.1+. Também existe um polyfill prático que verifica o suporte e adiciona as funcionalidades onde for necessário.

+ +

Escrevendo Animações CSS com a Web Animations API

+ +

Uma das maneiras mais familiares de abordar a Web Animations API é começar com algo que boa parte dos desenvolvedores web já utilizaram antes: Animações CSS. Animações CSS tem uma sintaxe familiar que funciona bem para nossa demonstração.

+ +

A versão CSS

+ +

Aqui temos uma animação escrita com CSS mostrando Alice caindo no buraco de coelho que leva ao País das Maravilhas (veja o código completo no Codepen):

+ +

Alice Tumbling down the rabbit's hole.

+ +

Perceba que o fundo se mexe, a Alice gira e sua cor muda em sincronia com o giro. Nós vamos focar somente na Alice para este tutorial. Segue a versão simplificada do CSS que controla a animação da Alice:

+ +
#alice {
+  animation: aliceTumbling infinite 3s linear;
+}
+
+@keyframes aliceTumbling {
+  0% {
+    color: #000;
+    transform: rotate(0) translate3D(-50%, -50%, 0);
+  }
+  30% {
+    color: #431236;
+  }
+  100% {
+    color: #000;
+    transform: rotate(360deg) translate3D(-50%, -50%, 0);
+  }
+}
+ +

Isso muda a cor da Alice e a rotação do `transform` por 3 segundos em um ritmo constante (linear) e se repete infinitamente. No bloco do @keyframes podemos ver que em 30% de cada repetição (por volta dos 900ms), a cor da Alice muda de preto para um vinho, e volta para o preto no final do loop.

+ +

Mudando para o JavaScript

+ +

Agora vamos tentar criar a mesma animação usando a Web Animations API.

+ +

Representando keyframes

+ +

A primeira coisa que precisamos fazer é criar um Objeto Keyframe correspondente ao nosso bloco @keyframes do CSS:

+ +
var aliceTumbling = [
+  { transform: 'rotate(0) translate3D(-50%, -50%, 0)', color: '#000' },
+  { color: '#431236', offset: 0.3},
+  { transform: 'rotate(360deg) translate3D(-50%, -50%, 0)', color: '#000' }
+];
+ +

Aqui estávamos utilizando uma array contendo múltiplos objetos. Cada objeto representa uma chave do CSS original. Contudo, diferente do CSS, a Web Animations API não precisa informar explicitamente as porcentagens temporais para cada chave, o JS automaticamente divide a animação em partes iguais baseado no número de chaves que você forneceu. Isso significa que um objeto Keyframe com três chaves vai reproduzir a chave do meio em 50% do tempo de cada loop, exceto se for definido o contrário.

+ +

Quando queremos explicitamente definir um timing diferente para essas outras chaves, podemos especificar um offset diretamente no objeto, separado do resto da declaração por uma vírgula. No exemplo acima, para definir que a cor da Alice muda em 30% do tempo (e não 50%), nós definiremos como offset: 0.3.

+ +

Atualmente, devem ser definidos pelo menos dois keyframes (representando o início e fim de estado das sequências de animação). Se a sua lista de keyframes somente tem uma entrada, {{domxref("Element.animate()")}} pode disparar uma exceção NotSupportedErro em alguns browsers até eles serem atualizados.

+ +

Então recapitulando: as chaves são espaçadas igualmente por padrão, exceto se você definir um offset para uma chave. Útil, não?

+ +

Representando propriedades temporais

+ +

Nós precisamos criar também um objeto de propriedades temporais (um objeto {{domxref("AnimationEffectTimingProperties")}}) correspondente aos valores da animação da Alice:

+ +
var aliceTiming = {
+  duration: 3000,
+  iterations: Infinity
+}
+ +

Você pode notar algumas diferenças aqui comparando com os valores equivalentes representados no CSS:

+ + + +
+

Existem algumas pequenas diferenças de terminologia entre o CSS Animations e o Web Animations. Por exemplo, Web Animations não usa a string "infinite", e sim a keyword JavaScript Infinity. E no lugar de timing-function, usamos easing. Não estamos citando um valor de easing aqui pois, diferente das Animações CSS onde o valor padrão do animation-timing-function é ease, na Web Animations API o padrão é linear — o que nós já queremos para a animação da Alice.

+
+ +

Juntando as peças

+ +

Agora vamos juntar o que já fizemos com o método {{domxref("Element.animate()")}}:

+ +
document.getElementById("alice").animate(
+  aliceTumbling,
+  aliceTiming
+)
+ +

E pronto: a animação começa a tocar (veja a versão final no Codepen).

+ +

O método animate() pode ser chamado em qualquer elemento do DOM que pode ser animado com CSS. E pode ser escrito de algumas maneiras. Ao invés de criar objetos para os keyframes e propriedades temporais, podemos passar seus valores diretamentes, tipo:

+ +
document.getElementById("alice").animate(
+  [
+    { transform: 'rotate(0) translate3D(-50%, -50%, 0)', color: '#000' },
+    { color: '#431236', offset: 0.3},
+    { transform: 'rotate(360deg) translate3D(-50%, -50%, 0)', color: '#000' }
+  ], {
+    duration: 3000,
+    iterations: Infinity
+  }
+);
+ +

E se nós precisarmos somente especificar a duração da animação e não suas iterações (por padrão, a animação roda uma ), podemos passar só os milisegundos após o array:

+ +
document.getElementById("alice").animate(
+  [
+    { transform: 'rotate(0) translate3D(-50%, -50%, 0)', color: '#000' },
+    { color: '#431236', offset: 0.3},
+    { transform: 'rotate(360deg) translate3D(-50%, -50%, 0)', color: '#000' }
+  ], 3000);
+ +

Controlando a reprodução com play(), pause(), reverse() e updatePlaybackRate()

+ +

Por mais que possamos escrever Animações CSS utilizando a Web Animations API, a API realmente mostra seu potencial quando precisamos manipular a reprodução da animação. A Web Animations API fornece vários métodos úteis para controlar a reprodução. Vamos dar uma olhada em como pausar e tocar animações no jogo da Alice Crescendo/Encolhendo (confira o código completo no Codepen):

+ +

Playing the growing and shrinking game with Alice.

+ +

Nesse jogo, Alice tem uma animação que a encolhe ou aumenta seu tamanho, que controlamos por uma garrafa e um cupcake. Cada um tem sua própria animação.

+ +

Pausando e tocando animações

+ +

Vamos falar sobre a animação da Alice depois, mas por enquanto, vamos dissecar esta animação do cupcake.

+ +
var nommingCake = document.getElementById('eat-me_sprite').animate(
+[
+  { transform: 'translateY(0)' },
+  { transform: 'translateY(-80%)' }
+], {
+  fill: 'forwards',
+  easing: 'steps(4, end)',
+  duration: aliceChange.effect.timing.duration / 2
+});
+ +

O método {{domxref("Element.animate()")}} vai rodar imediatamente depois de ser chamado. Para evitar que o bolinho se coma sozinho antes da interação do usuário, chamamos o {{domxref("Animation.pause()")}} imediatamente depois de criar a animação:

+ +
nommingCake.pause();
+ +

Agora nós podemos usar o método {{domxref("Animation.play()")}} para rodar assim que for o momento:

+ +
nommingCake.play();
+ +

Especificamente, nós queremos linka-lo à animação da Alice, para ela crescer assim que o cupcake é mordido. Podemos fazer isso com a seguinte função:

+ +
var growAlice = function() {
+
+  // Play Alice's animation.
+  aliceChange.play();
+
+  // Play the cake's animation.
+  nommingCake.play();
+
+}
+ +

Quando o usuário clicar ou pressionar seu dedo no bolinho em uma tela de toque, podemos chamar a função growAlice para fazer todas as animações tocarem:

+ +
cake.addEventListener("mousedown", growAlice, false);
+cake.addEventListener("touchstart", growAlice, false);
+ +

Outros métodos úteis

+ + + +

Vamos dar uma olhada primeiro no método playbackRate — um valor negativo vai fazer a animação tocar ao contrário. Quando Alice bebe da garrafa, ela encolhe. Isso porque a garrafa muda o playbackRate da animação de 1 para -1:

+ +
var shrinkAlice = function() {
+  aliceChange.playbackRate = -1;
+  aliceChange.play();
+}
+
+bottle.addEventListener("mousedown", shrinkAlice, false);
+bottle.addEventListener("touchstart", shrinkAlice, false);
+ +

Em Alice Através do Espelho, Alice viaja para um mundo onde ela deve correr para se manter no lugar — e correr com o dobro de velocidade para avançar! No exemplo da Corrida da Rainha Vermelha, Alice e a Rainha Vermelha estão correndo para se manter no lugar (veja o código completo no Codepen):

+ +

Alice and the Red Queen race to get to the next square in this game.

+ +

Já que crianças pequenas se cansam facilmente, diferente de peças de xadrez autônomas, Alice está constantemente desacelerando. Nós podemos fazer isso definindo uma queda no playbackRate da animação dela. Usamos o updatePlaybackRate() no lugar de definir manualmente o playbackRate, já que isso produz uma atualização mais suave:

+ +
setInterval( function() {
+
+  // Make sure the playback rate never falls below .4
+  if (redQueen_alice.playbackRate > .4) {
+    redQueen_alice.updatePlaybackRate(redQueen_alice.playbackRate * .9);
+  }
+
+}, 3000);
+ +

Mas impulsioná-las clicando ou tocando na tela aumenta a velocidade delas por multiplicar o playbackRate:

+ +
var goFaster = function() {
+  redQueen_alice.updatePlaybackRate(redQueen_alice.playbackRate * 1.1);
+}
+
+document.addEventListener("click", goFaster);
+document.addEventListener("touchstart", goFaster);
+ +

Os elementos do fundo também tem playbackRates que também são afetados pelo clique ou toque na tela. O que acontece quando você faz Alice e a Rainha Vermelha correrem com o dobro da velocidade? O que acontece quando você as deixa desacelerar?

+ +

Extraindo informação das animações

+ +

Imagine outras maneiras de utilizar o playbackRate, como melhorar a acessibilidade para usuários com disfunções vestibulares permitindo que eles desacelerem as animações do site todo. Isso é impossível de fazer via CSS sem recalcular todas as regras, mas com a Web Animations API, podemos utilizar o método {{domxref("document.getAnimations()")}} para iterar todas animações de uma página e dividir pela metade seu playbackRate, como por exemplo:

+ +
document.getAnimations().forEach(
+  function (animation) {
+    animation.updatePlaybackRate(animation.playbackRate * .5);
+  }
+);
+ +

Com a Web Animations API, você só precisa mudar uma simples propriedade!

+ +

Outra coisa que é difícil de fazer somente com Animações CSS é criar dependências de valores fornecidos por outras animações. Por exemplo, no logo Aumentando e Encolhendo Alice, você pode ter notado algo estranho sobre a duração do bolinho:

+ +
duration: aliceChange.effect.getComputedTiming().duration / 2
+ +

Para entender o que está acontecendo, vamos dar uma olhada na animação da Alice:

+ +
var aliceChange = document.getElementById('alice').animate(
+  [
+    { transform: 'translate(-50%, -50%) scale(.5)' },
+    { transform: 'translate(-50%, -50%) scale(2)' }
+  ], {
+    duration: 8000,
+    easing: 'ease-in-out',
+    fill: 'both'
+  });
+ +

A animação da Alice a fazia ir de metade de seu tamanho para o dobro em 8 segundos. Então nós a pausamos:

+ +
aliceChange.pause();
+ +

Se pausassemos no início da animação, ela começaria com metade de seu tamanho original, como se já tivesse bebido a garrafa toda! Então nós precisamos definir o estado inicial da animação no meio. Podemos fazer isso definindo o {{domxref("Animation.currentTime")}} para 4 segundos, como no exemplo abaixo:

+ +
aliceChange.currentTime = 4000;
+ +

Mas enquanto trabalhamos nessa animação, vamos mudar bastante a duração da Alice. Não seria melhor definir essa currentTime dinamicamente? Assim não precisariamos fazer duas atualizações de uma vez só. Podemos fazer isso referenciando a propriedade {{domxref("Animation.effect")}}, que retorna um objeto que contém todos os detalhes sobre o(s) efeito(s) ativos na Alice:

+ +
aliceChange.currentTime = aliceChange.effect.getComputedTiming().duration / 2;
+ +

O effect nos permite acessar os keyframes e propriedades temporais da animação — aliceChange.effect.getComputedTiming() aponta para o objeto timing da Alice (cujo tipo é {{domxref("ComputedEffectTiming")}}) — que contem o {{domxref("ComputedEffectTiming.duration")}} dela. Podemos dividir sua duração pela metade para definir a metade da animação para a linha do tempo da animação da Alice, assim ela começaria com o tamanho normal. Então nós podemos reverter e tocar a animação dela em qualquer direção para encolher ou aumentar seu tamanho!

+ +

E nós podemos fazer a mesma coisa quando definimos as durações da garrafa e do bolinho:

+ +
var drinking = document.getElementById('liquid').animate(
+[
+  { height: '100%' },
+  { height: '0' }
+], {
+  fill: 'forwards',
+  duration: aliceChange.effect.getComputedTiming().duration / 2
+});
+drinking.pause();
+ +

Agora todas as três animações estão ligadas por apenas um duration, que pode ser modificado facilmente em um só lugar do código.

+ +

Nós também podemos utilizar a Web Animations API para descobrir o quanto da linha do tempo já foi percorrido. O jogo acaba quando o seu bolinho acaba ou você esvazia a garrafa. A vinheta que é apresentada aos jogadores depende do quão longe a Alice estava em sua animação, seja ficando grande demais pra caber na portinha ou pequena demais pra não conseguir mais alcançar a chave para abrir a porta. Podemos descobrir se ela está nesses extremos pegando o currentTime da sua animação e dividir pelo activeDuration:

+ +
var endGame = function() {
+
+  // get Alice's timeline's playhead location
+  var alicePlayhead = aliceChange.currentTime;
+  var aliceTimeline = aliceChange.effect.getComputedTiming().activeDuration;
+
+  // stops Alice's and other animations
+  stopPlayingAlice();
+
+  // depending on which third it falls into
+  var aliceHeight = alicePlayhead / aliceTimeline;
+
+  if (aliceHeight <= .333){
+    // Alice got smaller!
+    ...
+
+  } else if (aliceHeight >= .666) {
+    // Alice got bigger!
+    ...
+
+  } else {
+    // Alice didn't change significantly
+    ...
+
+  }
+}
+
+ +
+

Nota: getAnimations() e effect não estão disponíveis em todos os browsers no momento em que este artigo foi escrito, mas o polyfill possibilita utilizá-los agora.

+
+ +

Callbacks e promises

+ +

Animações e Transições CSS tem seus event listeners próprios, que também são possíveis com a Web Animations API:

+ + + +

Aqui nós definimos os callbacks para o bolinho, a garrafa e para Alice para disparar a função endGame:

+ +
// When the cake or bottle runs out...
+nommingCake.onfinish = endGame;
+drinking.onfinish = endGame;
+
+// ...or Alice reaches the end of her animation
+aliceChange.onfinish = endGame;
+
+
+ +

Ainda melhor, a Web Animations API também fornece uma promise finished que será resolvida quando a animação é completada, e rejeitada se for cancelada.

+ +

Conclusão

+ +

Essas são as funcionalidades básicas da Web Animations API, a maioria delas já estão sendo suportadas pelas últimas versões do Chrome, Firefox e Safari. Agora você está pronto pra "cair na toca do coelho" de animar utilizando o browser e pronto pra escrever e experimentar com sua própria animação! Se você está utilizando a API e deseja compartilha, tente usar a hashtag #WAAPI. Nós estaremos de olho e vamos escrever mais tutoriais para cobrir funcionalidades futuras assim que o suporte aumentar!

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/web_crypto_api/index.html b/files/pt-br/web/api/web_crypto_api/index.html new file mode 100644 index 0000000000..3058112978 --- /dev/null +++ b/files/pt-br/web/api/web_crypto_api/index.html @@ -0,0 +1,132 @@ +--- +title: Web Crypto API +slug: Web/API/Web_Crypto_API +tags: + - API + - API de criptografia Web + - Overview + - Referencia + - Visão Geral + - Web Crypto API +translation_of: Web/API/Web_Crypto_API +--- +

{{DefaultAPISidebar("Web Crypto API")}}{{SeeCompatTable}}{{draft}}

+ +

A Web Crypto API é uma interface que permite um script utilizar criptografias primitivas para criar sistemas usando criptografia.

+ +

Uma característica fundamental desta API é permitir a manipulação e o armazenamento de keys de criptografia privadas e secretas sem que o JavaScript tenha acesso aos bits internos das keys.

+ +

Essa interface permite que scripts acessem as seguintes primitivas:

+ + + +

A Web Crypto API não resolve todos os problemas de criptografia que um site Web ou aplicação pode encontrar:

+ + + +
+

Atenção!

+ + +
+ +

Interfaces

+ +

Alguns navegadores implementam uma interface chamada {{domxref("Crypto")}} sem que ela esteja bem definida ou seja substancialmente criptografado. Para evitar confusões, métodos e propriedades desta interface foram retiradas de navegadores que implementaram Web Crypto API, e todos os métodos Web Crypto API estão disponíveis em uma nova interface: {{domxref("SubtleCrypto")}}. A propriedade {{domxref("Crypto.subtle")}} dá acesso a um objeto que a implementa.

+ +

Casos de uso

+ +

A Web Crypto API pode ser utilizada:

+ + + +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName("Web Crypto API")}}{{Spec2("Web Crypto API")}}Definição inicial
+ +

 

+ +

 

+ +

Compatibilidade de Browser

+ +

{{CompatibilityTable}}

+ + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico{{CompatChrome(37)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOpera(24)}}{{CompatUnknown}}
+ + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Suporte básico{{CompatNo}}{{CompatChrome(37)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+ +

 

diff --git a/files/pt-br/web/api/web_storage_api_pt_br/index.html b/files/pt-br/web/api/web_storage_api_pt_br/index.html new file mode 100644 index 0000000000..f4e16bd9e7 --- /dev/null +++ b/files/pt-br/web/api/web_storage_api_pt_br/index.html @@ -0,0 +1,139 @@ +--- +title: API de Armazenamento na Web +slug: Web/API/Web_Storage_API_pt_br +translation_of: Web/API/Web_Storage_API +--- +

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

+ +

A  API de armazenamento na web (Web Storage) fornece mecanismos para que os navegadores possam armazenar dados através de chave/valor de uma forma mais eficiente que os cookies.

+ +

Armazenamento na Web conceitos e formas de uso

+ +

A API de Web Storage fornece duas maneiras de armazenar dados:

+ + + +

Esses mecanismos estão disponíveis a partir das seguintes propriedades {{domxref("Window.sessionStorage")}} e {{domxref("Window.localStorage")}} (para um maior suporte, o objeto Window implementa os objetos  Window.LocalStorageWindow.SessionStorage) — ao invocar uma dessas propriedades, é criada uma instância do objeto {{domxref("Storage")}}, que fornece métodos para inserir, recuperar e remover os dados. Sempre será utilizado um objeto diferente para cada origem de sessionStorage e localStorage, dessa forma o controle de ambos é realizado de forma separada.

+ +
+

Nota: O acesso a API de Web storage a partir de IFrames de terceiros é negado se o usuário desabilitou cookies de terceiros (Firefox implementa esse comportamento a partir da versão 43 em diante).

+
+ +
+

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

+
+ +

Interfaces de Armazenamento na Web

+ +
+
{{domxref("Storage")}}
+
Permite que você insira, recupere e remova dados de um domínio no storage(session ou local).
+
{{domxref("Window")}}
+
A API de Web Storage estende o objeto {{domxref("Window")}} com duas novas propriedades — {{domxref("Window.sessionStorage")}} e {{domxref("Window.localStorage")}} —  fornecendo acesso à sessão do domínio atual e local para o objeto {{domxref("Storage")}} respectivamente.
+
{{domxref("StorageEvent")}}
+
+

Um evento de storage é chamado em um objeto window do documento quando ocorre uma mudança no storage.

+
+
+ +

Exemplos

+ +

Para desmonstrar o uso de web storage, nós criamos um exemplo simples, chamado Web Storage Demo. A página da demo landing page oferece funcionalidades que permitem alterar a cor, fonte e imagem que é exibida na página. Quando você escolhe uma opção diferente, a página será atualizada imediatamente. Além disso, sua escolha foi armazenada em localStorage,  para que quando você feche o navegador e abra novamente para acessar a página, suas escolhas sejam lembradas.

+ +

Nós também fornecemos um event output page —  para quando você abrir a página em outra aba,  as informações sejam atualizadas através da chamada de um {{event("StorageEvent")}}.

+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('Web Storage')}}{{Spec2('Web Storage')}}
+ +

Compatibilidade com os Navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropriedadeChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
localStorage43.5810.504
sessionStorage52810.504
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Suporte básico2.1{{ CompatUnknown }}811iOS 3.2
+
+ +

Todos os navegadores têm espaços de armazenamento diferentes tanto para localStorage quanto para sessionStorage. Veja um resumo detalhado da capacidade de armazenamento de vários navegadores.

+ +
+

Nota: Desde iOS 5.1, o Safari armazena dados móveis de LocalStorage na pasta cache, que está sujeito a limpeza pelo OS, além disso o espaço de armazenamento é curto.

+
+ + + +

Boa parte dos navegadores atuais suportam a opção de privacidade chamada modo de "Navegação privada ou anônima", que basicamente torna a sessão de navegação privada e não deixa rastros depois que o navegador é fechado. Este modo é incompatível com armazenamento na Web por razões óbvias. Os fabricantes de navegadores estão experimentando com diferentes cenários como lidar com essa incompatibilidade.

+ +

A maioria dos navegadores optaram por uma estratégia onde as APIs de armazenamento ainda estão disponíveis e, aparentemente, funcional, com a grande diferença de que todos os dados armazenados é apagado depois que o navegador é fechado. Para estes navegadores ainda existem diferentes interpretações sobre o que deve ser feito com os dados existentes armazenados (a partir de uma sessão de navegação regular). E quanto   a leitura dos dados se o navegador estiver no modo privado? Há alguns navegadores, principalmente Safari, que optaram por uma solução em que o armazenamento está disponível, mas está vazio e tem uma quota de 0 bytes atribuídos, tornando impossível o armazenamento de dados.

+ +

Os desenvolvedores devem estar cientes e considerar as diferentes formas de implementações ao desenvolverem sites dependendo das APIs Web Storage. Para mais informações, leia neste post escrito no blog do WHATWG que lida especificamente com este tópico.

+ +

Veja também

+ +

Usando a API Web Storage

diff --git a/files/pt-br/web/api/web_storage_api_pt_br/using_the_web_storage_api/index.html b/files/pt-br/web/api/web_storage_api_pt_br/using_the_web_storage_api/index.html new file mode 100644 index 0000000000..eb9807f0ef --- /dev/null +++ b/files/pt-br/web/api/web_storage_api_pt_br/using_the_web_storage_api/index.html @@ -0,0 +1,267 @@ +--- +title: Usando a API Web Storage +slug: Web/API/Web_Storage_API_pt_br/Using_the_Web_Storage_API +tags: + - API + - Guía + - Storage + - Web Storage API + - localStorage + - sessionStorage +translation_of: Web/API/Web_Storage_API/Using_the_Web_Storage_API +--- +
{{DefaultAPISidebar("Web Storage API")}}
+ +
+

A API Web Storage fornece mecanismos pelos quais os navegadores podem armazenar pares de chaves/valores de uma maneira muito mais segura e intuitiva do que usar cookies. Este artigo fornece um passo a passo sobre como usar essa tecnologia.

+
+ +

Conceitos básicos

+ +

Objetos Storage são simples conjuntos contendo pares de chave/valor, de forma parecida com objetos, porém eles permanecem intactos mesmo após a página ser recarregada. As chaves e valores são sempre strings (note que chaves cujo nome seja um número inteiro serão automaticamente convertidas par strings, assim como acontece nos objetos). Você pode acessar esses valores como você faria com um objeto ou usando os métodos {{domxref("Storage.getItem()")}} e {{domxref("Storage.setItem()")}}. As três linhas seguintes definem o valor de corDefinida de maneiras diferentes, mas com o mesmo resultado:

+ +
localStorage.corDefinida = '#a4509b';
+localStorage['corDefinida'] = '#a4509b';
+localStorage.setItem('corDefinida', '#a4509b');
+ +
+

Nota: Recomendamos que você utilize a API Web Storage (setItemgetItemremoveItemkeylength) para evitar as armadilhas associadas ao uso de objetos literais como mapas de chave-valor.

+
+ +

Os dois mecanismos presentes na Web Storage são os seguintes:

+ + + +

Esses mecanismos estão disponíveis através das propriedades {{domxref("Window.sessionStorage")}} e {{domxref("Window.localStorage")}} (de forma mais específica, em navegadores compatíveis, o objeto Window implementa os objetos WindowLocalStorageWindowSessionStorage, aos quais as propriedades localStorage and sessionStorage pertencem, respectivamente) — invocar uma dessas propriedades irá criar uma instância do objeto {{domxref("Storage")}}, através do qual itens de dados podem ser definidos, acessados e removidos. Cada origem recebe objetos Storage diferentes para sessionStorage and localStorage — eles operam e são controlados separadamente.

+ +

Por exemplo, chamar localStorage pela primeira vez em um documento retornará um objeto {{domxref("Storage")}}; chamar sessionStorage em um documento retornará um outro objeto {{domxref("Storage")}}. Ambos podem ser manipulados da mesma maneira, mas de forma isolada.

+ +

Detectando a disponibilidade do localStorage

+ +

Para poder usarmos o localStorage, devemos antes verificar se ele é compatível e está disponível na sessão atual de navegação.

+ +

Testando a disponibilidade

+ +

Navegadores compatíveis com localStorage terão uma propriedade no objeto window chamada localStorage. Contudo, por várias razões, apenas verificar se essa propriedade existe pode gerar erros. Se ela existir, ainda não haverá garantias de que o localStorage está de fato disponível para uso, já que vários navegadores fornecem opções que desativam o localStorage. Dessa forma, um navegador pode ser compatível com o localStorage, mas também pode não torná-lo disponível para os scripts usarem. One example of that is Safari, which in Private Browsing mode gives us an empty localStorage object with a quota of zero, effectively making it unusable. However, we might still get a legitimate QuotaExceededError, which only means that we've used up all available storage space, but storage is actually available. Our feature detect should take these scenarios into account.

+ +

Here is a function that detects whether localStorage is both supported and available:

+ +
function storageAvailable(type) {
+    try {
+        var storage = window[type],
+            x = '__storage_test__';
+        storage.setItem(x, x);
+        storage.removeItem(x);
+        return true;
+    }
+    catch(e) {
+        return e instanceof DOMException && (
+            // everything except Firefox
+            e.code === 22 ||
+            // Firefox
+            e.code === 1014 ||
+            // test name field too, because code might not be present
+            // everything except Firefox
+            e.name === 'QuotaExceededError' ||
+            // Firefox
+            e.name === 'NS_ERROR_DOM_QUOTA_REACHED') &&
+            // acknowledge QuotaExceededError only if there's something already stored
+            storage.length !== 0;
+    }
+}
+ +

And here is how you would use it:

+ +
if (storageAvailable('localStorage')) {
+  // Yippee! We can use localStorage awesomeness
+}
+else {
+  // Too bad, no localStorage for us
+}
+ +

You can test for sessionStorage instead by calling storageAvailable('sessionStorage').

+ +

See here for a brief history of feature-detecting localStorage.

+ +

Example

+ +

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 color, 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 and load it again, later on, your choices are remembered.

+ +

We have also 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 a {{domxref("StorageEvent")}} is fired.

+ +

+ +
+

Note: As well as viewing the example pages live using the above links, you can also check out the source code.

+
+ +

Testing whether your storage has been populated

+ +

To start with on main.js, we will test whether the storage object has already been populated (i.e., the page was previously accessed):

+ +
if(!localStorage.getItem('bgcolor')) {
+  populateStorage();
+} else {
+  setStyles();
+}
+ +

The {{domxref("Storage.getItem()")}} method is used to get a data item from storage; in this case, we are testing to see whether the bgcolor item exists; if not, we run populateStorage() to add the existing customization values to the storage. If there are already values there, we run setStyles() to update the page styling with the stored values.

+ +

Note: You could also use {{domxref("Storage.length")}} to test whether the storage object is empty or not.

+ +

Getting values from storage

+ +

As noted above, values can be retrieved from storage using {{domxref("Storage.getItem()")}}. This takes the key of the data item as an argument, and returns the data value. For example:

+ +
function setStyles() {
+  var currentColor = localStorage.getItem('bgcolor');
+  var currentFont = localStorage.getItem('font');
+  var currentImage = localStorage.getItem('image');
+
+  document.getElementById('bgcolor').value = currentColor;
+  document.getElementById('font').value = currentFont;
+  document.getElementById('image').value = currentImage;
+
+  htmlElem.style.backgroundColor = '#' + currentColor;
+  pElem.style.fontFamily = currentFont;
+  imgElem.setAttribute('src', currentImage);
+}
+ +

Here, the first three lines grab the values from local storage. Next, we set the values displayed in the form elements to those values, so that they keep in sync when you reload the page. Finally, we update the styles/decorative image on the page, so your customization options come up again on reload.

+ +

Setting values in storage

+ +

{{domxref("Storage.setItem()")}} is used both to create new data items, and (if the data item already exists) update existing values. This takes two arguments — the key of the data item to create/modify, and the value to store in it.

+ +
function populateStorage() {
+  localStorage.setItem('bgcolor', document.getElementById('bgcolor').value);
+  localStorage.setItem('font', document.getElementById('font').value);
+  localStorage.setItem('image', document.getElementById('image').value);
+
+  setStyles();
+}
+ +

The populateStorage() function sets three items in local storage — the background color, font, and image path. It then runs the setStyles() function to update the page styles, etc.

+ +

We've also included an onchange handler on each form element so that the data and styling are updated whenever a form value is changed:

+ +
bgcolorForm.onchange = populateStorage;
+fontForm.onchange = populateStorage;
+imageForm.onchange = populateStorage;
+ +

Responding to storage changes with the StorageEvent

+ +

The {{domxref("StorageEvent")}} is fired whenever a change is made to the {{domxref("Storage")}} object (note that this event is not fired for sessionStorage changes). This won't work on the same page that is making the changes — it is really a way for other pages on the domain using the storage to sync any changes that are made. Pages on other domains can't access the same storage objects.

+ +

On the events page (see events.js) the only JavaScript is as follows:

+ +
window.addEventListener('storage', function(e) {
+  document.querySelector('.my-key').textContent = e.key;
+  document.querySelector('.my-old').textContent = e.oldValue;
+  document.querySelector('.my-new').textContent = e.newValue;
+  document.querySelector('.my-url').textContent = e.url;
+  document.querySelector('.my-storage').textContent = e.storageArea;
+});
+ +

Here we add an event listener to the window object that fires when the {{domxref("Storage")}} object associated with the current origin is changed. As you can see above, the event object associated with this event has a number of properties containing useful information — the key of the data that changed, the old value before the change, the new value after that change, the URL of the document that changed the storage, and the storage object itself.

+ +

Deleting data records

+ +

Web Storage also provides a couple of simple methods to remove data. We don't use these in our demo, but they are very simple to add to your project:

+ + + +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'webstorage.html#webstorage')}}{{Spec2('HTML WHATWG')}} 
+ +

Browser compatibility

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
localStorage43.5810.504
sessionStorage52810.504
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support2.1{{ 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.

+ +
+

Note: since iOS 5.1, Safari Mobile stores localStorage data in the cache folder, which is subject to occasional cleanup, at the behest of the OS, typically if space is short.

+
+ +

See also

+ + diff --git a/files/pt-br/web/api/web_workers_api/index.html b/files/pt-br/web/api/web_workers_api/index.html new file mode 100644 index 0000000000..538a92bd1f --- /dev/null +++ b/files/pt-br/web/api/web_workers_api/index.html @@ -0,0 +1,213 @@ +--- +title: Web Workers API +slug: Web/API/Web_Workers_API +translation_of: Web/API/Web_Workers_API +--- +

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

+ +

Web Workers são mecanismos que permitem que uma operação de um dado script seja executado em uma thread diferente da thread principal da aplicação Web. Permitindo que cálculos laboriosos sejam processados sem que ocorra bloqueio da thread principal (geralmente associado à interface).

+ +

 

+ +

Web Workers: conceitos e uso

+ +

Um "worker" é um objeto criado através da utilização do construtor (ex {{domxref("Worker.Worker", "Worker()")}}) que executa um dado arquivo Javascript —  o código contido em tal arquivo é executado no thread do worker; e tais workers são executados em um contexto diferente do principal {{domxref("window")}}. O contexto dos workers é representado pelo objeto {{domxref("DedicatedWorkerGlobalScope")}} no caso de workers dedicados (workers padrões são utilizados por um único script; workers compartilhados utilizam {{domxref("SharedWorkerGlobalScope")}}).

+ +

O thread do worker roda qualquer trecho de código, mas é importante ressaltar que esse trecho não poderá manipular o DOM, ou usar alguns métodos e propriedades do objeto {{domxref("window")}}. Mas, é permitido usar um grande número de itens fornecidos pelo objeto window, incluindo WebSockets, mecanismos de data storage tais como IndexedDB, Firefox OS-only Data Store API. Para mais detalhes veja Funções e classes disponíveis para os workers.

+ +

O thread principal e os threads dos workers comunicam-se entre si enviando dados através do sistema de mensagens — ambos os lados enviam mensagens usando o método postMessage(), e respondem as mensagens via o manipulador de eventos onmessage (a mensagem está contida no atributo data do evento {{event("Message")}}). É importante ressaltar que os dados são copiados, e não compartilhados.

+ +

Workers podem, por sua vez, gerar novos workers, desde que esses workers sejam hospedados na mesma origem que a página principal. Além disso, workers podem usar XMLHttpRequest para network I/O, com a exceção de que os atributos responseXMLchannel do XMLHttpRequest sempre retornam nulo.

+ +

Além dos workers dedicados, existem outros tipos de workers:

+ + + +

Interfaces Web Worker

+ +
+
{{domxref("AbstractWorker")}}
+
Propriedades Abstratas e métodos comuns a todos tipos de workers (i.e. {{domxref("Worker")}} ou {{domxref("SharedWorker")}}).
+
{{domxref("Worker")}}
+
Representa a worker thread em execução, permitindo que você passe mensagens para o código em execução.
+
{{domxref("SharedWorker")}}
+
Representa um tipo específico de worker que pode ser acessado a partir de vários contextos de navegação, sendo várias janelas, iframes ou mesmo workers.
+
{{domxref("WorkerGlobalScope")}}
+
Representa o escopo genérico de qualquer worker (fazendo o mesmo trabalho como {{domxref("Window")}} para conteúdo normal da web). Diferentes tipos de workers têm objetos de escopo que herdam desta interface e adicionam recursos mais específicos.
+
{{domxref("DedicatedWorkerGlobalScope")}}
+
Representa o escopo de um dedicated worker, herdado de {{domxref("WorkerGlobalScope")}} e adicionam recursos mais específicos.
+
{{domxref("SharedWorkerGlobalScope")}}
+
Representa o escopo de um shared worker, herdado de {{domxref("WorkerGlobalScope")}} e adicionam recursos mais específicos.
+
{{domxref("WorkerNavigator")}}
+
Representa a identidade e estado do user agent (o cliente):
+
+ +

Exemplos

+ +

Criamos algumas demonstrações simples para mostrar o uso básico:

+ + + +

Você pode descobrir mais informações sobre como essas demonstrações funcionam em Usando web workers.

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG', '#toc-workers')}}{{Spec2('HTML WHATWG')}}No change from {{SpecName("Web Workers")}}.
{{SpecName('Web Workers')}}{{Spec2('Web Workers')}}Initial definition.
+ +

Compatibilidade do navegador

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support4{{CompatGeckoDesktop(1.9.1)}}10.010.64
Shared workers4{{CompatGeckoDesktop(29)}}{{CompatNo}}10.64
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 [1]
+ 23
{{CompatGeckoDesktop(21)}}11156 [2]
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome MobileFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support4.44{{CompatGeckoDesktop(1.9.1)}}1.0.110.011.55.1
Shared workers{{CompatNo}}4291.4{{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][2] Como em webkitURL.

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/webgl_api/index.html b/files/pt-br/web/api/webgl_api/index.html new file mode 100644 index 0000000000..97e1e97857 --- /dev/null +++ b/files/pt-br/web/api/webgl_api/index.html @@ -0,0 +1,278 @@ +--- +title: WebGL +slug: Web/API/WebGL_API +tags: + - WebGL +translation_of: Web/API/WebGL_API +--- +
{{WebGLSidebar}}
+ +
+

WebGL (Web Graphics Library) é uma API do JavaScript para renderizar gráficos 3D e 2D dentro de um navegador web compatível sem o uso de plug-ins. O WebGL faz isso introduzindo uma API que está de acordo com o OpenGL ES 2.0 e que pode ser usada em elementos do HTML5 {{HTMLElement("canvas")}}.

+
+ +

O suporte para WebGL está presente no Firefox 4+, Google Chrome 9+, Opera 12+, Safari 5.1+ e Internet Explorer 11+. No entanto, o dispositivo do usuário também deve ter um hardware que suporte esses recursos.

+ +

O elemento {{HTMLElement("canvas")}} é também usado pelo Canvas 2D para renderizar gráficos 2D em páginas web.

+ +

Referências

+ +

Interfaces padrão

+ +
+ +
+ +

Extensões

+ +
+ +
+ +

Eventos

+ + + +

Constantes e tipos

+ + + +

WebGL 2

+ +

O WebGL 2 é uma atualização importante para o WebGL, que é fornecida através da interface {{domxref ("WebGL2RenderingContext")}}. Baseia-se no OpenGL ES 3.0 e os novos recursos incluem:

+ + + +

Veja também os posts WebGL 2 lands in Firefox e webglsamples.org/WebGL2Samples para alguns exemplos de demonstração.

+ +

Guias e tutoriais

+ + + +

Tutoriais avançados

+ + + +

Recursos

+ + + +

Bibliotecas

+ + + +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('WebGL')}}{{Spec2('WebGL')}}Definição inicial. Baseada em OpenGL ES 2.0
{{SpecName('WebGL2')}}{{Spec2('WebGL2')}}Criada com base no WebGL 1. Baseada em 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 em navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
RecursoChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico9{{CompatVersionUnknown}}{{CompatGeckoDesktop("2.0")}}11125.1
WebGL 256{{CompatNo}}{{CompatGeckoDesktop("51")}}{{CompatNo}}43{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
RecursoChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico25{{CompatVersionUnknown}}4{{CompatNo}}128.1
WebGL 2{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Notas sobre compatibilidade

+ +

Além do navegador, a própria GPU também precisa suportar o recurso. Por exemplo, o S3 Texture Compression (S3TC) só está disponível em tablets baseados em Tegra. A maioria dos navegadores disponibiliza o contexto WebGL usando o nome de contexto webgl, mas navegadores antigos também precisam do nome de contexto experimental-webgl. Além disso, o futuro WebGL 2 é totalmente retrocompatível e terá o nome de contexto webgl2.

+ +

Notas sobre o Gecko

+ +

Debugando e testando WebGL

+ +

Iniciando com o Gecko 10.0 {{geckoRelease("10.0")}}, há duas preferências disponíveis que permitem controlar as funcionalidades do WebGL, para efeitos de teste:

+ +
+
webgl.min_capability_mode
+
Uma propriedade booleana que, quando configurada para true, habilita um modo de capacidade mínima. Neste modo, o WebGL é configurado para suportar somente um conjunto básico de recursos e funcionalidades requeridos pela especificação WebGL. Isto garante que o código WebGL funcione em qualquer dispositivo ou navegador, independente de suas funcionalidades. Esta propriedade tem o valor false por padrão.
+
webgl.disable_extensions
+
Uma propriedade booleana que, quando configurada para true, desabilita todas as extensões WebGL. Esta propriedade tem o valor false por padrão.
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/webgl_api/tutorial/adicionando_conteudo_2d_a_um_contexto_webgl/index.html b/files/pt-br/web/api/webgl_api/tutorial/adicionando_conteudo_2d_a_um_contexto_webgl/index.html new file mode 100644 index 0000000000..7b4f6384f6 --- /dev/null +++ b/files/pt-br/web/api/webgl_api/tutorial/adicionando_conteudo_2d_a_um_contexto_webgl/index.html @@ -0,0 +1,226 @@ +--- +title: Adicionando conteúdo 2D a um contexto WebGL +slug: Web/API/WebGL_API/Tutorial/Adicionando_conteudo_2D_a_um_contexto_WebGL +tags: + - Tutorial + - WebGL +translation_of: Web/API/WebGL_API/Tutorial/Adding_2D_content_to_a_WebGL_context +--- +

{{WebGLSidebar("Tutorial")}} {{PreviousNext("Web/API/WebGL_API/Tutorial/Getting_started_with_WebGL", "Web/API/WebGL_API/Tutorial/Using_shaders_to_apply_color_in_WebGL")}}

+ +

Uma vez que você tenha  criado um contexto WebGL com sucesso, você pode iniciar a renderizar nele. O mais simples que podemos fazer é desenhar um objeto 2D não texturizado. Então vamos começar por aí, construindo o código necessário para se desenhar um quadrado.

+ +

Desenhando a cena

+ +

A coisa mais importante para se entender antes de começarmos é que, mesmo que estejamos só renderizando um objeto bidimensional nesse exemplo, nós ainda estamos desenhamos em um espaço 3d. Portanto, ainda precisamos estabelecer os shaders que irão criar a cor para a nossa cena simples, assim como desenhar o objeto. Eles irão estabelecer como o quadrado irá aparecer na tela.

+ +

Inicializando os shaders

+ +

Shaders são especificados ao usar a Linguagem de Shading OpenGL ES. Com o intuito de tornar mais fácil para manter e atualizar nosso conteúdo, nós podemos escrever nosso código que carrega os shaders para buscá-los no documento HTML, ao invés de termos de criar tudo em JavaScript. Vamos dar uma olhada na nossa rotina initShaders(), que cuida dessa tarefa:

+ +
function initShaders() {
+  var fragmentShader = getShader(gl, "shader-fs");
+  var vertexShader = getShader(gl, "shader-vs");
+
+  // Cria o progrma shader
+
+  shaderProgram = gl.createProgram();
+  gl.attachShader(shaderProgram, vertexShader);
+  gl.attachShader(shaderProgram, fragmentShader);
+  gl.linkProgram(shaderProgram);
+
+  // Se falhar ao criar o progrma shader, alerta
+
+  if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
+    alert("Não foi possível inicializar o programa shader.");
+  }
+
+  gl.useProgram(shaderProgram);
+
+  vertexPositionAttribute = gl.getAttribLocation(shaderProgram, "aVertexPosition");
+  gl.enableVertexAttribArray(vertexPositionAttribute);
+}
+
+
+ +

Dois programas estão sendo inicializados por essa rotina; o primeiro, fragment shader, é carregado a partir do elemento HTML com o id "shader-fs". O segundo, vertex shader, é carregado pelo elemento HTML com o id "shader-vs". Nós vamos analisar a função getShader() no próximo tutorial; Essa rotina, na verdade, lida com a parte de puxar os programas shader da DOM.

+ +

Então nós criamos o programa shader chamando do objeto WebGL a função createProgram(), anexamos dois shaders nele e fazemos o link com o programa shader. Depois de fazer isso, o parametro LINK_STATUS do objeto g1 é checado para ter certeza de que o link foi criado com sucesso; Se sim, nós ativamos o novo programa shader.

+ +

Carregando os shaders da DOM

+ +

A rotina getShader() busca um programa shader com o nome específico do DOM, retornando o programa shader compilado para o requisitante, ou null se ele não pode ser carregado ou compilado.

+ +
function getShader(gl, id) {
+  var shaderScript, theSource, currentChild, shader;
+
+  shaderScript = document.getElementById(id);
+
+  if (!shaderScript) {
+    return null;
+  }
+
+  theSource = "";
+  currentChild = shaderScript.firstChild;
+
+  while(currentChild) {
+    if (currentChild.nodeType == currentChild.TEXT_NODE) {
+      theSource += currentChild.textContent;
+    }
+
+    currentChild = currentChild.nextSibling;
+  }
+
+ +

Uma vez que o elemento com o ID específico é encontrado, seu texto é lido na variável theSource.

+ +
  if (shaderScript.type == "x-shader/x-fragment") {
+    shader = gl.createShader(gl.FRAGMENT_SHADER);
+  } else if (shaderScript.type == "x-shader/x-vertex") {
+    shader = gl.createShader(gl.VERTEX_SHADER);
+  } else {
+     // Tipo de shader desconhecido
+     return null;
+  }
+ +

Uma vez que o código para o shader tenha sido lido, nós observamos o tipo MIME do objeto shader para determinar se é um sombreamento de vértice (MIME type "x-shader/x-vertex") ou um fragmento de shader (MIME type "x-shader/x-fragment"), em seguinda crie um tipo de shader apropriado para a partir do código fonte recuperado.

+ +
  gl.shaderSource(shader, theSource);
+
+  // Compile o programa shader
+  gl.compileShader(shader);
+
+  // Veja se ele compila com sucesso
+  if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
+      alert("Um erro ocorreu ao compilar os shaders: " + gl.getShaderInfoLog(shader));
+      return null;
+  }
+
+  return shader;
+}
+
+ +

Finalmente, a fonte é passada para o shader e compilada. Se um erro ocorrer enquanto o shader estiver compilando, nós mostraremos um alerta e retornaremos null; Caso contrário, o shader recém compilado é retornado para o requisitante.

+ +

Os shaders

+ +

Agora, nós precisamos adicionar os programas shaders ao HTML para descrever nosso documento. Os detalhes sobre como os shaders trabalham estão além do escopo deste artigo, assim como a sintaxe da linguagem do shader.

+ +

Fragmentos shader

+ +

Cada pixel é um poligono chamado de fragmento (fragment) na linguagem GL. O trabalho do fragmento de shader é estabelecer a cor de cada pixel. Ness caso, nós estamos apenas definindo a cor branca para cada pixel.

+ +

g1_FragColor é um construtor de variável GL que é utilizado para a cor do fragmento. Altere seu valor para definir a cor do pixel, como mostrado abaixo.

+ +
<script id="shader-fs" type="x-shader/x-fragment">
+  void main(void) {
+    gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);
+  }
+</script>
+
+ +

Vértice do shader

+ +

A vértice (vertex) do shader define a posição e a forma de cada vértice.

+ +
<script id="shader-vs" type="x-shader/x-vertex">
+  attribute vec3 aVertexPosition;
+
+  uniform mat4 uMVMatrix;
+  uniform mat4 uPMatrix;
+
+  void main(void) {
+    gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);
+  }
+</script>
+
+ +

Criando um objeto

+ +

Before we can render our square, we need to create the buffer that contains its vertices. We'll do that using a function we call initBuffers(); as we explore more advanced WebGL concepts, this routine will be augmented to create more -- and more complex -- 3D objects.

+ +
var horizAspect = 480.0/640.0;
+
+function initBuffers() {
+  squareVerticesBuffer = gl.createBuffer();
+  gl.bindBuffer(gl.ARRAY_BUFFER, squareVerticesBuffer);
+
+  var vertices = [
+    1.0,  1.0,  0.0,
+    -1.0, 1.0,  0.0,
+    1.0,  -1.0, 0.0,
+    -1.0, -1.0, 0.0
+  ];
+
+  gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
+}
+
+ +

This routine is pretty simplistic given the basic nature of the scene in this example. It starts by calling the gl object's createBuffer() method to obtain a buffer into which we'll store the vertices. This is then bound to the context by calling the bindBuffer() method.

+ +

Once that's done, we create a JavaScript array containing the coordinates for each vertex of the square. This is then converted into an array of WebGL floats and passed into the gl object's bufferData() method to establish the vertices for the object.

+ +

Desenhando a cena

+ +

Once the shaders are established and the object constructed, we can actually render the scene. Since we're not animating anything in this example, our drawScene() function is very simple. It uses a few utility routines we'll cover shortly.

+ +
function drawScene() {
+  gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
+
+  perspectiveMatrix = makePerspective(45, 640.0/480.0, 0.1, 100.0);
+
+  loadIdentity();
+  mvTranslate([-0.0, 0.0, -6.0]);
+
+  gl.bindBuffer(gl.ARRAY_BUFFER, squareVerticesBuffer);
+  gl.vertexAttribPointer(vertexPositionAttribute, 3, gl.FLOAT, false, 0, 0);
+  setMatrixUniforms();
+  gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
+}
+
+ +

The first step is to clear the context to our background color; then we establish the camera's perspective. We set a field of view of 45°, with a width to height ratio of 640/480 (the dimensions of our canvas). We also specify that we only want objects between 0.1 and 100 units from the camera to be rendered.

+ +

Then we establish the position of the square by loading the identity position and translating away from the camera by 6 units. After that, we bind the square's vertex buffer to the context, configure it, and draw the object by calling the drawArrays() method.

+ +

{{EmbedGHLiveSample('webgl-examples/tutorial/sample2/index.html', 670, 510) }}

+ +

View the complete code | Open this demo on a new page

+ +

Operações úteis da Matrix

+ +

Matrix operations are complicated enough. Nobody really wants to write all the code needed to handle them on their own. Fortunately, there's Sylvester, a very handy library for handling vector and matrix operations from JavaScript.

+ +

The glUtils.js file used by this demo is used by a number of WebGL demos floating around on the Web. Nobody seems entirely clear on where it came from, but it does simplify the use of Sylvester even further by adding methods for building special types of matrices, as well as outputting HTML for displaying them.

+ +

In addition, this demo defines a few helpful routines to interface with these libraries for specific tasks. What exactly they do is beyond the scope of this demo, but there are plenty of good references on matrices available online; see the {{ anch("See also") }} section for a list of a few.

+ +
function loadIdentity() {
+  mvMatrix = Matrix.I(4);
+}
+
+function multMatrix(m) {
+  mvMatrix = mvMatrix.x(m);
+}
+
+function mvTranslate(v) {
+  multMatrix(Matrix.Translation($V([v[0], v[1], v[2]])).ensure4x4());
+}
+
+function setMatrixUniforms() {
+  var pUniform = gl.getUniformLocation(shaderProgram, "uPMatrix");
+  gl.uniformMatrix4fv(pUniform, false, new Float32Array(perspectiveMatrix.flatten()));
+
+  var mvUniform = gl.getUniformLocation(shaderProgram, "uMVMatrix");
+  gl.uniformMatrix4fv(mvUniform, false, new Float32Array(mvMatrix.flatten()));
+}
+
+ +

Ver Também

+ + + +

{{PreviousNext("Web/API/WebGL_API/Tutorial/Getting_started_with_WebGL", "Web/API/WebGL_API/Tutorial/Using_shaders_to_apply_color_in_WebGL")}}

diff --git a/files/pt-br/web/api/webgl_api/tutorial/getting_started_with_webgl/index.html b/files/pt-br/web/api/webgl_api/tutorial/getting_started_with_webgl/index.html new file mode 100644 index 0000000000..4abbd5e304 --- /dev/null +++ b/files/pt-br/web/api/webgl_api/tutorial/getting_started_with_webgl/index.html @@ -0,0 +1,71 @@ +--- +title: Começando com WebGL +slug: Web/API/WebGL_API/Tutorial/Getting_started_with_WebGL +translation_of: Web/API/WebGL_API/Tutorial/Getting_started_with_WebGL +--- +

{{WebGLSidebar("Tutorial")}} {{Next("Web/API/WebGL_API/Tutorial/Adding_2D_content_to_a_WebGL_context")}}

+ +

WebGL permite que o contéudo web use uma API baseada em OpenGL ES 2.0 para realizar renderização 3D em um canvas HTML em browsers que o suportam sem o uso de plugins. Programas WebGL consistem em um código de controle escrito em JavaScript e códigos de efeitos especiais (shader code) que é executado na Unidade Gráfica de Processamento (GPU) de um computador. Elementos WebGL podem ser utilizados junto com outros elementos HTML e com outras partes da página ou do fundo.

+ +

Esse artigo vai introduzir o básico sobre o uso do WebGL. Acredita-se que você já possui entendimento da matemática que envolve os gráficos 3D, e que este artigo não tem a pretensão de tentar ensinar-lhe OpenGL em si.

+ +

Os exemplos de código deste tutorial também podem ser encontrados no Exemplos de WebGL no repositório do GitHub.

+ +

Preparando-se para renderizar em 3D

+ +

A primeira coisa que você precisa para para renderização do WebGL, é a inicialização do canvas. O fragmento HTML abaixo declara um canvas em que nosso exemplo será desenhado.

+ +
<body>
+  <canvas id="glCanvas" width="640" height="480"></canvas>
+</body>
+
+ +

Preparando o contexto WebGL

+ +

A função main() em nosso código JavaScript é chamada quando nosso script é carregado. O objetivo é configurar o contexto do WebGL e começar a renderizar o conteúdo.

+ +
main();
+
+//
+// começa aqui
+//
+function main() {
+  const canvas = document.querySelector("#glCanvas");
+  // Inicializa o contexto GL
+  const gl = canvas.getContext("webgl");
+
+  // Só continua se o WebGL estiver disponível e funcionando
+  if (!gl) {
+    alert("Incapaz de inicializar o WebGL.Seu navegador ou sua máquina não suporta.");
+    return;
+  }
+
+  // Define a cor para preto totalmente opaca (sem transparência)
+  gl.clearColor(0.0, 0.0, 0.0, 1.0);
+  // Limpa o buffer de cores com uma cor específica
+  gl.clear(gl.COLOR_BUFFER_BIT);
+}
+
+
+ +

A primeira coisa que nós fazemos aqui é obter a referência para o canvas, atribuindo-a para a variável chamada canvas.

+ +

Uma vez que nós temos o canvas, nós tentamos obter um WebGLRenderingContext para ele chamando o getContext e passando a string "webgl". Se o browser não suportar o webgl getContext vai retornar null nesse caso nós mostraremos uma mensagem para o usuário e sair.

+ +

Se o contexto for inicializado com sucesso, a variável gl é nossa referência para ele. Nesse caso, nós altermos a cor para preto, e o contexto para aquela cor (redesenhando o canvas com a cor de fundo).

+ +

Nesse ponto, você tem código suficiente para o contexto WebGL ser inicializado com sucesso, e você deve visualizar uma grande caixa preta vazia, pronta e esperando para receber conteúdo.

+ +

{{EmbedGHLiveSample('webgl-examples/tutorial/sample1/index.html', 670, 510) }}

+ +

Veja o código completo | Abra a demo em uma nova página

+ +

Veja também

+ + + +

{{Next("Web/API/WebGL_API/Tutorial/Adding_2D_content_to_a_WebGL_context")}}

diff --git a/files/pt-br/web/api/webgl_api/tutorial/index.html b/files/pt-br/web/api/webgl_api/tutorial/index.html new file mode 100644 index 0000000000..4fa7ba76cf --- /dev/null +++ b/files/pt-br/web/api/webgl_api/tutorial/index.html @@ -0,0 +1,39 @@ +--- +title: WebGL tutorial +slug: Web/API/WebGL_API/Tutorial +tags: + - WebGL +translation_of: Web/API/WebGL_API/Tutorial +--- +
{{WebGLSidebar}}
+ +
+

WebGL enables web content to use an API based on OpenGL ES 2.0 to perform 3D rendering in an HTML {{HTMLElement("canvas")}} in browsers that support it without the use of plug-ins. WebGL programs consist of control code written in JavaScript and special effects code(shader code) that is executed on a computer's Graphics Processing Unit (GPU). WebGL elements can be mixed with other HTML elements and composited with other parts of the page or page background.

+
+ +

This tutorial describes how to use the <canvas> element to draw WebGL graphics, starting with the basics. The examples provided should give you some clear ideas what you can do with WebGL and will provide code snippets that may get you started in building your own content.

+ +

Before you start

+ +

Using the <canvas> element is not very difficult, but you do need a basic understanding of HTML and JavaScript. The <canvas> element and WebGL are not supported in some older browsers, but are supported in recent versions of all major browsers. In order to draw graphics on the canvas we use a JavaScript context object, which creates graphics on the fly.

+ +

In this tutorial

+ +
+
Getting started with WebGL
+
How to set up a WebGL context.
+
Adding 2D content to a WebGL context
+
How to render simple flat shapes using WebGL.
+
Using shaders to apply color in WebGL
+
Demonstrates how to add color to shapes using shaders.
+
Animating objects with WebGL
+
Shows how to rotate and translate objects to create simple animations.
+
Creating 3D objects using WebGL
+
Shows how to create and animate a 3D object (in this case, a cube).
+
Using textures in WebGL
+
Demonstrates how to map textures onto the faces of an object.
+
Lighting in WebGL
+
How to simulate lighting effects in your WebGL context.
+
Animating textures in WebGL
+
Shows how to animate textures; in this case, by mapping an Ogg video onto the faces of a rotating cube.
+
diff --git a/files/pt-br/web/api/webrtc_api/index.html b/files/pt-br/web/api/webrtc_api/index.html new file mode 100644 index 0000000000..f4a91242e3 --- /dev/null +++ b/files/pt-br/web/api/webrtc_api/index.html @@ -0,0 +1,197 @@ +--- +title: WebRTC API +slug: Web/API/WebRTC_API +tags: + - API + - Audio + - Landing + - Media + - NeedsTranslation + - Networking + - TopicStub + - Video + - WebRTC + - WebRTC API + - streaming +translation_of: Web/API/WebRTC_API +--- +
{{APIRef("WebRTC")}}
+ +

WebRTC (Web Real-Time Communications) é uma tecnologia que permite aplicativos e sites da Web a capturarem e opcionalmente transmitirem mídia de áudio e/ou vídeo, assim como trocar informação arbitrária entre navegadores sem a necessidade de um intermediador. O conjunto de padrões que abrangem WebRTC possibilita o compartilhamento de informação e a realização de teleconferência peer-to-peer, dispensando a instalação de plug-ins ou quaisquer softwares de terceiros.

+ +

WebRTC consiste em diversas APIs e protocolos interrelacionados que trabalham juntos. A documentação que você encontrará aqui o ajudará a entender os fundamentos de WebRTC, como configurar e usar, tanto informação, quanto conexões de mídia e mais. 

+ +

WebRTC conceitos e uso

+ +

WebRTC serve à diversas propostas, e sobrepõe-se substancialmente com a API de Captura e Transmissão. Juntas, provém capacidades poderosas de multimídia para a Web, incluíndo suporte para conferência em áudio e vídeo, troca de arquivos, administração de identidade, e lidando com sistemas telefônicos legados enviando sinais {{Glossary("DTMF")}}.

+ +

Conexões entre dois peers são criadas usando—e representadas por—uma interface {{DOMxRef("RTCPeerConnection")}}. Uma vez que a conexão tenha sido estabilizada e iniciada, media streams ({{DOMxRef("MediaStream")}}s) (transmissões de mídia) e/ou data channels ({{DOMxRef("RTCDataChannel")}}s) (canais de dados) podem ser adicionados à conexão.

+ +

Dados de mídia podem consistir em qualquer número de tracks(faixas) de dados de mídia; tracks, que são representados por objetos baseados na interface {{DOMxRef("MediaStreamTrack")}} , que podem conter um número dentre tipos de dados de mídia, incluíndo áudio, vídeo e texto (como legendas ou até mesmo nomes de capítulos). A maioria das transmissões consiste de ao menos uma faixa de áudio e comumente também uma faixa de vídeo, e podem ser usadas para enviar e receber ambas as mídias ao vivo ou dados salvos de mídia (como um filme transmitido).

+ +

Você também pode usar a conexão entre dois peers para trocar dados arbitrários binários usando a interface {{DOMxRef("RTCDataChannel")}}. Isto pode ser usado para informação de back-channel (canal de volta), troca de metadata, pacotes de status de games, transferência de arquivos, ou até mesmo como um canal primário para transferir dados.

+ +

são necessários mais detalhes e links e tutoriais relevantes

+ +

WebRTC interfaces

+ +

Porque WebRTC provê interfaces que trabalham em conjunto para realizar uma variedade de tarefas, nós dividimos as interfaces na listagem abaixo por categoria. Por favor, atente-se a sidebar para uma listagem em ordem alfabética.

+ +

Conexão, configuração e gerenciamento

+ +

Estas interfaces são usadas para configurar, abrir e gerenciar conexões WebRTC.

+ +
+
{{domxref("RTCPeerConnection")}}
+
Representa a conexão WebRTC entre o computador local e um peer remoto. É usado para lidar com um streaming eficiente de dados entre os dois peers.
+
{{domxref("RTCDataChannel")}}
+
Representa um canal de dados bidirecional entre dois peers de uma conexão
+
{{domxref("RTCDataChannelEvent")}}
+
Represents events that occur while attaching a {{domxref("RTCDataChannel")}} to a {{domxref("RTCPeerConnection")}}. The only event sent with this interface is {{event("datachannel")}}.
+
{{domxref("RTCSessionDescription")}}
+
Represents the parameters of a session. Each RTCSessionDescription consists of a description type indicating which part of the offer/answer negotiation process it describes and of the SDP descriptor of the session.
+
{{domxref("RTCStatsReport")}}
+
Provides information detailing statistics for a connection or for an individual track on the connection; the report can be obtained by calling {{domxref("RTCPeerConnection.getStats()")}}.
+
{{domxref("RTCIceCandidate")}}
+
Represents a candidate internet connectivity establishment (ICE) server for establishing an {{domxref("RTCPeerConnection")}}.
+
{{domxref("RTCIceTransport")}}
+
Represents information about an internet connectivity establishment (ICE) transport.
+
{{domxref("RTCPeerConnectionIceEvent")}}
+
Represents events that occurs in relation to ICE candidates with the target, usually an {{domxref("RTCPeerConnection")}}. Only one event is of this type: {{event("icecandidate")}}.
+
{{domxref("RTCRtpSender")}}
+
Manages the encoding and transmission of data for a {{domxref("MediaStreamTrack")}} on an {{domxref("RTCPeerConnection")}}.
+
{{domxref("RTCRtpReceiver")}}
+
Manages the reception and decoding of data for a {{domxref("MediaStreamTrack")}} on an {{domxref("RTCPeerConnection")}}.
+
{{domxref("RTCTrackEvent")}}
+
Indicates that a new incoming {{domxref("MediaStreamTrack")}} was created and an associated {{domxref("RTCRtpReceiver")}} object was added to the {{domxref("RTCPeerConnection")}} object.
+
+ +

Identity and security

+ +

The WebRTC API includes a number of interfaces to manage security and identity.

+ +
+
{{domxref("RTCIdentityProvider")}}
+
Enables a user agent is able to request that an identity assertion be generated or validated.
+
{{domxref("RTCIdentityAssertion")}}
+
Represents the identity of the a remote peer of the current connection. If no peer has yet been set and verified this interface returns null. Once set it can't be changed.
+
{{domxref("RTCIdentityProviderRegistrar")}}
+
Registers an  identity provider (idP).
+
{{domxref("RTCIdentityEvent")}}
+
Represents an identity assertion generated by an identity provider (idP). This is usually for an {{domxref("RTCPeerConnection")}}. The only event sent with this type is {{event("identityresult")}}.
+
{{domxref("RTCIdentityErrorEvent")}}
+
Represents an error associated with the identity provider (idP). This is usually for an {{domxref("RTCPeerConnection")}}. Two events are sent with this type: {{event("idpassertionerror")}} and {{event("idpvalidationerror")}}.
+
{{domxref("RTCCertificate")}}
+
Represents a certificate that an {{domxref("RTCPeerConnection")}} uses to authenticate.
+
+ +

Telephony

+ +

These interfaces are related to interactivity with public-switched telephone networks (PTSNs).

+ +
+
{{domxref("RTCDTMFSender")}}
+
Manages the encoding and transmission of dual-tone multi-frequency (DTMF) signaling for an {{domxref("RTCPeerConnection")}}.
+
{{domxref("RTCDTMFToneChangeEvent")}}
+
Indicates an occurrence of a of dual-tone multi-frequency (DTMF). This event does not bubble (except where otherwise stated) and is not cancelable (except where otherwise stated).
+
+ +

Guides

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

Tutorials

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

Resources

+ +

Protocols

+ +

WebRTC-proper protocols

+ + + + + + + +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebRTC 1.0')}}{{Spec2('WebRTC 1.0')}}The initial definition of the API of WebRTC.
{{SpecName('Media Capture')}}{{Spec2('Media Capture')}}The initial definition of the object conveying the stream of media content.
{{SpecName('Media Capture DOM Elements')}}{{Spec2('Media Capture DOM Elements')}}The initial definition on how to obtain stream of content from DOM Elements
+ +

In additions to these specifications defining the API needed to use WebRTC, there are several protocols, listed under resources.

+ + + + diff --git a/files/pt-br/web/api/webrtc_api/protocols/index.html b/files/pt-br/web/api/webrtc_api/protocols/index.html new file mode 100644 index 0000000000..973a160ca7 --- /dev/null +++ b/files/pt-br/web/api/webrtc_api/protocols/index.html @@ -0,0 +1,70 @@ +--- +title: Introdução aos protocolos WebRTC +slug: Web/API/WebRTC_API/Protocols +tags: + - API + - Audio + - Guía + - ICE + - Iniciante + - Media + - NAT + - Projeto + - SDP + - STUN + - TURN + - Video + - WebRTC + - WebRTC API +translation_of: Web/API/WebRTC_API/Protocols +--- +
{{WebRTCSidebar}}{{draft}}
+ +

Este artigo apresenta os protocolos sobre os quais a API WebRTC é construída.

+ +

ICE

+ +

Interactive Connectivity Establishment (ICE) é a estrutura que permite seu navegador web se conectar com outras pessoas. Existem muitas razões pelas quais uma conexão direta do Ponto A para o Ponto B simplesmente não funciona. Ele precisa ignorar firewalls que impediriam a abertura de conexões, fornecer um endereço exclusivo, como na maioria das situações, caso seu dispositivo não tiver um endereço IP público e retransmitir dados por meio de um servidor ou se seu roteador não permitir a conexão direta com seus pares . O ICE usa servidores STUN e / ou TURN para fazer isso, conforme descrito abaixo.

+ +

STUN

+ +

Session Traversal Utilities for NAT (STUN) (sigla dentro de uma sigla) é um protocolo para descobrir seu endereço público e determinar quaisquer restrições em seu roteador que poderiam impedir uma conexão direta com um par.

+ +

O cliente enviará uma solicitação a um servidor STUN na Internet que responderá com o endereço público do cliente e se o cliente está ou não acessível por meio do NAT do roteador.

+ +

An interaction between two users of a WebRTC application involving a STUN server.

+ +

NAT

+ +

Network Address Translation (NAT) é usado para dar ao seu dispositivo um endereço IP público. Um roteador terá um endereço IP público e cada dispositivo conectado ao roteador terá um endereço IP privado. As solicitações serão traduzidas do IP privado do dispositivo para o IP público do roteador com uma porta exclusiva. Dessa forma, você não precisa de um IP público exclusivo para cada dispositivo, mas ainda pode ser descoberto na Internet.

+ +

Alguns roteadores terão restrições sobre quem pode se conectar a dispositivos na rede. Isso pode significar que, embora tenhamos o endereço IP público encontrado pelo servidor STUN, ninguém pode criar uma conexão. Nesta situação, precisamos voltar para TURN.

+ +

TURN

+ +

Alguns roteadores que usam NAT empregam uma restrição chamada ‘Symmetric NAT’ (NAT simétrico). Isso significa que o roteador só aceitará conexões de pares aos quais você já se conectou.

+ +

Traversal Using Relays around NAT (TURN) destina-se a contornar a restrição de NAT simétrico abrindo uma conexão com um servidor TURN para que ele re-transmita toda informação. Você criaria uma conexão com um servidor TURN e avisaria a todos os pares (peers) para enviar pacotes para este servidor, que lhe encaminharia. Isso obviamente vem com alguma sobrecarga, então só é usado se não houver outras alternativas.

+ +

An interaction between two users of a WebRTC application involving STUN and TURN servers.

+ +

SDP

+ +

Session Description Protocol (SDP) é um padrão para descrever o conteúdo multimídia da conexão, como resolução, formatos, codecs, criptografia, etc., para que os dois pontos possam se entender uma vez que os dados estejam sendo transferidos. Em essência, são os metadados que descrevem o conteúdo e não o conteúdo da mídia em si.

+ +

Tecnicamente, então, SDP não é realmente um protocolo, mas um formato de dados usado para descrever a conexão que compartilha mídia entre dispositivos.

+ +

A documentação do SDP está bem fora do escopo desta documentação; no entanto, existem algumas coisas que vale a pena observar aqui.

+ +

Estrutura

+ +

O SDP consiste em uma ou mais linhas de texto UTF-8, cada uma começando com um tipo de um caractere, seguido por um sinal de igual ("="), seguido por um texto estruturado contendo um valor ou descrição, cujo formato depende do tipo. As linhas de texto que começam com uma determinada letra são geralmente chamadas de "letter-lines" ("linhas de letras"). Por exemplo, as linhas que fornecem descrições de mídia têm o tipo "m", portanto, essas linhas são chamadas de "linhas m".

+ +

Para mais informações

+ +

Para saber mais sobre o SDP, consulte os seguintes recursos úteis:

+ + diff --git a/files/pt-br/web/api/webrtc_api/simples_rtcdatachannel_amostra/index.html b/files/pt-br/web/api/webrtc_api/simples_rtcdatachannel_amostra/index.html new file mode 100644 index 0000000000..72ac37e56a --- /dev/null +++ b/files/pt-br/web/api/webrtc_api/simples_rtcdatachannel_amostra/index.html @@ -0,0 +1,272 @@ +--- +title: Uma simples amostra de RTCDataChannel +slug: Web/API/WebRTC_API/Simples_RTCDataChannel_amostra +translation_of: Web/API/WebRTC_API/Simple_RTCDataChannel_sample +--- +

{{WebRTCSidebar}}

+ +

A interface {{domxref("RTCDataChannel")}} é um recurso da WebRTC API que permite abrir um canal entre dois pares sobre os quais você pode enviar e receber dados arbitrários. A API é intencionalmente semelhante à WebSocket API, de modo que o mesmo modelo de programação pode ser usado para ambos.

+ +

Neste exemplo, abriremos um {{domxref("RTCDataChannel")}} para realizar a conexão entre dois elementos na mesma página. Embora seja obviamente um cenário artificial, é útil para demonstrar o fluxo de conexão entre dois pares. Vamos cobrir a mecânica necessária para conectar, transmitir e receber dados, mas vamos deixar para outro exemplo os detalhes sobre como localizar e se conectar a um computador remoto.

+ +

O HTML

+ +

Primeiro, vamos dar uma olhada rápida no HTML que é necessário. Não há nada incrivelmente complicado aqui. Primeiro, temos um par de botões para estabelecer e fechar a conexão:

+ +
<button id="connectButton" name="connectButton" class="buttonleft">
+  Conectar
+</button>
+<button id="disconnectButton" name="disconnectButton" class="buttonright" disabled>
+  Desconectar
+</button>
+ +

Depois, há uma caixa que contém o campo de input no qual o usuário pode digitar uma mensagem para transmitir, com um botão para enviar o texto digitado. Este {{HTMLElement("div")}} será o primeiro ponto (peer) no canal.

+ +
  <div class="messagebox">
+    <label for="message">Insira a mensagem:
+      <input type="text" name="message" id="message" placeholder="Texto da mensagem"
+              inputmode="latin" size=60 maxlength=120 disabled>
+    </label>
+    <button id="sendButton" name="sendButton" class="buttonright" disabled>
+      Enviar
+    </button>
+  </div>
+ +

Finalmente, há uma pequena caixa na qual vamos inserir as mensagens. Este bloco {{HTMLElement("div")}} será o segundo ponto do par (peer).

+ +
<div class="messagebox" id="receivebox">
+  <p>Mensagens recebidas:</p>
+</div>
+ +

O código JavaScript

+ +

Como você pode simplesmente ver o próprio código no GitHub, abaixo, analisaremos as partes do código que fazem o trabalho pesado.

+ +

A WebRTC API faz um intenso uso de {{jsxref("Promise")}}s. Que tornam muito fácil encadear as etapas do processo de conexão; Se você ainda não leu sobre esta funcionalidade do ECMAScript 2015, você deveria ler sobre eles. Da mesma forma, este exemplo usa arrow functions para simplificar a sintaxe.

+ +

Começando

+ +

Quando o script é executado, configuramos um {{event("load")}} ouvinte de eventos (event listener), De modo que, uma vez que a página esteja totalmente carregada, nossa função startup() seja chamada.

+ +
function startup() {
+  connectButton = document.getElementById('connectButton');
+  disconnectButton = document.getElementById('disconnectButton');
+  sendButton = document.getElementById('sendButton');
+  messageInputBox = document.getElementById('message');
+  receiveBox = document.getElementById('receivebox');
+
+  // Define os ouvintes de eventos para os elementos da interface do usuário
+
+  connectButton.addEventListener('click', connectPeers, false);
+  disconnectButton.addEventListener('click', disconnectPeers, false);
+  sendButton.addEventListener('click', sendMessage, false);
+}
+ +

Isso é bastante direto. Pegamos referências de todos os elementos da página que precisaremos acessar e, em seguida, configuramos {{domxref("EventListener", "event listeners")}} nos três botões.

+ +

Estabelecendo uma conexão

+ +

Quando o usuário clica no botão "Conectar", o método connectPeers() é chamado. Para que fique mais claro, iremos quebrar o código em mais partes, e analisar um pouco de cada vez.

+ +
+

Nota: Mesmo que ambas as extremidades da nossa conexão estejam na mesma página, vamos nos referir ao ponto que inicia a conexão como "local", e ao outro como sendo o "remoto".

+
+ +

Configurando o ponto local (local peer)

+ +
localConnection = new RTCPeerConnection();
+
+sendChannel = localConnection.createDataChannel("sendChannel");
+sendChannel.onopen = handleSendChannelStatusChange;
+sendChannel.onclose = handleSendChannelStatusChange;
+
+ +

O primeiro passo é criar o ponto "local" da conexão. Este é o ponto que enviará o pedido de conexão. O próximo passo é criar o {{domxref("RTCDataChannel")}} chamando {{domxref("RTCPeerConnection.createDataChannel()")}} e configurando ouvintes de eventos (event listeners) para monitorar o canal, e para que possamos saber quando ele for aberto e fechado (isto é, quando o canal está conectado ou desconectado dentro dessa conexão entre pares (peer connection)).

+ +

É importante ter em mente que cada extremidade do canal tem seu próprio objeto {{domxref("RTCDataChannel")}} .

+ +

Configurando o ponto remoto (remote peer)

+ +
remoteConnection = new RTCPeerConnection();
+remoteConnection.ondatachannel = receiveChannelCallback;
+ +

O ponto remoto está configurado de forma semelhante, exceto que não precisamos nós mesmos criar explicitamente um {{domxref("RTCDataChannel")}} , uma vez que vamos ser conectados através do canal estabelecido acima. Em vez disso, criamos um {{event("datachannel")}} manipulador de eventos (event handler); Isso será chamado quando o canal de dados (data channel) for aberto; Este manipulador (handler) receberá um objeto RTCDataChannel; você verá isso abaixo.

+ +

Configurando  ICE candidates

+ +

O próximo passo é configurar cada conexão com os ouvintes do ICE que serão chamados quando houver um novo candidato ICE para comunicar com o outro lado.

+ +
+

Nota: Em um cenário do mundo real em que os dois pares não estão sendo executados no mesmo contexto, o processo é um pouco mais complexo; Cada lado fornece, um de cada vez, um sugestão sobre como conectar (por exemplo, UDP, UDP com um relay, TCP, etc.) chamando {{domxref("RTCPeerConnection.addIceCandidate()")}}, e eles vão de um lado para outro até chegarem a um acordo. Mas aqui, acabamos de aceitar a primeira oferta de cada lado, uma vez que não existe uma rede real envolvida.

+
+ +
    localConnection.onicecandidate = e => !e.candidate
+        || remoteConnection.addIceCandidate(e.candidate)
+        .catch(handleAddCandidateError);
+
+    remoteConnection.onicecandidate = e => !e.candidate
+        || localConnection.addIceCandidate(e.candidate)
+        .catch(handleAddCandidateError);
+ +

Configuramos cada {{domxref("RTCPeerConnection")}} para ter um manipulador de eventos (event handler) para o evento {{event("icecandidate")}} .

+ +

Iniciando a tentativa de conexão

+ +

A última coisa que precisamos fazer para começar a conectar nossos pares é criar uma oferta de conexão.

+ +
    localConnection.createOffer()
+    .then(offer => localConnection.setLocalDescription(offer))
+    .then(() => remoteConnection.setRemoteDescription(localConnection.localDescription))
+    .then(() => remoteConnection.createAnswer())
+    .then(answer => remoteConnection.setLocalDescription(answer))
+    .then(() => localConnection.setRemoteDescription(remoteConnection.localDescription))
+    .catch(handleCreateDescriptionError);
+ +

Vamos passar por isto linha por linha e decifrar o que significa.

+ +
    +
  1. Primeiro chamamos {{domxref("RTCPeerConnection.createOffer()")}} método para criar um resumo {{Glossary("SDP")}} (Session Description Protocol) descrevendo a conexão que queremos fazer. Este método aceita, opcionalmente, um objeto com restrições a serem suportadas pela conexão para atender às suas necessidades, como no caso da conexão precisar suportar áudio, vídeo ou ambos. Em nosso exemplo simples, não temos restrições.
  2. +
  3. Se a oferta for criada com sucesso, passamos o resumo junto ao método de conexões locais {{domxref("RTCPeerConnection.setLocalDescription()")}} . Isso configura o ponto local da conexão.
  4. +
  5. O próximo passo é conectar o ponto local ao remoto comunicando ao ponto remoto sobre ele. Isso é feito chamando remoteConnection.{{domxref("RTCPeerConnection.setRemoteDescription()")}}. Agora o remoteConnection conhece a conexão que está sendo construída.
  6. +
  7. Isso significa que é hora do ponto remoto responder. Ele faz isso chamando o método {{domxref("RTCPeerConnection.createAnswer", "createAnswer()")}} . Isso gera um resumo de SDP que descreve a conexão que o ponto remoto está disposto e capaz de estabelecer. Essa configuração está em algum lugar na união das opções que ambos os pares podem suportar.
  8. +
  9. Uma vez que a resposta foi criada, ela é passada para o remoteConnection chamando {{domxref("RTCPeerConnection.setLocalDescription()")}}. Isso estabelece o ponto remoto da conexão (que, para o ponto remoto, é o ponto local. Isso pode parecer confuso, mas você irá se acostumar com isso.
  10. +
  11. Finalmente, a descrição local das conexões remotas está configurada para se referir ao ponto remoto, chamando localConnection's {{domxref("RTCPeerConnection.setRemoteDescription()")}}.
  12. +
  13. catch() chama uma rotina que lida com os erros que ocorrem.
  14. +
+ +
+

Nota: Mais uma vez, esse processo não é uma implementação do mundo real; No uso normal, há dois pedaços de código executados em duas máquinas, interagindo e negociando a conexão.

+
+ +

Manipulação da conexão de pares bem sucedida

+ +

Como cada lado da conexão peer-to-peer é conectado com sucesso, o evento correspondente {{domxref("RTCPeerConnection")}}'s {{event("icecandidate")}} é disparado. Esses manipuladores podem fazer o que for necessário, mas, neste exemplo, tudo o que precisamos fazer é atualizar a interface do usuário:

+ +
  function handleLocalAddCandidateSuccess() {
+    connectButton.disabled = true;
+  }
+
+  function handleRemoteAddCandidateSuccess() {
+    disconnectButton.disabled = false;
+  }
+ +

A única coisa que fazemos aqui é desativar o botão "Conectar" quando o ponto local estiver conectado e ativar o botão "Desconectar" quando o ponto remoto se conectar.

+ +

Conectando o canal de dados

+ +

Uma vez que o {{domxref("RTCPeerConnection")}} é aberto, o evento {{event("datachannel")}} é enviado para o ponto remoto para completar o processo de abertura do canal de dados; Isso invoca nosso método receiveChannelCallback(), que se parece com isso:

+ +
  function receiveChannelCallback(event) {
+    receiveChannel = event.channel;
+    receiveChannel.onmessage = handleReceiveMessage;
+    receiveChannel.onopen = handleReceiveChannelStatusChange;
+    receiveChannel.onclose = handleReceiveChannelStatusChange;
+  }
+ +

O evento{{event("datachannel")}} inclui, em sua propriedade de canal, uma referência a um {{domxref("RTCDataChannel")}} Representando o ponto remoto do canal. Isso é salvo, e nós configuramos, no canal, ouvintes de eventos para os eventos que queremos manipular. Uma vez feito isso, nosso método handleReceiveMessage() Será chamado cada vez que os dados são recebidos pelo ponto remoto, e o método handleReceiveChannelStatusChange() será chamado sempre que mudar o estado da conexão do canal, para que possamos reagir quando o canal estiver totalmente aberto e quando ele for fechado.

+ +

Lidando com as mudanças de status do canal

+ +

Ambos nossos pontos locais e remotos usam um único método para lidar com eventos que indicam alguma alteração no status da conexão do canal.

+ +

Quando o ponto local experimenta um evento aberto ou fechado, o métodohandleSendChannelStatusChange() é chamado:

+ +
  function handleSendChannelStatusChange(event) {
+    if (sendChannel) {
+      var state = sendChannel.readyState;
+
+      if (state === "open") {
+        messageInputBox.disabled = false;
+        messageInputBox.focus();
+        sendButton.disabled = false;
+        disconnectButton.disabled = false;
+        connectButton.disabled = true;
+      } else {
+        messageInputBox.disabled = true;
+        sendButton.disabled = true;
+        connectButton.disabled = false;
+        disconnectButton.disabled = true;
+      }
+    }
+  }
+ +

Se o estado do canal mudou para "open", isso indica que terminamos de estabelecer o link entre os dois pares. A interface do usuário é atualizada de forma correspondente: ativando o elemento de input de texto para a mensagem a ser enviada, focando este elemento de input para que o usuário comece imediatamente a digitar, habilitando os botões "Enviar" e "Desconectar", que são agora utilizáveis, E desativando o botão "Conectar", uma vez que não é necessário quando a conexão está aberta.

+ +

Se o estado do canal mudou para "closed", ocorre o conjunto oposto de ações: a caixa de entrada de texto e o botão "Enviar" estão desativados, o botão "Conectar" está habilitado para que o usuário possa abrir uma nova conexão se desejar, e o botão "Desconectar" está desativado, uma vez que não é útil quando não existe conexão.

+ +

Nosso exemplo de par remoto, por outro lado, ignora os eventos de alteração de status, exceto para registrar o evento no console:

+ +
  function handleReceiveChannelStatusChange(event) {
+    if (receiveChannel) {
+      console.log("Receive channel's status has changed to " +
+                  receiveChannel.readyState);
+    }
+  }
+ +

O método handleReceiveChannelStatusChange() recebe como parâmetro de entrada o evento que ocorreu; Este será um {{domxref("RTCDataChannelEvent")}}.

+ +

Enviando mensagens

+ +

Quando o usuário pressiona o botão "Enviar", o método sendMessage() que estabelecemos como o manipulador para o evento do botão {{event("click")}} é chamado. Esse método é bastante simples:

+ +
  function sendMessage() {
+    var message = messageInputBox.value;
+    sendChannel.send(message);
+
+    messageInputBox.value = "";
+    messageInputBox.focus();
+  }
+ +

Primeiro, o texto da mensagem é obtido dos atributos do elemento de input {{htmlattrxref("value", "input")}} . Isso é enviado para o ponto remoto, ligando para {{domxref("RTCDataChannel.send", "sendChannel.send()")}}. E está tudo aí! O resto deste método é apenas um pouco de açúcar para experiência do usuário - a caixa de entrada é esvaziada e re-focada para que o usuário comece imediatamente a digitar outra mensagem.

+ +

Recebendo mensagens

+ +

Quando ocorre um evento de "mensagem" no canal remoto, nosso método handleReceiveMessage() é chamado como o manipulador de eventos.

+ +
  function handleReceiveMessage(event) {
+    var el = document.createElement("p");
+    var txtNode = document.createTextNode(event.data);
+
+    el.appendChild(txtNode);
+    receiveBox.appendChild(el);
+  }
+ +

Este método simplesmente executa alguns injeções básicas {{Glossary("DOM")}} ; cria um novo {{HTMLElement("p")}} (paragraph) elemento, então cria um novo nó {{domxref("Text")}} contendo o texto da mensagem, que é recebido na propriedade de dados do evento. Este nó de texto é anexado como um filho do novo elemento, que é então inserido no bloco receiveBox, fazendo com que ele desenhe na janela do navegador.

+ +

Desconectando os pares (peers)

+ +

Quando o usuário clica no botão "Desconectar", o método disconnectPeers() previamente configurado como o manipulador desse botão é chamado.

+ +
  function disconnectPeers() {
+
+    // Close the RTCDataChannels if they're open.
+
+    sendChannel.close();
+    receiveChannel.close();
+
+    // Close the RTCPeerConnections
+
+    localConnection.close();
+    remoteConnection.close();
+
+    sendChannel = null;
+    receiveChannel = null;
+    localConnection = null;
+    remoteConnection = null;
+
+    // Update user interface elements
+
+    connectButton.disabled = false;
+    disconnectButton.disabled = true;
+    sendButton.disabled = true;
+
+    messageInputBox.value = "";
+    messageInputBox.disabled = true;
+  }
+
+ +

Isso começa por fechar cada par {{domxref("RTCDataChannel")}}, então, de forma semelhante, cada um {{domxref("RTCPeerConnection")}}. Então, todas as referências salvas desses objetos são definidas como null para evitar a reutilização acidental, e a interface do usuário é atualizada para refletir o fato de que a conexão foi fechada.

+ +

Próximos passos

+ +

Você poderia tentar este exemplo e dar uma olhada no código fonte webrtc-simple-datachannel, disponível no GitHub.

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

O objeto WebSocket provê uma API para criação e gerenciamento de uma conexão WebSocket com um servidor, bem como o envio e recebimento de dados através dessa conexão.

+ +

O construtor do WebSocket aceita um parâmetro obrigatório e um opcional:

+ +
WebSocket WebSocket(
+  in DOMString url,
+  in optional DOMString protocols
+);
+
+WebSocket WebSocket(
+  in DOMString url,
+  in optional DOMString[] protocols
+);
+
+ +
+
url
+
A URL da devida conexão; esta deve ser a URL da qual o servidor WebSocket irá responder.
+
protocols {{optional_inline}}
+
Um único protocolo em formato texto ou uma lista de textos de protocolo. Estes textos são usados para indicar sub-protocolos, assim então um único servidor pode implementar múltiplos sub-protocolos WebSocket (por exemplo, você pode querer um servidor capaz de manipular diferentes tipos de interações dependendo do protocolo especificado). se você não especificar um protocolo em texto, será assumido um texto vazio.
+
+ +

O construtor pode lançar exceções:

+ +
+
SECURITY_ERR
+
A porta a qual a conexão está sendo executada está bloqueada.
+
+ +

Visão Geral do método

+ + + + + + + + + + +
void close(É opcional: unsigned long code, É opcional: DOMString reason);
void send(in DOMString data);
+ +

Atributos

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
AttributoTipoDescrição
binaryType{{DOMXref("DOMString")}} +

Uma string indica o tipo de dado binário que está sendo transmitido pela conexão. Este deve ser tanto "blob" se o objeto DOM {{domxref("Blob")}} estiver sendo usado ou "arraybuffer" se os objetos {{jsxref("ArrayBuffer")}} estiver sendo usada

+
bufferedAmountunsigned long +

O número de bites de dados que tem sid consultado usando chamadas para {{manch("send")}} mas não ainda para a rede.Estes valor reseta para zero uma vez que todos os dados tem sido mandados.Este valor não reseta para zero quando a conexão está fechada, se você continuar chamando {{manch("send")}}, isto continuará escalando. Leitura online

+
extensions{{DOMXref("DOMString")}}As extensões selecionadas pelo servidor. Este é atualmente apenas a string vazia ou uma lista de extensões negociadas pela conexão.
onclose{{domxref("EventListener")}}Um event listener para ser chamado quando o readyState da conexão do WebSocket mudar para CLOSED . O listener recebe um CloseEvent "close".
onerror{{domxref("EventListener")}}Um event listener para ser chamado quando ocorrer um erro. Este é um evento simples chamado "erro".
onmessage{{domxref("EventListener")}}Um event listener para ser chamado quando uma mensagem é recebida do servidor. O listener recebe um MessageEvent "message".
onopen{{domxref("EventListener")}}Um event listener para ser chamado quando o readyState da conexão do WebSocket mudar para OPEN , isso indica que a conexão está pronta para enviar e receber dados. O evento é simples, com o nome "open".
protocol{{DOMXref("DOMString")}}Uma sequência de caracteres que indica o nome do sub-protocolo selecionado pelo servidor, este será um dos parâmetros especificados no protocolo ao criar o objeto WebSocket.
readyStateunsigned shortO estado atual da conexão, este é um dos {{anch("Ready state constants")}}. Apenas leitura.
url{{DOMXref("DOMString")}}O URL resolvido pelo construtor. Este é sempre um URL absoluto. Apenas leitura.
+ +

Constantes

+ +

Estados de constantes prontas

+ +

Essas constantes são usadas pelo atributo readyState para descrever o estado da conexão do WebSocket.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ConstanteValorDescrição
CONNECTING0A conexão ainda não está aberta.
OPEN1A conexão está aberta e pronta para se comunicar.
CLOSING2A conexão está em processo de fechamento.
CLOSED3A conexão está fechada ou não foi possível abrir.
+ +

Métodos

+ +

close()

+ +

Fecha a conexão do WebSocket ou a tentativa de conexão, se houver. Se a conexão já for CLOSED , este método não faz nada.

+ +
void close(
+  É opcional: unsigned short code,
+  É opcional: DOMString reason
+);
+
+ +

Parametros

+ +
+
code {{optional_inline}}
+
Um valor numérico que indica o código de status explicando por que a conexão está sendo fechada. Se esse parâmetro não for especificado, é assumido um valor padrão de 1000 (indicando um fechamento "completo da transação"). Veja a lista de status de códigos na CloseEvent página de valores permitidos.
+
reason {{optional_inline}}
+
Uma string legível para humanos que explica por que a conexão está se fechando. Esta seqüência de caracteres não deve ter mais de 123 bytes de texto UTF-8 (não caracteres).
+
+ +

Exceções lançadas

+ +
+
INVALID_ACCESS_ERR
+
Foi especificado um códigoinválido.
+
SYNTAX_ERR
+
A string reason é muito longa ou contém substitutos não comparados.
+
+ +
+

Note: No Gecko, este método não suporta nenhum parâmetro antes do Gecko 8.0 {{geckoRelease("8.0")}}.

+
+ +

send()

+ +

Transmite dados para o servidor através da conexão WebSocket.

+ +

+void send(
+  in DOMString data
+);
+
+void send(
+  in ArrayBuffer data
+);
+
+void send(
+  in Blob data
+);
+
+ +

Parametros

+ +
+
data
+
Uma sequência de texto para enviar para o servidor.
+
+ +

Exceções lançadas

+ +
+
INVALID_STATE_ERR
+
A conexão não está atualmente OPEN .
+
SYNTAX_ERR
+
Os dados são uma string que tem substituto não comparado.
+
+ +
+

Nota: A implementação do método send () de Gecko difere um pouco da especificação em {{Gecko("6.0")}}. Gecko retorna um boolean indicando se a conexão ainda está aberta (por extensão, ou os dados estão em fila ou transmitidos com sucesso). Isso é corrigido em {{Gecko("8.0")}}.

+ +

A partir de {{Gecko("11.0")}}, o suporte para {{jsxref ("ArrayBuffer")}} está implementado, mas não {{domxref("Blob")}} tipos de dados.

+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçõesStatusComentário
{{SpecName("Websockets", "#the-websocket-interface", "WebSocket")}}{{Spec2("Websockets")}}Definição inicial
+ + + +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticasChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatGeckoDesktop("2.0")}}[1]{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
Suporte sub-protocolo{{CompatUnknown}}{{CompatGeckoDesktop("6.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticasAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatUnknown}}{{CompatGeckoMobile("7.0")}}[1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Suporte sub-protocolo{{CompatUnknown}}{{CompatGeckoMobile("7.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Iniciado no Gecko 6.0 {{geckoRelease("6.0")}}, o construtor está prefixado. Você precisará usar MozWebSocket() : var mySocket = new MozWebSocket("http://www.example.com/socketserver");

+ +

As extensões atribuídas não eram suportadas no Gecko até Gecko 8.0.

+ +

Antes do Gecko 11.0 {{geckoRelease("11.0")}}, as mensagens de saída enviadas usavam o método send(), eram limitadas a 16MB. Agora elas podem ter até 2GB de tamanho.

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/webvr_api/index.html b/files/pt-br/web/api/webvr_api/index.html new file mode 100644 index 0000000000..3046e3f086 --- /dev/null +++ b/files/pt-br/web/api/webvr_api/index.html @@ -0,0 +1,151 @@ +--- +title: WebVR API +slug: Web/API/WebVR_API +translation_of: Web/API/WebVR_API +--- +
{{draft("The WebVR API documentation is currently being updated to cover the v1.0 spec, therefore some of this information will be out of date. Contact ~~chrisdavidmills if you have any questions about this work.")}}{{DefaultAPISidebar("WebVR API")}}{{SeeCompatTable}}
+ +

O WebVR oferece suporte para expor dispositivos de realidade virtual - por exemplo, telas montadas na cabeça, como o Oculus Rift - para aplicativos da web, permitindo que os desenvolvedores traduzam informações de posição e movimento da tela para movimento em torno de uma cena 3D. Isso tem inúmeras aplicações muito interessantes, de passeios de produtos virtuais e aplicativos de treinamento interativo para super imersivo jogos em primeira pessoa.

+ +

Conceitos e uso

+ +

Sketch of a person in a chair with wearing goggles labelled Head mounted display (HMD) facing a monitor with a webcam labelled Position sensor

+ +

Todos os dispositivos VR ligados ao computador serão devolvidos pelo {{domxref("Navigator.getVRDisplays()")}} método. Que retorna uma matriz de objetos para representar os dispositivos conectados, que herdam do objeto geral {{domxref("VRDevice")}} Geralmente o display usado na cabeça terá dois dispositivos - o próprio display montado na cabeça, representado por {{domxref("HMDVRDevice")}}, e uma câmera com sensor na posição que manterá o controle de sua posição de cabeça, representada por {{domxref("PositionSensorVRDevice")}}.

+ +

O objeto {{domxref("PositionSensorVRDevice")}} contém o método {{domxref("PositionSensorVRDevice.getState", "getState()")}}, que retorna um objeto {{domxref("VRPositionState")}} - isto representa o estado do sensor num dado carimbo de data e inclui propriedades que contêm dados úteis tais como velocidade, aceleração e orientação atuais, úteis para atualizar o processamento de uma cena em cada trama de acordo com o movimento do visor montado na cabeça VR.

+ +

O método {{domxref("HMDVRDevice.getEyeParameters()")}} retorna um objeto {{domxref("VREyeParameters")}}, que pode ser usado para retornar informações do campo de exibição - quanto da cena a tela montada na cabeça pode ver.O {{domxref("VREyeParameters.currentFieldOfView")}} retorna um objeto {{domxref("VRFieldOfView")}} que contém 4 ângulos que descrevem a vista atual a partir de um ponto central. Você também pode alterar o campo de visualização usando {{domxref("HMDVRDevice.setFieldOfView()")}}.

+ +
+

WebVR Interfaces

+ +

{{domxref("VRDisplay")}}
+ Representa qualquer dispositivo VR suportado por esta API. Ele inclui informações genéricas, como IDs de dispositivo e descrições, bem como métodos para começar a apresentar uma cena VR, recuperar os parâmetros do olho e exibir capacidades e outras funcionalidades importantes.
+ {{domxref("VRDisplayCapabilities")}}
+ Descreve os recursos de um {{domxref("VRDisplay")}} - seus recursos podem ser usados ​​para executar testes de capacidade do dispositivo VR, por exemplo, ele pode retornar informações de posição.
+ {{domxref("VRPose")}}
+ Representa o estado de posição em um dado carimbo de data/hora (que inclui orientação, posição, velocidade e aceleração).
+ {{domxref ("VREyeParameters")}}
+ Fornece acesso a todas as informações necessárias para processar corretamente uma cena para cada olho, incluindo informações de campo de visão.
+ {{domxref("VRFieldOfView")}}
+ Representa um campo de visão definido por 4 valores de graus diferentes que descrevem a vista a partir de um ponto central.
+ {{Domxref("VRLayer")}}
+ Representa uma camada a ser apresentada em {{domxref("VRDisplay")}}.
+ {{domxref("VRStageParameters")}}
+ Representa os valores que descrevem a área de estágio para dispositivos que suportam experiências em escala de sala.

+ +

Extensões para outras interfaces

+ +

{{domxref("Gamepad.displayId")}} {{readonlyInline}}
+ Retorna o {{domxref("VRDisplay.displayId")}} do associado {{domxref("VRDisplay")}} - o VRDisplay que o gamepad está controlando a cena exibida de.
+ {{domxref("Navigator.activeVRDisplays")}} {{readonlyInline}}
+ Retorna uma matriz contendo todos os objetos {{domxref("VRDisplay")}} que está sendo apresentado ({{domxref("VRDisplay.ispresenting")}}).
+ {{domxref("Navigator.getVRDisplays()")}}
+ Retorna uma promessa que resolve uma matriz de objetos {{domxref("VRDisplay")}} que representa qualquer dispositivo VR disponível conectado ao computador.
+ {{domxref("Window.onvrdisplayconnected")}}
+ Representa um manipulador de eventos que será executado quando um dispositivo VR compatível tiver sido conectado ao computador (quando o evento {{event("vrdisplayconnected")}} for acionado).
+ {{domxref("Window.onvrdisplaydisconnected")}}
+ Representa um manipulador de eventos que será executado quando um dispositivo VR compatível tiver sido desconectado do computador (quando o evento {{event("vrdisplaydisconnected")}} for acionado).
+ {{domxref("Window.onvrdisplaypresentchange")}}
+ Representa um manipulador de eventos que será executado quando o estado de apresentação de um dispositivo VR mudar - isto é, vai de apresentar a não apresentar, ou vice-versa (quando o evento {{event("onvrdisplaypresentchange")}} é acionado).

+
+ +

Examplos

+ +

Você pode encontrar uma série de exemplos nesses repositórios Github:

+ + + +

Especificações

+ + + + + + + + + + + + + + +
SpecificaçãoStatusComentario
{{SpecName('WebVR')}}{{Spec2('WebVR')}}Initial definition
+ +

Compatibilidade do Browser (navegador)

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeChromiumFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
+

Suporte Básico

+
{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileChrome for AndroidSamsung Internet for GearVR
+

Suporte Básico

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

Veja Também

+ + diff --git a/files/pt-br/web/api/webvr_api/using_the_webvr_api/index.html b/files/pt-br/web/api/webvr_api/using_the_webvr_api/index.html new file mode 100644 index 0000000000..88c0697bdb --- /dev/null +++ b/files/pt-br/web/api/webvr_api/using_the_webvr_api/index.html @@ -0,0 +1,440 @@ +--- +title: Using the WebVR API +slug: Web/API/WebVR_API/Using_the_WebVR_API +translation_of: Web/API/WebVR_API/Using_the_WebVR_API +--- +
{{APIRef("WebVR API")}}{{deprecated_header}}
+ +
Note: WebVR API is replaced by WebXR API. WebVR was never ratified as a standard, was implemented and enabled by default in very few browsers and supported a small number of devices.
+ +

The WebVR API is a fantastic addition to the web developer's toolkit, allowing WebGL scenes to be presented in virtual reality displays such as the Oculus Rift and HTC Vive. But how do you get started with developing VR apps for the Web? This article will guide you through the basics.

+ +
+

Note: The WebVR API's most stable version — 1.1 — has recently been implemented in Firefox 55 (Windows in release version, and Mac OS X on Nightly only) and is also available in Chrome when used with Google Daydream hardware. There is also a later evolution of the spec — 2.0 — but this is at an early stage right now. You can find information on the latest state of the specs at WebVR Spec Version List.

+
+ +

Getting started

+ +

To get started, you need:

+ + + +

Once you have everything assembled, you can test to see whether your setup works with WebVR by going to our simple A-Frame demo, and seeing whether the scene renders and whether you can enter VR display mode by pressing the button at the bottom right.

+ +

A-Frame is by far the best option if you want to create a WebVR-compatible 3D scene quickly, without needing to understand a bunch of new JavaScript code. It doesn't however teach you how the raw WebVR API works, and this is what we'll get on to next.

+ +

Introducing our demo

+ +

To illustrate how the WebVR API works, we'll study our raw-webgl-example, which looks a bit like this:

+ +

+ +
+

Note: You can find the source code of our demo on GitHub, and view it live also.

+
+ +
+

Note: If WebVR isn't working in your browser, you might need to make sure it is running through your graphics card. For example for NVIDIA cards, if you've got the NVIDIA control panel set up successfully, there will be a context menu option available — right click on Firefox, then choose Run with graphics processor > High-performance NVIDIA processor.

+
+ +

Our demo features the holy grail of WebGL demos — a rotating 3D cube. We've implemented this using raw WebGL API code. We won't be teaching any basic JavaScript or WebGL, just the WebVR parts.

+ +

Our demo also features:

+ + + +

When you look through the source code of our demo's main JavaScript file, you can easily find the WebVR-specific parts by searching for the string "WebVR" in preceding comments.

+ +
+

Note: To find out more about basic JavaScript and WebGL, consult our JavaScript learning material, and our WebGL Tutorial.

+
+ +

How does it work?

+ +

At this point, let's look at how the WebVR parts of the code work.

+ +

A typical (simple) WebVR app works like this:

+ +
    +
  1. {{domxref("Navigator.getVRDisplays()")}} is used to get a reference to your VR display.
  2. +
  3. {{domxref("VRDisplay.requestPresent()")}} is used to start presenting to the VR display.
  4. +
  5. WebVR's dedicated {{domxref("VRDisplay.requestAnimationFrame()")}} method is used to run the app's rendering loop at the correct refresh rate for the display.
  6. +
  7. Inside the rendering loop, you grab the data required to display the current frame ({{domxref("VRDisplay.getFrameData()")}}), draw the displayed scene twice — once for the view in each eye — then submit the rendered view to the display to show to the user via ({{domxref("VRDisplay.submitFrame()")}}).
  8. +
+ +

In the below sections we'll look at our raw-webgl-demo in detail, and see where exactly the above features are used.

+ +

Starting with some variables

+ +

The first WebVR-related code you'll meet is this following block:

+ +
// WebVR variables
+
+var frameData = new VRFrameData();
+var vrDisplay;
+var btn = document.querySelector('.stop-start');
+var normalSceneFrame;
+var vrSceneFrame;
+
+var poseStatsBtn = document.querySelector('.pose-stats');
+var poseStatsSection = document.querySelector('section');
+poseStatsSection.style.visibility = 'hidden'; // hide it initially
+
+var posStats = document.querySelector('.pos');
+var orientStats = document.querySelector('.orient');
+var linVelStats = document.querySelector('.lin-vel');
+var linAccStats = document.querySelector('.lin-acc');
+var angVelStats = document.querySelector('.ang-vel');
+var angAccStats = document.querySelector('.ang-acc');
+var poseStatsDisplayed = false;
+ +

Let's briefly explain these:

+ + + +

Getting a reference to our VR display

+ +

One of the major functions inside our code is start() — we run this function when the body has finished loading:

+ +
// start
+//
+// Called when the body has loaded is created to get the ball rolling.
+
+document.body.onload = start;
+ +

To begin with, start() retrieves a WebGL context to use to render 3D graphics into the {{htmlelement("canvas")}} element in our HTML. We then check whether the gl context is available — if so, we run a number of functions to set up the scene for display.

+ +
function start() {
+  canvas = document.getElementById("glcanvas");
+
+  initWebGL(canvas);      // Initialize the GL context
+
+  // WebGL setup code here
+ +

Next, we start the process of actually rendering the scene onto the canvas, by setting the canvas to fill the entire browser viewport, and running the rendering loop (drawScene()) for the first time. This is the non-WebVR — normal — rendering loop.

+ +
    // draw the scene normally, without WebVR - for those who don't have it and want to see the scene in their browser
+
+    canvas.width = window.innerWidth;
+    canvas.height = window.innerHeight;
+    drawScene();
+ +

Now onto our first WebVR-specific code. First of all, we check to see if {{domxref("Navigator.getVRDisplays")}} exists — this is the entry point into the API, and therefore good basic feature detection for WebVR. You'll see at the end of the block (inside the else clause) that if this doesn't exist, we log a message to indicate that WebVR 1.1 isn't supported by the browser.

+ +
    // WebVR: Check to see if WebVR is supported
+    if(navigator.getVRDisplays) {
+      console.log('WebVR 1.1 supported');
+ +

Inside our if() { ... } block, we run the {{domxref("Navigator.getVRDisplays()")}} function. This returns a promise, which is fulfilled with an array containing all the VR display devices connected to the computer. If none are connected, the array will be empty.

+ +
      // Then get the displays attached to the computer
+      navigator.getVRDisplays().then(function(displays) {
+ +

Inside the promise then() block, we check whether the array length is more than 0; if so, we set the value of our vrDisplay variable to the 0 index item inside the array. vrDisplay now contains a {{domxref("VRDisplay")}} object representing our connected display!

+ +
        // If a display is available, use it to present the scene
+        if(displays.length > 0) {
+          vrDisplay = displays[0];
+          console.log('Display found');
+ +
+

Note: It is unlikely that you'll have multiple VR displays connected to your computer, and this is just a simple demo, so this will do for now.

+
+ +

Starting and stopping the VR presentation

+ +

Now we have a {{domxref("VRDisplay")}} object, we can use it do a number of things. The next thing we want to do is wire up functionality to start and stop presentation of the WebGL content to the display.

+ +

Continuing on with the previous code block, we now add an event listener to our start/stop button (btn) — when this button is clicked we want to check whether we are presenting to the display already (we do this in a fairly dumb fashion, by checking what the button textContent contains).

+ +

If the display is not already presenting, we use the {{domxref("VRDisplay.requestPresent()")}} method to request that the browser start presenting content to the display. This takes as a parameter an array of the {{domxref("VRLayerInit")}} objects representing the layers you want to present in the display.

+ +

Since the maximum number of layers you can display is currently 1, and the only required object member is the {{domxref("VRLayerInit.source")}} property (which is a reference to the {{htmlelement("canvas")}} you want to present in that layer; the other parameters are given sensible defaults — see {{domxref("VRLayerInit.leftBounds", "leftBounds")}} and {{domxref("VRLayerInit.rightBounds", "rightBounds")}})), the parameter is simply [{ source: canvas }].

+ +

requestPresent() returns a promise that is fulfilled when the presentation begins successfully.

+ +
          // Starting the presentation when the button is clicked: It can only be called in response to a user gesture
+          btn.addEventListener('click', function() {
+            if(btn.textContent === 'Start VR display') {
+              vrDisplay.requestPresent([{ source: canvas }]).then(function() {
+                console.log('Presenting to WebVR display');
+ +

With our presentation request successful, we now want to start setting up to render content to present to the VRDisplay. First of all we set the canvas to the same size as the VR display area. We do this by getting the {{domxref("VREyeParameters")}} for both eyes using {{domxref("VRDisplay.getEyeParameters()")}}.

+ +

We then do some simple math to calculate the total width of the VRDisplay rendering area based on the eye {{domxref("VREyeParameters.renderWidth")}} and {{domxref("VREyeParameters.renderHeight")}}.

+ +
                // Set the canvas size to the size of the vrDisplay viewport
+
+                var leftEye = vrDisplay.getEyeParameters('left');
+                var rightEye = vrDisplay.getEyeParameters('right');
+
+                canvas.width = Math.max(leftEye.renderWidth, rightEye.renderWidth) * 2;
+                canvas.height = Math.max(leftEye.renderHeight, rightEye.renderHeight);
+ +

Next, we {{domxref("Window.cancelAnimationFrame()", "cancel the animation loop")}} previously set in motion by the {{domxref("Window.requestAnimationFrame()")}} call inside the drawScene() function, and instead invoke drawVRScene(). This function renders the same scene as before, but with some special WebVR magic going on. The loop inside here is maintained by WebVR's special {{domxref("VRDisplay.requestAnimationFrame")}} method.

+ +
                // stop the normal presentation, and start the vr presentation
+                window.cancelAnimationFrame(normalSceneFrame);
+                drawVRScene();
+ +

Finally, we update the button text so that the next time it is pressed, it will stop presentation to the VR display.

+ +
                btn.textContent = 'Exit VR display';
+              });
+ +


+ To stop the VR presentation when the button is subsequently pressed, we call {{domxref("VRDisplay.exitPresent()")}}. We also reverse the button's text content, and swap over the requestAnimationFrame calls. You can see here that we are using {{domxref("VRDisplay.cancelAnimationFrame")}} to stop the VR rendering loop, and starting the normal rendering loop off again by calling drawScene().

+ +
            } else {
+              vrDisplay.exitPresent();
+              console.log('Stopped presenting to WebVR display');
+
+              btn.textContent = 'Start VR display';
+
+              // Stop the VR presentation, and start the normal presentation
+              vrDisplay.cancelAnimationFrame(vrSceneFrame);
+              drawScene();
+            }
+          });
+        }
+      });
+    } else {
+      console.log('WebVR API not supported by this browser.');
+    }
+  }
+}
+ +

Once the presentation starts, you'll be able to see the stereoscopic view displayed in the browser:

+ +

+ +

You'll learn below how the stereoscopic view is actually produced.

+ +

Why does WebVR have its own requestAnimationFrame()?

+ +

This is a good question. The reason is that for smooth rendering inside the VR display, you need to render the content at the display's native refresh rate, not that of the computer. VR display refresh rates are greater than PC refresh rates, typically up to 90fps. The rate will be differ from the computer's core refresh rate.

+ +

Note that when the VR display is not presenting, {{domxref("VRDisplay.requestAnimationFrame")}} runs identically to {{domxref("Window.requestAnimationFrame")}}, so if you wanted, you could just use a single rendering loop, rather than the two we are using in our app. We have used two because we wanted to do slightly different things depending on whether the VR display is presenting or not, and keep things separated for ease of comprehension.

+ +

Rendering and display

+ +

At this point, we've seen all the code required to access the VR hardware, request that we present our scene to the hardware, and start running the rending loop. Let's now look at the code for the rendering loop, and explain how the WebVR-specific parts of it work.

+ +

First of all, we begin the definition of our rendering loop function — drawVRScene(). The first thing we do inside here is make a call to {{domxref("VRDisplay.requestAnimationFrame()")}} to keep the loop running after it has been called once (this occurred earlier on in our code when we started presenting to the VR display). This call is set as the value of the global vrSceneFrame variable, so we can cancel the loop with a call to {{domxref("VRDisplay.cancelAnimationFrame()")}} once we exit VR presenting.

+ +
function drawVRScene() {
+  // WebVR: Request the next frame of the animation
+  vrSceneFrame = vrDisplay.requestAnimationFrame(drawVRScene);
+ +

Next, we call {{domxref("VRDisplay.getFrameData()")}}, passing it the name of the variable that we want to use to contain the frame data. We initialized this earlier on — frameData. After the call completes, this variable will contain the data need to render the next frame to the VR device, packaged up as a {{domxref("VRFrameData")}} object. This contains things like projection and view matrices for rendering the scene correctly for the left and right eye view, and the current {{domxref("VRPose")}} object, which contains data on the VR display such as orientation, position, etc.

+ +

This has to be called on every frame so the rendered view is always up-to-date.

+ +
  // Populate frameData with the data of the next frame to display
+  vrDisplay.getFrameData(frameData);
+ +

Now we retrieve the current {{domxref("VRPose")}} from the {{domxref("VRFrameData.pose")}} property, store the position and orientation for use later on, and send the current pose to the pose stats box for display, if the poseStatsDisplayed variable is set to true.

+ +
  // You can get the position, orientation, etc. of the display from the current frame's pose
+
+  var curFramePose = frameData.pose;
+  var curPos = curFramePose.position;
+  var curOrient = curFramePose.orientation;
+  if(poseStatsDisplayed) {
+    displayPoseStats(curFramePose);
+  }
+ +

  We now clear the canvas before we start drawing on it, so that the next frame is clearly seen, and we don't also see previous rendered frames:

+ +
  // Clear the canvas before we start drawing on it.
+
+  gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
+ +

We now render the view for both the left and right eyes. First of all we need to create projection and view locations for use in the rendering. these are {{domxref("WebGLUniformLocation")}} objects, created using the {{domxref("WebGLRenderingContext.getUniformLocation()")}} method, passing it the shader program's identifier and an identifying name as parameters.

+ +
  // WebVR: Create the required projection and view matrix locations needed
+  // for passing into the uniformMatrix4fv methods below
+
+  var projectionMatrixLocation = gl.getUniformLocation(shaderProgram, "projMatrix");
+  var viewMatrixLocation = gl.getUniformLocation(shaderProgram, "viewMatrix");
+ +

The next rendering step involves:

+ + + +
  // WebVR: Render the left eye’s view to the left half of the canvas
+  gl.viewport(0, 0, canvas.width * 0.5, canvas.height);
+  gl.uniformMatrix4fv(projectionMatrixLocation, false, frameData.leftProjectionMatrix);
+  gl.uniformMatrix4fv(viewMatrixLocation, false, frameData.leftViewMatrix);
+  drawGeometry();
+ +

We now do exactly the same thing, but for the right eye:

+ +
  // WebVR: Render the right eye’s view to the right half of the canvas
+  gl.viewport(canvas.width * 0.5, 0, canvas.width * 0.5, canvas.height);
+  gl.uniformMatrix4fv(projectionMatrixLocation, false, frameData.rightProjectionMatrix);
+  gl.uniformMatrix4fv(viewMatrixLocation, false, frameData.rightViewMatrix);
+  drawGeometry();
+ +

Next we define our drawGeometry() function. Most of this is just general WebGL code required to draw our 3D cube. You'll see some WebVR-specific parts in the mvTranslate() and mvRotate() function calls — these pass matrices into the WebGL program that define the translation and rotation of the cube for the current frame

+ +

You'll see that we are modifying these values by the position (curPos) and orientation (curOrient) of the VR display we got from the {{domxref("VRPose")}} object. The result is that, for example, as you move or rotate your head left, the x position value (curPos[0]) and y rotation value ([curOrient[1]) are added to the x translation value, meaning that the cube will move to the right, as you'd expect when you are looking at something and then move/turn your head left.

+ +

This is a quick and dirty way to use VR pose data, but it illustrates the basic principle.

+ +
  function drawGeometry() {
+    // Establish the perspective with which we want to view the
+    // scene. Our field of view is 45 degrees, with a width/height
+    // ratio of 640:480, and we only want to see objects between 0.1 units
+    // and 100 units away from the camera.
+
+    perspectiveMatrix = makePerspective(45, 640.0/480.0, 0.1, 100.0);
+
+    // Set the drawing position to the "identity" point, which is
+    // the center of the scene.
+
+    loadIdentity();
+
+    // Now move the drawing position a bit to where we want to start
+    // drawing the cube.
+
+    mvTranslate([
+                  0.0 - (curPos[0] * 25) + (curOrient[1] * 25),
+                  5.0 - (curPos[1] * 25) - (curOrient[0] * 25),
+                  -15.0 - (curPos[2] * 25)
+               ]);
+
+    // Save the current matrix, then rotate before we draw.
+
+    mvPushMatrix();
+    mvRotate(cubeRotation, [0.25, 0, 0.25 - curOrient[2] * 0.5]);
+
+    // Draw the cube by binding the array buffer to the cube's vertices
+    // array, setting attributes, and pushing it to GL.
+
+    gl.bindBuffer(gl.ARRAY_BUFFER, cubeVerticesBuffer);
+    gl.vertexAttribPointer(vertexPositionAttribute, 3, gl.FLOAT, false, 0, 0);
+
+    // Set the texture coordinates attribute for the vertices.
+
+    gl.bindBuffer(gl.ARRAY_BUFFER, cubeVerticesTextureCoordBuffer);
+    gl.vertexAttribPointer(textureCoordAttribute, 2, gl.FLOAT, false, 0, 0);
+
+    // Specify the texture to map onto the faces.
+
+    gl.activeTexture(gl.TEXTURE0);
+    gl.bindTexture(gl.TEXTURE_2D, cubeTexture);
+    gl.uniform1i(gl.getUniformLocation(shaderProgram, "uSampler"), 0);
+
+    // Draw the cube.
+
+    gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, cubeVerticesIndexBuffer);
+    setMatrixUniforms();
+    gl.drawElements(gl.TRIANGLES, 36, gl.UNSIGNED_SHORT, 0);
+
+    // Restore the original matrix
+
+    mvPopMatrix();
+  }
+
+ +

The next bit of the code has nothing to do with WebVR — it just updates the rotation of the cube on each frame:

+ +
  // Update the rotation for the next draw, if it's time to do so.
+
+  var currentTime = (new Date).getTime();
+  if (lastCubeUpdateTime) {
+    var delta = currentTime - lastCubeUpdateTime;
+
+    cubeRotation += (30 * delta) / 1000.0;
+  }
+
+  lastCubeUpdateTime = currentTime;
+ +

The last part of the rendering loop involves us calling {{domxref("VRDisplay.submitFrame()")}} — now all the work has been done and we've rendered the display on the {{htmlelement("canvas")}}, this method then submits the frame to the VR display so it is displayed on there as well.

+ +
  // WebVR: Indicate that we are ready to present the rendered frame to the VR display
+  vrDisplay.submitFrame();
+}
+ +

Displaying the pose (position, orientation, etc.) data

+ +

In this section we'll discuss the displayPoseStats() function, which displays our updated pose data on each frame. The function is fairly simple.

+ +

First of all, we store the six different property values obtainable from the {{domxref("VRPose")}} object in their own variables — each one is a {{domxref("Float32Array")}}.

+ +
function displayPoseStats(pose) {
+  var pos = pose.position;
+  var orient = pose.orientation;
+  var linVel = pose.linearVelocity;
+  var linAcc = pose.linearAcceleration;
+  var angVel = pose.angularVelocity;
+  var angAcc = pose.angularAcceleration;
+ +

We then write out the data into the information box, updating it on every frame. We've clamped each value to three decimal places using toFixed(), as the values are hard to read otherwise.

+ +

You should note that we've used a conditional expression to detect whether the linear acceleration and angular acceleration arrays are successfully returned before we display the data. These values are not reported by most VR hardware as yet, so the code would throw an error if we did not do this (the arrays return null if they are not successfully reported).

+ +
  posStats.textContent = 'Position: x ' + pos[0].toFixed(3) + ', y ' + pos[1].toFixed(3) + ', z ' + pos[2].toFixed(3);
+  orientStats.textContent = 'Orientation: x ' + orient[0].toFixed(3) + ', y ' + orient[1].toFixed(3) + ', z ' + orient[2].toFixed(3);
+  linVelStats.textContent = 'Linear velocity: x ' + linVel[0].toFixed(3) + ', y ' + linVel[1].toFixed(3) + ', z ' + linVel[2].toFixed(3);
+  angVelStats.textContent = 'Angular velocity: x ' + angVel[0].toFixed(3) + ', y ' + angVel[1].toFixed(3) + ', z ' + angVel[2].toFixed(3);
+
+  if(linAcc) {
+    linAccStats.textContent = 'Linear acceleration: x ' + linAcc[0].toFixed(3) + ', y ' + linAcc[1].toFixed(3) + ', z ' + linAcc[2].toFixed(3);
+  } else {
+    linAccStats.textContent = 'Linear acceleration not reported';
+  }
+
+  if(angAcc) {
+    angAccStats.textContent = 'Angular acceleration: x ' + angAcc[0].toFixed(3) + ', y ' + angAcc[1].toFixed(3) + ', z ' + angAcc[2].toFixed(3);
+  } else {
+    angAccStats.textContent = 'Angular acceleration not reported';
+  }
+}
+ +

WebVR events

+ +

The WebVR spec features a number of events that are fired, allowing our app code to react to changes in the state of the VR display (see Window events). For example:

+ + + +

To demonstrate how they work, our simple demo includes the following example:

+ +
window.addEventListener('vrdisplaypresentchange', function(e) {
+  console.log('Display ' + e.display.displayId + ' presentation has changed. Reason given: ' + e.reason + '.');
+});
+ +

As you can see, the {{domxref("VRDisplayEvent", "event object")}} provides two useful properties — {{domxref("VRDisplayEvent.display")}}, which contains a reference to the {{domxref("VRDisplay")}} the event was fired in response to, and {{domxref("VRDisplayEvent.reason")}}, which contains a human-readable reason why the event was fired.

+ +

This is a very useful event; you could use it to handle cases where the display gets disconnected unexpectedly, stopping errors from being thrown and making sure the user is aware of the situation. In Google's Webvr.info presentation demo, the event is used to run an onVRPresentChange() function, which updates the UI controls as appropriate and resizes the canvas.

+ +

Summary

+ +

This article has given you the very basics of how to create a simple WebVR 1.1 app, to help you get started.

diff --git a/files/pt-br/web/api/window/alert/index.html b/files/pt-br/web/api/window/alert/index.html new file mode 100644 index 0000000000..028eba5e6c --- /dev/null +++ b/files/pt-br/web/api/window/alert/index.html @@ -0,0 +1,47 @@ +--- +title: Window.alert +slug: Web/API/Window/alert +translation_of: Web/API/Window/alert +--- +

{{ APIRef }}

+ +

O método Window.alert() mostra uma caixa de diálogo de aviso com o conteúdo opcionalmente especificado e um botão OK.

+ +

Sintaxe

+ +
window.alert(message);
+ + + +

Exemplo

+ +
window.alert("Hello world!");
+
+ +

resulta em:

+ +

Image:AlertHelloWorld.png

+ +

Notas

+ +

A caixa de diálogo de aviso deve ser utilizada para mensagens que não requeiram nenhuma resposta da parte do usuário, a não ser o reconhecimento da mensagem.

+ +

The following text is shared between this article, DOM:window.prompt and DOM:window.confirmCaixas de diálogo são janelas modais - elas evitam que o usuário acesse o resto da interface do programa sem ter fechado a caixa de diálogo. Por essa razão, você não deve utilizar excessivamente nenhuma função que crie caixas de diálogo (ou janelas modais).

+ +

Usuários do Chrome (por exemplo, em extensões) devem utilizar os métodos da interface {{interface("nsIPromptService")}} como alternativa.

+ +

{{gecko_minversion_inline("23.0")}} O argumento agora é opcional conforme exigido na especificação.

+ +

Especificação

+ +

Especificado no HTML5.

+ +

Ver também

+ + diff --git a/files/pt-br/web/api/window/applicationcache/index.html b/files/pt-br/web/api/window/applicationcache/index.html new file mode 100644 index 0000000000..d4210a0543 --- /dev/null +++ b/files/pt-br/web/api/window/applicationcache/index.html @@ -0,0 +1,33 @@ +--- +title: Window.applicationCache +slug: Web/API/Window/applicationCache +translation_of: Web/API/Window/applicationCache +--- +

{{APIRef}}

+ +

Sumário

+ +

Returna uma referência para o objeto de cache da janela.

+ +

Sintaxe

+ +
cache = window.applicationCache
+
+ +

Parâmetros

+ + + +

Especificação

+ + + +

Veja também

+ + diff --git a/files/pt-br/web/api/window/closed/index.html b/files/pt-br/web/api/window/closed/index.html new file mode 100644 index 0000000000..a7f65aff5f --- /dev/null +++ b/files/pt-br/web/api/window/closed/index.html @@ -0,0 +1,59 @@ +--- +title: Window.closed +slug: Web/API/Window/closed +translation_of: Web/API/Window/closed +--- +
{{APIRef}}
+ +

Sumário

+ +

Essa propriedade (read-only) indica se a janela referenciada está ou não fechada.

+ +

Sintaxe

+ +
isClosed = windowRef.closed;
+
+ +
+
isClosed
+
Um booleano. Valores possíveis: +
    +
  • true: A janela foi fechada.
  • +
  • false: A janela está aberta.
  • +
+
+
+ +

Exemplos

+ +

Mudar a URL de uma janela a partir de um popup

+ +

O seguinte exemplo demonstra com uma janela de popup pode alterar a URL da janela que abriu ela. Antes de tentarmos mudar a URL da janela que a abriu, verificamos se a janela atual tem uma janela pai que a abriu usando a propriedade window.opener e que esta não está fechada:

+ +
// Verifique se o opener existe e não está fechado
+if (window.opener && !window.opener.closed) {
+  window.opener.location.href = "http://www.mozilla.org";
+}
+ +

Note que popups podem somente acessar a janela que os abriu.

+ +

Atualizando um popup anteriormente aberto

+ +

Neste exemplo, a função refreshPopupWindow() chama o método reload do objeto location do popup para atualizar seus dados. Se o popup não foi aberto ainda ou o usuário o fechou,  uma nova janela é aberta.

+ +
var popupWindow = null;
+
+function refreshPopupWindow() {
+  if (popupWindow && !popupWindow.closed) {
+    // popupWindow está aberto, atualize-o
+    popupWindow.location.reload(true);
+  } else {
+    // Abra uma nova janela de popup
+    popupWindow = window.open("popup.html","dataWindow");
+  }
+}
+
+ +

Especificação

+ +

HTML5

diff --git a/files/pt-br/web/api/window/confirm/index.html b/files/pt-br/web/api/window/confirm/index.html new file mode 100644 index 0000000000..e3ced2de5a --- /dev/null +++ b/files/pt-br/web/api/window/confirm/index.html @@ -0,0 +1,49 @@ +--- +title: Window.confirm() +slug: Web/API/Window/confirm +translation_of: Web/API/Window/confirm +--- +
{{ApiRef("Window")}}
+ +

O método Window.confirm() mostra uma janela modal com uma mensagem opcional e dois botões, OK e Cancelar.

+ +

Sintaxe

+ +
resultado = window.confirm(mensagem);
+
+ + + +

Exemplo

+ +
if (window.confirm("Você realmente quer sair?")) {
+  window.open("sair.html", "Obrigado pela visita!");
+}
+
+ +

Produzirá:

+ +

firefox confirm
+  

+ +

Notas

+ +

The following text is shared between this article, DOM:window.prompt and DOM:window.alert Caixas de diálogo são janelas modais - elas previnem o usuário de acessar o resto da interface da aplicação enquanto a caixa de diálogo não for fechada. Por esta razão, você não deve usar abusivamente nenhuma função que crie uma caixa de diálogo (ou uma janela modal). E independente disso, existem boas razões para evitar o uso de caixas de diálogo para confirmações.

+ +

Usuários do Mozilla Chrome (Ex.: Extensões do Firefox) devem utilizar métodos de {{interface("nsIPromptService")}}.

+ +

{{gecko_minversion_inline("23.0")}}O argumento é opcional e não é requerido por especificações.

+ +

Especificação

+ +

Especificado em HTML5.

+ +

Veja Também

+ + diff --git a/files/pt-br/web/api/window/crypto/index.html b/files/pt-br/web/api/window/crypto/index.html new file mode 100644 index 0000000000..d303c9dd74 --- /dev/null +++ b/files/pt-br/web/api/window/crypto/index.html @@ -0,0 +1,128 @@ +--- +title: Window.crypto +slug: Web/API/Window/crypto +tags: + - API + - HTML DOM + - Janela + - NeedsCompatTable + - Propriedade + - Referencia + - Window +translation_of: Web/API/Window/crypto +--- +
{{APIRef}}
+ +

{{domxref("Window.crypto")}} propriedade somente de leitura, devolve um objeto do tipo {{domxref("Crypto")}} associado ao objeto global. Este objeto permite que páginas da web utilizem recursos de criptografia.

+ +

Sintaxe

+ +
var cryptoObj = window.crypto || window.msCrypto; // for IE 11
+
+ +

Exemplo

+ +

Usando a propriedade {{domxref("Window.crypto")}}  para acessar o método getRandomValues().

+ +

JavaScript

+ +
genRandomNumbers = function getRandomNumbers() {
+  var array = new Uint32Array(10);
+  window.crypto.getRandomValues(array);
+
+  var randText = document.getElementById("myRandText");
+  randText.innerHTML = "The random numbers are: "
+  for (var i = 0; i < array.length; i++) {
+    randText.innerHTML += array[i] + " ";
+  }
+}
+ +

HTML

+ +
<p id="myRandText">The random numbers are: </p>
+<button type="button" onClick='genRandomNumbers()'>Generate 10 random numbers</button>
+ +

Resultado

+ +

{{ EmbedLiveSample('Example') }}

+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName("Web Crypto API", "#dfn-GlobalCrypto", "Window.crypto")}}{{Spec2("Web Crypto API")}}Definição inicial.
+ +

Compatibilidade de Browser

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeEdgeFirefox (Gecko)Internet ExplorerEdgeOperaSafari
Suporte básico44 {{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}11 {{property_prefix("ms")}}2019{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChrome for AndroidEdgeFirefox MobileFirefox OSIE PhoneOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/window/document/index.html b/files/pt-br/web/api/window/document/index.html new file mode 100644 index 0000000000..f7cfc4d860 --- /dev/null +++ b/files/pt-br/web/api/window/document/index.html @@ -0,0 +1,56 @@ +--- +title: Window.document +slug: Web/API/Window/document +tags: + - API + - DOM HTML + - NeedsCompatTable + - NeedsExample + - NeedsMarkupWork + - NeedsSpecTable + - Propriedade + - Referencia + - Window +translation_of: Web/API/Window/document +--- +
{{APIRef}}
+ +

Resumo

+ +

Retorna a referência para o documento contido na janela.

+ +
Nota: {{Fx_minversion_inline(3)}} Firefox 3 altera a segurança para documentos de uma janela de modo que apenas o domínio a partir do qual foi localizado possa acessar o documento. Enquanto isso pode quebrar alguns sites existentes, é um movimento feito por ambos Firefox 3 e Internet Explorer 7, e resulta na melhoria de segurança.
+ +

Sintaxe

+ +
doc = window.document
+
+ +

Parâmetros

+ + + +

Exemplo

+ +
<!DOCTYPE html>
+<html>
+<head>
+   <title>Hello, World!</title>
+</head>
+<body>
+
+<script type="text/javascript">
+   var doc = window.document;
+   alert( doc.title);    // alerts: Hello, World!
+</script>
+
+</body>
+</html>
+ +

Especificação

+ + diff --git a/files/pt-br/web/api/window/event/index.html b/files/pt-br/web/api/window/event/index.html new file mode 100644 index 0000000000..49452c20de --- /dev/null +++ b/files/pt-br/web/api/window/event/index.html @@ -0,0 +1,72 @@ +--- +title: Window.event +slug: Web/API/Window/event +translation_of: Web/API/Window/event +--- +

{{APIRef}}

+ +

{{ Non-standard_header() }}

+ +

window.event é uma propriedade proprietária do Microsoft Internet Explorer que só está disponível enquanto um manipulador de eventos DOM é chamado. Seu valor é o objeto Event atualmente tratado.

+ +

Especificações

+ +

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

+ +

Microsoft tem uma descrição na MSDN.

+ +

Compatibilidade de navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Suporte básico{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/window/fullscreen/index.html b/files/pt-br/web/api/window/fullscreen/index.html new file mode 100644 index 0000000000..666b763bf5 --- /dev/null +++ b/files/pt-br/web/api/window/fullscreen/index.html @@ -0,0 +1,44 @@ +--- +title: Window.fullScreen +slug: Web/API/Window/fullScreen +translation_of: Web/API/Window/fullScreen +--- +
{{APIRef}}
+ +

Sumário

+ +

Esta propriedade indica se a janela está sendo exibida em modo de tela cheia ("full screen") ou não. Ela é confiável apenas no Gecko 1.9 (Firefox 3) e posteriores, veja as  Notas abaixo.

+ +

Sintaxe

+ +
isInFullScreen = windowRef.fullScreen;
+
+ +

Com "chrome privileges" (privilégios para acesso a funções de baixo nível), a propriedade é de leitura e escrita, caso contrário é de apenas leitura. Tenha em mente que se você tentar definir esta propriedade sem chrome privileges, isto não irá gerar uma excessão; ao invés disto, irá simples e silenciosamente falhar. Isto é para prevenir que scripts projetados para definir esta propriedade no Internet Explorer se quebrem.

+ +

Valor de Retorno

+ +
+
isInFullScreen
+
Um booleano. Valores possíveis:
+
+ + + +

Exemplos

+ +

{{todo}}

+ +

Especificação

+ +

DOM Level 0. window.fullScreen não é parte de nenhuma especificação do W3C ou recomendação técnica.

+ +

Notas

+ + diff --git a/files/pt-br/web/api/window/getselection/index.html b/files/pt-br/web/api/window/getselection/index.html new file mode 100644 index 0000000000..7afcb23ef6 --- /dev/null +++ b/files/pt-br/web/api/window/getselection/index.html @@ -0,0 +1,129 @@ +--- +title: Window.getSelection() +slug: Web/API/Window/getSelection +translation_of: Web/API/Window/getSelection +--- +
{{ ApiRef() }}
+ +

Resumo

+ +

Retorna um objeto {{domxref("Selection")}} representando a parte do texto selecionada pelo usuário ou a posição atual do cursor.

+ +

Syntax

+ +
selection = window.getSelection();
+ + + +

Example

+ +
function foo() {
+    var selObj = window.getSelection();
+    alert(selObj);
+    var selRange = selObj.getRangeAt(0);
+    // do stuff with the range
+}
+ +

Nota

+ +

Representação do objeto Selection em String

+ +

No  JavaScript, quando um objeto é passado para uma função que espera uma string (como {{ Domxref("window.alert()") }} ou {{ Domxref("document.write()") }}), o método {{jsxref("Object.toString", "toString()")}} do objeto é chamado e o valor retornado é passado para a função. Isso pode fazer com que o objeto pareça ser uma string quando usado com outras funções quando na verdade é um objeto com propriedades e métodos.

+ +

No exemplo acima, selObj.toString() é chamado automaticamente quando é passado para {{domxref("window.alert()")}}. Contudo,  tentar usar propriedades ou métodos do objeto JavaScript String como length ou substr diretamente no objeto {{domxref("Selection")}} resultará em erro se o objeto não possuir essa propriedade ou método e pode retornar valores inesperados mesmo se os tiver. Para usar um objecto Selection como uma string, faça a chamada do seu método toString() diretamente:

+ +
var selectedText = selObj.toString();
+ + + +

Objectos Relacionados

+ +

É útil também notar que você pode chamar {{domxref("Document.getSelection()")}},  que funciona de forma idêntica.

+ +

Inputs HTML provêm APIs mais simples para se trabalhar com seleções (veja {{domxref("HTMLInputElement.setSelectionRange()")}}).

+ +

Note a diferença entre selection e focus. {{domxref("Document.activeElement")}} retorna o elemento com foco.

+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName("HTML Editing", "#dom-window-getselection", "Window.getSelection()")}}{{Spec2("HTML Editing")}}Definição inicial
+ +

Compatibilidade dos Browsers

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}9{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/window/history/index.html b/files/pt-br/web/api/window/history/index.html new file mode 100644 index 0000000000..cc96ab5be5 --- /dev/null +++ b/files/pt-br/web/api/window/history/index.html @@ -0,0 +1,52 @@ +--- +title: Window.history +slug: Web/API/Window/history +translation_of: Web/API/Window/history +--- +

{{ APIRef }}

+ +

A propriedade só de leitura Window.history retorna uma referência ao objeto History, que fornece uma interface para manipular o histórico de sessão do navegador (páginas visitadas na guia ou quadro em que a página atual é carregada).

+ +

Consulte Manipulação do histórico do navegador para obter exemplos e detalhes. Em particular, esse artigo explica os recursos de segurança dos métodos pushState () e replaceState () que você deve conhecer antes de usá-los.

+ +

Syntax

+ +
var historyObj = window.history;
+
+ +

Example

+ +
History.back (); // equivalente ao clique no botão Voltar
+History.go (-1); // equivalente a history.back ();
+
+ +

Notas

+ +


+ Para páginas de nível superior, você pode ver a lista de páginas no histórico da sessão, acessível através do objeto Histórico, nos menus suspensos do navegador ao lado dos botões para trás e para frente.

+ +

Por motivos de segurança, o objeto Histórico não permite que o código não privilegiado acesse os URLs de outras páginas no histórico da sessão, mas permite que ele navegue pelo histórico da sessão.

+ +

Não há nenhuma maneira de limpar o histórico da sessão ou desabilitar a navegação para trás / para frente do código não privilegiado. A solução disponível mais próxima é o método location.replace (), que substitui o item atual do histórico da sessão pelo URL fornecido.

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + +
EspecificaçõesStatusComentário
{{SpecName('HTML WHATWG', 'browsers.html#the-history-interface', 'The History interface')}}{{Spec2('HTML WHATWG')}} 
{{SpecName('HTML5 W3C', 'browsers.html#the-history-interface', 'The History interface')}}{{Spec2('HTML5 W3C')}} 
diff --git a/files/pt-br/web/api/window/index.html b/files/pt-br/web/api/window/index.html new file mode 100644 index 0000000000..45b7ce7759 --- /dev/null +++ b/files/pt-br/web/api/window/index.html @@ -0,0 +1,381 @@ +--- +title: Window +slug: Web/API/Window +translation_of: Web/API/Window +--- +

{{APIRef}}

+ +

O objeto window representa uma janela que contém um elemento DOM; a propriedade document aponta para o documento DOM document carregado naquela janela. Uma janela para um dado documento pode ser obtido usando a propriedade {{Domxref("document.defaultView")}}.

+ +

Esta seção provê uma breve referência a todos os métodos, propriedades e eventos disponíveis através do objeto DOM window. O objeto window implementa a interface Window, o qual herda da interface AbstractView. Algumas funções globais, objeto de namespace, interfaces e construtores, apesar de não tipicamente associados ao objeto em questão, estão disponíveis e estão listados nas referências JavaScript Reference e DOM Reference.

+ +

Em um navegador com suporte a abas, como o Firefox, cada aba contém seu próprio objeto window (e, se você estiver escrevendo uma extensão, a janela do navegador é uma janela distinta também - veja Working with windows in chrome code para mais informação). Isto é, o objeto window não é compartilhado entre as abas na mesma janela. Alguns métodos, nomeadamente {{Domxref("window.resizeTo")}} e {{Domxref("window.resizeBy")}} aplicam-se à janela toda e não à aba em questão ao que o objeto window pertence. Geralmente, qualquer coisa que não pode racionalmente pertencer a uma aba, pertence a uma janela..

+ +

Propriedades

+ +

Esta interface herda propriedades da interface {{domxref("EventTarget")}} e implementa propriedades de {{domxref("WindowTimers")}}, {{domxref("WindowBase64")}}, e {{domxref("WindowEventHandlers")}}.

+ +

Perceba que propriedades que são objetos (ex.: sobrecarregar o protótipo de elementos built-in) são listados em uma sessão separada abaixo.

+ +
+
{{domxref("Window.applicationCache")}}  {{readOnlyInline}} {{gecko_minversion_inline("1.9")}}
+
Um objeto {{domxref("OfflineResourceList")}} fornece acesso aos recursos offline para o window.
+
{{domxref("Window.closed")}} {{Non-standard_inline}}{{readOnlyInline}}
+
Esta propriedade indica quando a window atual está fechada ou não.
+
Window.Components {{Non-standard_inline}}
+
O ponto de entrada para muitas características XPCOM. Algumas propriedades, por exemplo, classes, estão apenas disponíveis para código suficientemente privilegiado. Código de Web não deve usar essa propriedade.
+
{{domxref("console","Window.console")}} {{Non-standard_inline}} {{ReadOnlyInline}}
+
Retorna uma referência para o objeto console fornecendo acesso ao console debugging do navegador.
+
{{domxref("Window.content")}} and Window._content {{Non-standard_inline}} {{obsolete_inline}}{{ReadOnlyInline}}
+
Retorna uma referência para o elemento de conteúdo na janela atual. A variante obsoleta com sublinhado não está disponível a partir do conteúdo da Web.
+
{{domxref("Window.controllers")}}{{non-standard_inline}}{{ReadOnlyInline}}
+
Retorna os objetos de controlador XUL para a janela atual do crome.
+
{{domxref("Window.crypto")}} {{readOnlyInline}}
+
Retorna o objeto de criptografia do navegador.
+
{{domxref("Window.defaultStatus")}} {{Obsolete_inline("gecko23")}}
+
Obtém/define o texto da barra de status para determinada janela.
+
{{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}}
+
Retorna a referência à propriedade document que a janela contém.
+
{{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}}
+
Retorna a referência ao objeto history.
+
{{domxref("Window.innerHeight")}}
+
Gets the height of the content area of the browser window including, if rendered, the horizontal scrollbar.
+
{{domxref("window.innerWidth")}}
+
Gets the width of the content area of the browser window including, if rendered, the vertical scrollbar.
+
{{domxref("Window.length")}} {{readOnlyInline}}
+
Returns the number of frames in the window. See also {{domxref("window.frames")}}.
+
{{domxref("Window.location")}} {{ReadOnlyInline}}
+
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("WindowStorage.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")}}
+
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")}}
+
Pega/attribui o nome ao objeto 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.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("WindowSession.sessionStorage")}} {{readOnlyInline}}
+
+
{{domxref("SpeechSynthesisGetter.speechSynthesis")}} {{readOnlyInline}}
+
+
{{domxref("Window.parent")}} {{readOnlyInline}}
+
Returns a reference to the parent of the current window or subframe.
+
{{domxref("Window.performance")}} {{readOnlyInline}}
+
Provides a hosting area for performance related attributes.
+
{{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")}}
+
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.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.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.
+
+ +

Methods

+ +

This interface inherits methods from the {{domxref("EventTarget")}} interface and implements methods from {{domxref("WindowTimers")}}, {{domxref("WindowBase64")}}, and {{domxref("WindowEventHandlers")}}.

+ +
+
{{domxref("EventTarget.addEventListener()")}}
+
Register an event handler to a specific event type on the window.
+
{{domxref("Window.alert()")}}
+
Displays an alert dialog.
+
{{domxref("WindowBase64.atob()")}}
+
Decodes a string of data which has been encoded using base-64 encoding.
+
{{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("WindowBase64.btoa()")}}
+
Creates a base-64 encoded ASCII string from a string of binary data.
+
{{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("WindowTimers.clearInterval()")}}
+
Cancels the repeated execution set using {{domxref("WindowTimers.setInterval()")}}.
+
{{domxref("WindowTimers.clearTimeout()")}}
+
Cancels the repeated execution set using {{domxref("WindowTimers.setTimeout()")}}.
+
{{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()")}}
+
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()")}}
+
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.getDefaulComputedStyle()")}}
+
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.mozRequestAnimationFrame()")}} {{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. This will cause a MozBeforePaint event to fire before that repaint occurs.
+
{{domxref("Window.open()")}}
+
Opens a new window.
+
{{domxref("Window.openDialog()")}}
+
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, in a secure manner.
+
{{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()")}} {{Deprecated_inline}}
+
Releases the window from trapping events of a specific type.
+
{{domxref("element.removeEventListener","Window.removeEventListener()")}}
+
Removes an event listener from the window.
+
{{domxref("Window.resizeBy()")}}
+
Resizes the current window by a certain amount.
+
{{domxref("Window.resizeTo()")}}
+
Dynamically resizes window.
+
{{domxref("Window.restore()")}}
+
{{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()")}}
+
Scrolls the document by the given number of lines.
+
{{domxref("Window.scrollByPages()")}}
+
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()")}}
+
Changes the cursor for the current window
+
{{domxref("Window.setImmediate()")}}
+
Executes a function after the browser has finished other heavy tasks
+
{{domxref("WindowTimers.setInterval()")}}
+
Schedules the execution of a function each X milliseconds.
+
{{domxref("Window.setResizable")}}
+
{{todo("NeedsContents")}}
+
{{domxref("WindowTimers.setTimeout()")}}
+
Sets a delay for executing a function.
+
{{domxref("Window.showModalDialog()")}} {{Fx_minversion_inline(3)}}
+
Displays a modal dialog.
+
{{domxref("Window.sizeToContent()")}}
+
Sizes the window according to its content.
+
{{domxref("Window.stop()")}}
+
This method stops window loading.
+
{{domxref("Window.updateCommands()")}}
+
Updates the state of commands of the current chrome window (UI).
+
+ +

Event handlers

+ +

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("WindowTimers")}}, {{domxref("WindowBase64")}}, and {{domxref("WindowEventHandlers")}}.

+ +
+

Note: 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")}}
+
An event handler property for abort events on the window.
+
{{domxref("WindowEventHandlers.onbeforeunload")}}
+
An event handler property for before-unload events on the window.
+
{{domxref("GlobalEventHandlers.onblur")}}
+
An event handler property for blur events on the window.
+
{{domxref("GlobalEventHandlers.onchange")}}
+
An event handler property for change events on the window.
+
{{domxref("GlobalEventHandlers.onclick")}}
+
An event handler property for click events on the window.
+
{{domxref("GlobalEventHandlers.onclose")}}
+
An event handler property for handling the window close event.
+
{{domxref("GlobalEventHandlers.oncontextmenu")}}
+
An event handler property for right-click events on the window.
+
{{domxref("Window.ondevicelight")}}
+
An event handler property for any ambient light levels changes
+
{{domxref("Window.ondevicemotion")}} {{gecko_minversion_inline("6.0")}}
+
{{todo("NeedsContents")}}
+
{{domxref("Window.ondeviceorientation")}} {{gecko_minversion_inline("6.0")}}
+
An event handler property for any device orientation changes
+
{{domxref("Window.ondeviceproximity")}}
+
An event handler property for device proximity event
+
{{domxref("GlobalEventHandlers.onerror")}}
+
An event handler property for {{event("error")}} events raised on the window.
+
{{domxref("GlobalEventHandlers.onfocus")}}
+
An event handler property for {{event("focus")}} events on the window.
+
{{domxref("WindowEventHandlers.onhashchange")}} {{gecko_minversion_inline("1.9.2")}}
+
An event handler property for hash change events on the window; called when the part of the URL after the hash mark ("#") changes.
+
{{domxref("GlobalEventHandlers.onkeydown")}}
+
An event handler property for {{event("keydown")}} events on the window.
+
{{domxref("GlobalEventHandlers.onkeypress")}}
+
An event handler property for {{event("keypress")}} events on the window.
+
{{domxref("GlobalEventHandlers.onkeyup")}}
+
An event handler property for {{event("keyup")}} events on the window.
+
{{domxref("WindowEventHandlers.onlanguagechange")}}
+
An event handler property for {{event("languagechange")}} events on the window.
+
{{domxref("GlobalEventHandlers.onload")}}
+
An event handler property for window loading.
+
{{domxref("GlobalEventHandlers.onmousedown")}}
+
An event handler property for mousedown events on the window.
+
{{domxref("GlobalEventHandlers.onmousemove")}}
+
An event handler property for mousemove events on the window.
+
{{domxref("GlobalEventHandlers.onmouseout")}}
+
An event handler property for mouseout events on the window.
+
{{domxref("GlobalEventHandlers.onmouseover")}}
+
An event handler property for mouseover events on the window.
+
{{domxref("GlobalEventHandlers.onmouseup")}}
+
An event handler property for mouseup events on the window.
+
{{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.onpageshow")}}
+
An event handler property for pageshow events on the window.
+
{{domxref("WindowEventHandlers.onpagehide")}}
+
An event handler property for pagehide events on the window.
+
{{domxref("Window.onpaint")}}
+
An event handler property for paint events on the window.
+
{{domxref("WindowEventHandlers.onpopstate")}} {{gecko_minversion_inline("2.0")}}
+
An event handler property for popstate events, which are fired when navigating to a session history entry representing a state object.
+
{{domxref("GlobalEventHandlers.onreset")}}
+
An event handler property for reset events on the window.
+
{{domxref("GlobalEventHandlers.onresize")}}
+
An event handler property for window resizing.
+
{{domxref("GlobalEventHandlers.onscroll")}}
+
An event handler property for window scrolling.
+
{{domxref("GlobalEventHandlers.onselect")}}
+
An event handler property for window selection.
+
{{domxref("GlobalEventHandlers.onsubmit")}}
+
An event handler property for submits on window forms.
+
{{domxref("Window.onunload")}}
+
An event handler property for unload events on the window.
+
{{domxref("Window.onuserproximity")}}
+
An event handler property for user proximity events
+
+ +

Constructors

+ +

See also the DOM Interfaces.

+ +
+
{{domxref("Window.DOMParser")}}
+
{{todo("NeedsContents")}}
+
{{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

+ +

See DOM Reference

+ +

See also

+ + diff --git a/files/pt-br/web/api/window/innerheight/index.html b/files/pt-br/web/api/window/innerheight/index.html new file mode 100644 index 0000000000..5caf8ae916 --- /dev/null +++ b/files/pt-br/web/api/window/innerheight/index.html @@ -0,0 +1,137 @@ +--- +title: Window.innerHeight +slug: Web/API/Window/innerHeight +translation_of: Web/API/Window/innerHeight +--- +
{{APIRef}}
+ +

Altura (em pixels) da janela de visualização do navegador, incluindo, se renderizado, a barra de rolagem horizontal.

+ +
Note: If you use {{ifmethod("nsIDOMWindowUtils", "setCSSViewport")}} to set the virtual window size for page layout purposes, the value returned by this property corresponds to the viewport height set using that method.
+ +

Syntax

+ +
var intViewportHeight = window.innerHeight;
+ +

Value

+ +

On return, intViewportHeight is the height of the browser window's viewport.

+ +

The window.innerHeight property is read only; it has no default value.

+ +

Notes

+ +

The innerHeight property is supported in any window object like a {{domxref("window")}}, a frame, a frameset, or a secondary window.

+ +

There is an algorithm to obtain the height of the viewport excluding, if rendered, the horizontal scrollbar.

+ +

Example

+ +

Assuming a frameset

+ +
var intFrameHeight = window.innerHeight; // or
+
+var intFrameHeight = self.innerHeight;
+// will return the height of the frame viewport within the frameset
+
+var intFramesetHeight = parent.innerHeight;
+// will return the height of the viewport of the closest frameset
+
+var intOuterFramesetHeight = top.innerHeight;
+// will return the height of the viewport of the outermost frameset
+
+ +

{{todo("link to an interactive demo here")}}

+ +

To change the size of a window, see {{domxref("window.resizeBy()")}} and {{domxref("window.resizeTo()")}}.

+ +

To get the outer height of a window, i.e. the height of the whole browser window, see {{domxref("window.outerHeight")}}.

+ +

Graphical example

+ +

The following figure shows the difference between outerHeight and innerHeight.

+ +

innerHeight vs outerHeight illustration

+ +

Specification

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSSOM View', '#dom-window-innerheight', 'window.innerHeight')}}{{Spec2('CSSOM View')}}Initial definition
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1{{CompatVersionUnknown}}{{CompatGeckoDesktop(1.0)}}[1]993
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support1{{CompatVersionUnknown}}{{CompatGeckoMobile(1.0)}}[1]993
+
+ +

[1] From Firefox 4 to 24 this property was buggy and could give a wrong value before page load on certain circumstances, see {{bug(641188)}}.

+ +

See also

+ + diff --git a/files/pt-br/web/api/window/length/index.html b/files/pt-br/web/api/window/length/index.html new file mode 100644 index 0000000000..b99fa5747a --- /dev/null +++ b/files/pt-br/web/api/window/length/index.html @@ -0,0 +1,52 @@ +--- +title: Window.length +slug: Web/API/Window/length +tags: + - API + - DOM + - Gecko + - Propriedade + - Referencia + - Referência do DOM + - Referência do DOM do Gecko + - WebAPI + - Window +translation_of: Web/API/Window/length +--- +
{{ ApiRef() }}
+ +

Resumo

+ +

Retorna o número de frames (tanto elementos frame ou iframe) dentro da janela.

+ +

Sintaxe

+ +
quantidadeFrames = window.length;
+
+ + + +

Exemplo

+ +
if (window.length) {
+  // este é um documento com subframes
+}
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG','browsers.html#dom-length','Window.length')}}{{Spec2('HTML WHATWG')}} 
diff --git a/files/pt-br/web/api/window/location/index.html b/files/pt-br/web/api/window/location/index.html new file mode 100644 index 0000000000..09198523b3 --- /dev/null +++ b/files/pt-br/web/api/window/location/index.html @@ -0,0 +1,272 @@ +--- +title: Window.location +slug: Web/API/Window/location +translation_of: Web/API/Window/location +--- +

{{APIRef}}

+ +

O Window.location é uma propriedade de leitura que retorna um objeto {{domxref("Location")}} com informações de localização do documento atual.
+
+ Embora Window.location seja apenas um objeto de leitura de localização, você pode também atribuir uma {{domxref("DOMString")}} para ele. Isto significa que você pode trabalhar com location como se fosse uma string na maioria dos casos: location = 'http://www.exemplo.com' é um sinônimo de location.href = 'http://www.exemplo.com'.

+ +

Sintaxe

+ +
var oldLocation = location;
+location = newLocation;
+
+ +

Exemplos

+ +

Exemplo básico

+ +
alert(location); // alerta "https://developer.mozilla.org/en-US/docs/Web/API/Window.location"
+ +

Exemplo #1: Navegando para uma nova página

+ +

Sempre que um novo valor é atribuído a um objeto de localização, um documento será carregado usando a URL como se location.assign() tivesse sido chamado com a URL modificada. Observe que as configurações de segurança, como CORS, pode impedir que isso aconteça de forma eficaz.

+ +
location.assign("http://www.mozilla.org"); // ou
+location = "http://www.mozilla.org";
+
+ +

Exemplo #2: Forçando recerregamento da página atual do servidor

+ +
location.reload(true);
+ +

Exemplo #3

+ +

Considere o exemplo a seguir, que vai recarregar a página usando o método replace() para inserir o valor do location.pathname depois da hash:

+ +
function reloadPageWithHash() {
+  var initialPage = location.pathname;
+  location.replace('http://example.com/#' + initialPage);
+}
+
+ +
Nota: O exemplo acima funciona em situações onde location.hash não precisa ser retida. Contudo, em navegadores baseados em Gecko, definindo location.pathname desta forma irá apagar qualquer informação em location.hash, enquanto que no WebKit(e possivelmente em outro navegador), definir o pathname não vai alterar  o hash. Se você precisa mudar o pathname mas manter o hash como é, use o método replace(), que deve funcionar de forma consistente em todos os navegadores.
+ +

Exemplo #4: Mostrar as propriedades da URL atual em um alerta:

+ +
function showLoc() {
+  var oLocation = location, aLog = ["Property (Typeof): Value", "location (" + (typeof oLocation) + "): " + oLocation ];
+  for (var sProp in oLocation){
+    aLog.push(sProp + " (" + (typeof oLocation[sProp]) + "): " +  (oLocation[sProp] || "n/a"));
+  }
+  alert(aLog.join("\n"));
+}
+
+// no html: <button onclick="showLoc();">Mostrar propriedades de localização</button>
+
+ + + +
function sendData (sData) {
+  location.search = sData;
+}
+
+// no html: <button onclick="sendData('Algum dado');">Enviar dados</button>
+
+ +

A URL atual com "?Some%20data" anexada é enviada para o servidor (se nenhuma ação for captada pelo servidor, o documento atual é recarregado com o a linha de pesquisa modificada).

+ +

Exemplo #6: Usando favoritos sem mudar a propriedade hash:

+ +
<!doctype html>
+<html>
+<head>
+<meta charset="UTF-8"/>
+<title>MDN Exemplo</title>
+<script>
+function showNode (oNode) {
+  var nLeft = 0, nTop = 0;
+  for (var oItNode = oNode; oItNode; nLeft += oItNode.offsetLeft, nTop += oItNode.offsetTop, oItNode = oItNode.offsetParent);
+  document.documentElement.scrollTop = nTop;
+  document.documentElement.scrollLeft = nLeft;
+}
+
+function showBookmark (sBookmark, bUseHash) {
+  if (arguments.length === 1 || bUseHash) { location.hash = sBookmark; return; }
+  var oBookmark = document.querySelector(sBookmark);
+  if (oBookmark) { showNode(oBookmark); }
+}
+</script>
+<style>
+span.intLink {
+    cursor: pointer;
+    color: #0000ff;
+    text-decoration: underline;
+}
+</style>
+</head>
+
+<body>
+<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam ultrices dolor ac dolor imperdiet ullamcorper. Suspendisse quam libero, luctus auctor mollis sed, malesuada condimentum magna. Quisque in ante tellus, in placerat est. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Donec a mi magna, quis mattis dolor. Etiam sit amet ligula quis urna auctor imperdiet nec faucibus ante. Mauris vel consectetur dolor. Nunc eget elit eget velit pulvinar fringilla consectetur aliquam purus. Curabitur convallis, justo posuere porta egestas, velit erat ornare tortor, non viverra justo diam eget arcu. Phasellus adipiscing fermentum nibh ac commodo. Nam turpis nunc, suscipit a hendrerit vitae, volutpat non ipsum.</p>
+<p>Duis lobortis sapien quis nisl luctus porttitor. In tempor semper libero, eu tincidunt dolor eleifend sit amet. Ut nec velit in dolor tincidunt rhoncus non non diam. Morbi auctor ornare orci, non euismod felis gravida nec. Curabitur elementum nisi a eros rutrum nec blandit diam placerat. Aenean tincidunt risus ut nisi consectetur cursus. Ut vitae quam elit. Donec dignissim est in quam tempor consequat. Aliquam aliquam diam non felis convallis suscipit. Nulla facilisi. Donec lacus risus, dignissim et fringilla et, egestas vel eros. Duis malesuada accumsan dui, at fringilla mauris bibendum quis. Cras adipiscing ultricies fermentum. Praesent bibendum condimentum feugiat.</p>
+<p id="myBookmark1">[&nbsp;<span class="intLink" onclick="showBookmark('#myBookmark2');">Go to bookmark #2</span>&nbsp;]</p>
+<p>Vivamus blandit massa ut metus mattis in fringilla lectus imperdiet. Proin ac ante a felis ornare vehicula. Fusce pellentesque lacus vitae eros convallis ut mollis magna pellentesque. Pellentesque placerat enim at lacus ultricies vitae facilisis nisi fringilla. In tincidunt tincidunt tincidunt. Nulla vitae tempor nisl. Etiam congue, elit vitae egestas mollis, ipsum nisi malesuada turpis, a volutpat arcu arcu id risus.</p>
+<p>Nam faucibus, ligula eu fringilla pulvinar, lectus tellus iaculis nunc, vitae scelerisque metus leo non metus. Proin mattis lobortis lobortis. Quisque accumsan faucibus erat, vel varius tortor ultricies ac. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nec libero nunc. Nullam tortor nunc, elementum a consectetur et, ultrices eu orci. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque a nisl eu sem vehicula egestas.</p>
+<p>Aenean viverra varius mauris, sed elementum lacus interdum non. Phasellus sit amet lectus vitae eros egestas pellentesque fermentum eget magna. Quisque mauris nisl, gravida vitae placerat et, condimentum id metus. Nulla eu est dictum dolor pulvinar volutpat. Pellentesque vitae sollicitudin nunc. Donec neque magna, lobortis id egestas nec, sodales quis lectus. Fusce cursus sollicitudin porta. Suspendisse ut tortor in mauris tincidunt rhoncus. Maecenas tincidunt fermentum facilisis. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p>
+<p>Suspendisse turpis nisl, consectetur in lacinia ut, ornare vel mi. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin non lectus eu turpis vulputate cursus. Mauris interdum tincidunt erat id pharetra. Nullam in libero elit, sed consequat lectus. Morbi odio nisi, porta vitae molestie ut, gravida ut nunc. Ut non est dui, id ullamcorper orci. Praesent vel elementum felis. Maecenas ornare, dui quis auctor hendrerit, turpis sem ullamcorper odio, in auctor magna metus quis leo. Morbi at odio ante.</p>
+<p>Curabitur est ipsum, porta ac viverra faucibus, eleifend sed eros. In sit amet vehicula tortor. Vestibulum viverra pellentesque erat a elementum. Integer commodo ultricies lorem, eget tincidunt risus viverra et. In enim turpis, porttitor ac ornare et, suscipit sit amet nisl. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Pellentesque vel ultrices nibh. Sed commodo aliquam aliquam. Nulla euismod, odio ut eleifend mollis, nisi dui gravida nibh, vitae laoreet turpis purus id ipsum. Donec convallis, velit non scelerisque bibendum, diam nulla auctor nunc, vel dictum risus ipsum sit amet est. Praesent ut nibh sit amet nibh congue pulvinar. Suspendisse dictum porttitor tempor.</p>
+<p>Vestibulum dignissim erat vitae lectus auctor ac bibendum eros semper. Integer aliquet, leo non ornare faucibus, risus arcu tristique dolor, a aliquet massa mauris quis arcu. In porttitor, lectus ac semper egestas, ligula magna laoreet libero, eu commodo mauris odio id ante. In hac habitasse platea dictumst. In pretium erat diam, nec consequat eros. Praesent augue mi, consequat sed porttitor at, volutpat vitae eros. Sed pretium pharetra dapibus. Donec auctor interdum erat, lacinia molestie nibh commodo ut. Maecenas vestibulum vulputate felis, ut ullamcorper arcu faucibus in. Curabitur id arcu est. In semper mollis lorem at pellentesque. Sed lectus nisl, vestibulum id scelerisque eu, feugiat et tortor. Pellentesque porttitor facilisis ultricies.</p>
+<p id="myBookmark2">[&nbsp;<span class="intLink" onclick="showBookmark('#myBookmark1');">Go to bookmark #1</span> | <span class="intLink" onclick="showBookmark('#myBookmark1', false);">Go to bookmark #1 without using location.hash</span> | <span class="intLink" onclick="showBookmark('#myBookmark3');">Go to bookmark #3</span>&nbsp;]</p>
+<p>Phasellus tempus fringilla nunc, eget sagittis orci molestie vel. Nulla sollicitudin diam non quam iaculis ac porta justo venenatis. Quisque tellus urna, molestie vitae egestas sit amet, suscipit sed sem. Quisque nec lorem eu velit faucibus tristique ut ut dolor. Cras eu tortor ut libero placerat venenatis ut ut massa. Sed quis libero augue, et consequat libero. Morbi rutrum augue sed turpis elementum sed luctus nisl molestie. Aenean vitae purus risus, a semper nisl. Pellentesque malesuada, est id sagittis consequat, libero mauris tincidunt tellus, eu sagittis arcu purus rutrum eros. Quisque eget eleifend mi. Duis pharetra mi ac eros mattis lacinia rutrum ipsum varius.</p>
+<p>Fusce cursus pulvinar aliquam. Duis justo enim, ornare vitae elementum sed, porta a quam. Aliquam eu enim eu libero mollis tempus. Morbi ornare aliquam posuere. Proin faucibus luctus libero, sed ultrices lorem sagittis et. Vestibulum malesuada, ante nec molestie vehicula, quam diam mollis ipsum, rhoncus posuere mauris lectus in eros. Nullam feugiat ultrices augue, ac sodales sem mollis in.</p>
+<p id="myBookmark3"><em>Here is the bookmark #3</em></p>
+<p>Proin vitae sem non lorem pellentesque molestie. Nam tempus massa et turpis placerat sit amet sollicitudin orci sodales. Pellentesque enim enim, sagittis a lobortis ut, tempus sed arcu. Aliquam augue turpis, varius vel bibendum ut, aliquam at diam. Nam lobortis, dui eu hendrerit pellentesque, sem neque porttitor erat, non dapibus velit lectus in metus. Vestibulum sit amet felis enim. In quis est vitae nunc malesuada consequat nec nec sapien. Suspendisse aliquam massa placerat dui lacinia luctus sed vitae risus. Fusce tempus, neque id ultrices volutpat, mi urna auctor arcu, viverra semper libero sem vel enim. Mauris dictum, elit non placerat malesuada, libero elit euismod nibh, nec posuere massa arcu eu risus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer urna velit, dapibus eget varius feugiat, pellentesque sit amet ligula. Maecenas nulla nisl, facilisis eu egestas scelerisque, mollis eget metus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Morbi sed congue mi.</p>
+<p>Fusce metus velit, pharetra at vestibulum nec, facilisis porttitor mi. Curabitur ligula sapien, fermentum vel porttitor id, rutrum sit amet magna. Sed sit amet sollicitudin turpis. Aenean luctus rhoncus dolor, et pulvinar ante egestas et. Donec ac massa orci, quis dapibus augue. Vivamus consectetur auctor pellentesque. Praesent vestibulum tincidunt ante sed consectetur. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Fusce purus metus, imperdiet vitae iaculis convallis, bibendum vitae turpis.</p>
+<p>Fusce aliquet molestie dolor, in ornare dui sodales nec. In molestie sollicitudin felis a porta. Mauris nec orci sit amet orci blandit tristique congue nec nunc. Praesent et tellus sollicitudin mauris accumsan fringilla. Morbi sodales, justo eu sollicitudin lacinia, lectus sapien ullamcorper eros, quis molestie urna elit bibendum risus. Proin eget tincidunt quam. Nam luctus commodo mauris, eu posuere nunc luctus non. Nulla facilisi. Vivamus eget leo rhoncus quam accumsan fringilla. Aliquam sit amet lorem est. Nullam vel tellus nibh, id imperdiet orci. Integer egestas leo eu turpis blandit scelerisque.</p>
+<p>Etiam in blandit tellus. Integer sed varius quam. Vestibulum dapibus mi gravida arcu viverra blandit. Praesent tristique augue id sem adipiscing pellentesque. Sed sollicitudin, leo sed interdum elementum, nisi ante condimentum leo, eget ornare libero diam semper quam. Vivamus augue urna, porta eget ultrices et, dapibus ut ligula. Ut laoreet consequat faucibus. Praesent at lectus ut lectus malesuada mollis. Nam interdum adipiscing eros, nec sodales mi porta nec. Proin et quam vitae sem interdum aliquet. Proin vel odio at lacus vehicula aliquet.</p>
+<p>Etiam placerat dui ut sem ornare vel vestibulum augue mattis. Sed semper malesuada mi, eu bibendum lacus lobortis nec. Etiam fringilla elementum risus, eget consequat urna laoreet nec. Etiam mollis quam non sem convallis vel consectetur lectus ullamcorper. Aenean mattis lacus quis ligula mattis eget vestibulum diam hendrerit. In non placerat mauris. Praesent faucibus nunc quis eros sagittis viverra. In hac habitasse platea dictumst. Suspendisse eget nisl erat, ac molestie massa. Praesent mollis vestibulum tincidunt. Fusce suscipit laoreet malesuada. Aliquam erat volutpat. Aliquam dictum elementum rhoncus. Praesent in est massa, pulvinar sodales nunc. Pellentesque gravida euismod mi ac convallis.</p>
+<p>Mauris vel odio vel nulla facilisis lacinia. Aliquam ultrices est at leo blandit tincidunt. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Suspendisse porttitor adipiscing facilisis. Duis cursus quam iaculis augue interdum porttitor. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Duis vulputate magna ac metus pretium condimentum. In tempus, est eget vestibulum blandit, velit massa dignissim nisl, ut scelerisque lorem neque vel velit. Maecenas fermentum commodo viverra. Curabitur a nibh non velit aliquam cursus. Integer semper condimentum tortor a pellentesque. Pellentesque semper, nisl id porttitor vehicula, sem dui feugiat lacus, vitae consequat augue urna vel odio.</p>
+<p>Vestibulum id neque nec turpis iaculis pulvinar et a massa. Vestibulum sed nibh vitae arcu eleifend egestas. Mauris fermentum ultrices blandit. Suspendisse vitae lorem libero. Aenean et pellentesque tellus. Morbi quis neque orci, eu dignissim dui. Fusce sollicitudin mauris ac arcu vestibulum imperdiet. Proin ultricies nisl sit amet enim imperdiet eu ornare dui tempus. Maecenas lobortis nisi a tortor vestibulum vel eleifend tellus vestibulum. Donec metus sapien, hendrerit a fermentum id, dictum quis libero.</p>
+<p>Pellentesque a lorem nulla, in tempor justo. Duis odio nisl, dignissim sed consequat sit amet, hendrerit ac neque. Nunc ac augue nec massa tempor rhoncus. Nam feugiat, tellus a varius euismod, justo nisl faucibus velit, ut vulputate justo massa eu nibh. Sed bibendum urna quis magna facilisis in accumsan dolor malesuada. Morbi sit amet nunc risus, in faucibus sem. Nullam sollicitudin magna sed sem mollis id commodo libero condimentum. Duis eu massa et lacus semper molestie ut adipiscing sem.</p>
+<p>Sed id nulla mi, eget suscipit eros. Aliquam tempus molestie rutrum. In quis varius elit. Nullam dignissim neque nec velit vulputate porttitor. Mauris ac ligula sit amet elit fermentum rhoncus. In tellus urna, pulvinar quis condimentum ut, porta nec justo. In hac habitasse platea dictumst. Proin volutpat elit id quam molestie ac commodo lacus sagittis. Quisque placerat, augue tempor placerat pulvinar, nisi nisi venenatis urna, eget convallis eros velit quis magna. Suspendisse volutpat iaculis quam, ut tristique lacus luctus quis.</p>
+<p>Nullam commodo suscipit lacus non aliquet. Phasellus ac nisl lorem, sed facilisis ligula. Nam cursus lobortis placerat. Sed dui nisi, elementum eu sodales ac, placerat sit amet mauris. Pellentesque dapibus tellus ut ipsum aliquam eu auctor dui vehicula. Quisque ultrices laoreet erat, at ultrices tortor sodales non. Sed venenatis luctus magna, ultricies ultricies nunc fringilla eget. Praesent scelerisque urna vitae nibh tristique varius consequat neque luctus. Integer ornare, erat a porta tempus, velit justo fermentum elit, a fermentum metus nisi eu ipsum. Vivamus eget augue vel dui viverra adipiscing congue ut massa. Praesent vitae eros erat, pulvinar laoreet magna. Maecenas vestibulum mollis nunc in posuere. Pellentesque sit amet metus a turpis lobortis tempor eu vel tortor. Cras sodales eleifend interdum.</p>
+</body>
+</html>
+
+ +
Nota: A função showNode é também um exemplo de uso do ciclo for sem uma section statement. Neste  caso o ponto e vírgula é sempre colocado imediatamente depois da declaração do ciclo.
+ +

... a mesma coisa mas com uma animação de rolagem na página:

+ +
var showBookmark = (function () {
+  var  _useHash, _scrollX, _scrollY, _nodeX, _nodeY, _itFrame, _scrollId = -1, _bookMark,
+       /*
+       * nDuration: the duration in milliseconds of each frame
+       * nFrames: number of frames for each scroll
+       */
+       nDuration = 200, nFrames = 10;
+
+  function _next () {
+    if (_itFrame > nFrames) { clearInterval(_scrollId); _scrollId = -1; return; }
+    _isBot = true;
+    document.documentElement.scrollTop = Math.round(_scrollY + (_nodeY - _scrollY) * _itFrame / nFrames);
+    document.documentElement.scrollLeft = Math.round(_scrollX + (_nodeX - _scrollX) * _itFrame / nFrames);
+    if (_useHash && _itFrame === nFrames) { location.hash = _bookMark; }
+    _itFrame++;
+  }
+
+  function _chkOwner () {
+    if (_isBot) { _isBot = false; return; }
+    if (_scrollId > -1) { clearInterval(_scrollId); _scrollId = -1; }
+  }
+
+  if (window.addEventListener) { window.addEventListener("scroll", _chkOwner, false); }
+  else if (window.attachEvent) { window.attachEvent("onscroll", _chkOwner); }
+
+  return function (sBookmark, bUseHash) {
+    _scrollY = document.documentElement.scrollTop;
+    _scrollX = document.documentElement.scrollLeft;
+    _bookMark = sBookmark;
+    _useHash = arguments.length === 1 || bUseHash;
+    for (
+      var nLeft = 0, nTop = 0, oNode = document.querySelector(sBookmark);
+      oNode;
+      nLeft += oNode.offsetLeft, nTop += oNode.offsetTop, oNode = oNode.offsetParent
+    );
+    _nodeX = nLeft, _nodeY = nTop, _itFrame = 1;
+    if (_scrollId === -1) { _scrollId = setInterval(_next, Math.round(nDuration / nFrames)); }
+  };
+})();
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + +
EspecificaçãoEstatusComentário
{{SpecName('HTML WHATWG', "history.html#the-location-interface", "Window.location")}}{{Spec2('HTML WHATWG')}}Sem mudanças a partir de {{SpecName("HTML5 W3C")}}.
{{SpecName('HTML5 W3C', "browsers.html#the-location-interface", "Window.location")}}{{Spec2('HTML5 W3C')}}Definição inicial.
+ +

Compatibilidade de navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
window.location.origin30.0.1599.101 (possibly earlier){{CompatGeckoDesktop("21.0")}}11[1]{{CompatUnknown}}7 (possibly earlier, see webkit bug 46558)
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
window.location.origin30.0.1599.101 (possibly earlier){{CompatGeckoMobile("21.0")}}{{CompatUnknown}}{{CompatUnknown}}7 (possibly earlier, see webkit bug 46558)
+
+ +

[1] In Internet Explorer 11 on Windows 10 window.location.origin is undefined due to a bug, see https://connect.microsoft.com/IE/feedback/details/1763802/location-origin-is-undefined-in-ie-11-on-windows-10-but-works-on-windows-7.

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/window/matchmedia/index.html b/files/pt-br/web/api/window/matchmedia/index.html new file mode 100644 index 0000000000..a6497ded0a --- /dev/null +++ b/files/pt-br/web/api/window/matchmedia/index.html @@ -0,0 +1,106 @@ +--- +title: Window.matchMedia() +slug: Web/API/Window/matchMedia +translation_of: Web/API/Window/matchMedia +--- +
{{APIRef}}
+ +

Resumo

+ +

Retorna um novo objeto {{domxref("MediaQueryList")}} representando o resultado analisado da string media query especificada.

+ +

Sintaxe

+ +
mql = window.matchMedia(mediaQueryString)
+ +

onde mediaQueryString é uma string representando a media query para o qual retorna um novo objeto {{domxref("MediaQueryList")}}.

+ +

Exemplo

+ +
if (window.matchMedia("(min-width: 400px)").matches) {
+  /* a viewport tem pelo menos 400 pixels de largura */
+} else {
+  /* a viewport menos que 400 pixels de largura */
+}
+ +

Este código permite-lhe lidar com as coisas de forma diferente quando a janela é muito estreita.

+ +

Veja Usando media queries a partir do código para mais exemplos.

+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçõesStatusComment
{{SpecName("CSSOM View", "#dom-window-matchmedia", "Window.matchMedia()")}}{{Spec2("CSSOM View")}}Initial definition
+ +

Compatibilidade do navegador

+ +

{{CompatibilityTable()}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support9{{CompatGeckoDesktop("6.0")}}1012.15.1
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support3.0{{CompatGeckoMobile("6.0")}}{{CompatNo}}12.15
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/window/navigator/index.html b/files/pt-br/web/api/window/navigator/index.html new file mode 100644 index 0000000000..c73ebe3f36 --- /dev/null +++ b/files/pt-br/web/api/window/navigator/index.html @@ -0,0 +1,54 @@ +--- +title: Window.navigator +slug: Web/API/Window/navigator +tags: + - API + - Propriedade + - Referencia + - Somente-leitura + - Window +translation_of: Web/API/Window/navigator +--- +
+ {{APIRef}}
+

A propriedade somente leitura Window.navigator retorna uma referência para o objeto {{domxref("Navigator")}}, que pode ser consultada para obter informações sobre a aplicação executando o script.

+

Sintaxe

+
navigatorObject = window.navigator
+

Exemplos

+

Exemplo #1: Detecta o navegador e retorna uma string

+
var sBrowser, sUsrAg = navigator.userAgent;
+
+if(sUsrAg.indexOf("Chrome") > -1) {
+    sBrowser = "Google Chrome";
+} else if (sUsrAg.indexOf("Safari") > -1) {
+    sBrowser = "Apple Safari";
+} else if (sUsrAg.indexOf("Opera") > -1) {
+    sBrowser = "Opera";
+} else if (sUsrAg.indexOf("Firefox") > -1) {
+    sBrowser = "Mozilla Firefox";
+} else if (sUsrAg.indexOf("MSIE") > -1) {
+    sBrowser = "Microsoft Internet Explorer";
+}
+
+alert("Você está utilizando: " + sBrowser);
+

Exemplo #2: Detecta o navegador e retorna um índice

+
function getBrowserId () {
+
+    var
+        aKeys = ["MSIE", "Firefox", "Safari", "Chrome", "Opera"],
+        sUsrAg = navigator.userAgent, nIdx = aKeys.length - 1;
+
+    for (nIdx; nIdx > -1 && sUsrAg.indexOf(aKeys[nIdx]) === -1; nIdx--);
+
+    return nIdx
+
+}
+
+console.log(getBrowserId());
+

Especificação

+ +

Veja também

diff --git a/files/pt-br/web/api/window/ondevicelight/index.html b/files/pt-br/web/api/window/ondevicelight/index.html new file mode 100644 index 0000000000..005ef03903 --- /dev/null +++ b/files/pt-br/web/api/window/ondevicelight/index.html @@ -0,0 +1,99 @@ +--- +title: Window.ondevicelight +slug: Web/API/Window/ondevicelight +translation_of: Web/API/Window/ondevicelight +--- +
{{APIRef}}
+ +

Especifica um event listener para receber eventos {{event("devicelight")}}. Esses eventos ocorrem quando um dispositivo com sensores de nível de luz detecta uma mudança na intensidade do nível de luz do ambiente.

+ +

Sintaxe

+ +
window.ondevicelight = funcRef
+ +

Onde funcRef é a função a ser chamada quando o evento {{event("devicelight")}} ocorre. Estes eventos são do tipo {{domxref("DeviceLightEvent")}}.

+ +

Especificações

+ + + + + + + + + + + + + + + + +
SpecificaçãoStatusComment
{{SpecName('AmbientLight', '#event-handlers', 'Ambient Light Events')}}{{Spec2('AmbientLight')}}Initial definition
+ +

Compatibilidade com os Navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatNo}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("22.0")}}[1]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatUnknown}}{{CompatGeckoMobile("15.0")}}[1]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] The {{event("devicelight")}} event is implemented and by preference enabled by default in Firefox Mobile for Android (15.0) and in Firefox OS (B2G). Starting with Gecko 22.0 {{geckoRelease("22.0")}}, a desktop implementation for Mac OS X is also available. Support for Windows 7 is in progress (see {{bug(754199)}}).

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/window/onscroll/index.html b/files/pt-br/web/api/window/onscroll/index.html new file mode 100644 index 0000000000..9589f24eaa --- /dev/null +++ b/files/pt-br/web/api/window/onscroll/index.html @@ -0,0 +1,98 @@ +--- +title: window.onscroll +slug: Web/API/Window/onscroll +translation_of: Web/API/GlobalEventHandlers/onscroll +--- +

{{ ApiRef() }}

+

Sumário

+

Especifica a função a ser chamada quando é feito o scroll na janela.

+

Sintaxe

+
window.onscroll = funcRef;
+
+ +

Exemplos

+

Exemplo 1: Genérico

+
window.onscroll = function (oEvent) {
+  // executa um bloco de código ou funções, quando o scroll é feito na janela.
+}
+
+

Examplo 2: Dectando a rolagem

+

O exemplo a seguir, irá disparar um alerta sempre que o usuário rolar a página .

+
<!doctype html>
+<html>
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
+<title>onscroll test</title>
+<script type="text/javascript">
+window.onscroll = scroll;
+
+function scroll () {
+ alert("evento scroll detectado! " + window.pageXOffset + " " + window.pageYOffset);
+ // nota: você pode usar window.innerWidth e window.innerHeight para obter a largura e altura da área de visão.
+}
+</script>
+</head>
+
+<body>
+<p>Redimensione a janela</p>
+<p>para um tamanho pequeno,</p>
+<p>e use a barra de rolagem</p>
+<p>para mover ao redor do conteúdo da página</p>
+<p>na janela.</p>
+</body>
+</html>
+
+ +

O exemplo a seguir irá mostrar um link( uma imagem de seta ) no topo da página quando a rolagem vertical atingir 500 pixels

+

 

+
<!doctype html>
+<html>
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
+<title>MDN Example</title>
+<script type="text/javascript">
+var bAppended = false, oBookmark = document.createElement("div");
+oBookmark.id = "arrowUp";
+oBookmark.innerHTML = "<a href=\"#\" title=\"Top of the page.\">&uarr;<\/a>";
+
+onscroll = function() {
+  var nVScroll = document.documentElement.scrollTop || document.body.scrollTop;
+  bAppended = nVScroll > 500 ?
+    bAppended || (document.body.appendChild(oBookmark), true)
+    : bAppended && (document.body.removeChild(oBookmark), false);
+};
+</script>
+<style type="text/css">
+#arrowUp {
+  position: fixed;
+  height: auto;
+  width: auto;
+  right: 10px;
+  top: 10px;
+  font-size: 48px;
+}
+#arrowUp a {
+  text-decoration: none;
+  color: black;
+  font-weight: bold;
+  font-family: serif;
+}
+</style>
+</head>
+
+<body>
+<p>Conteúdo da página aqui!</p>
+</body>
+
+</html>
+

Notas

+

{{ Bug(189308) }}, nas versões antigas do Gecko, o evento 'onscroll' era executado apenas quando a barra de rolagem era arrastada, não quando utilizada a seta do teclado ou scroll do mouse.
+ Esse bug foi corrigido no Gecko 1.8/Firefox 1.5

+

Quando o window.scrollX/scrollY não é 0 -- considerando que o scroll ocorreu por algum script ou uma ação manual -- recarregando a página irá disparar o evento onscroll imediatamente.

+

Especificação

+ +

{{ languages( { "zh-cn": "zh-cn/DOM/window.onscroll"} ) }}

diff --git a/files/pt-br/web/api/window/opendialog/index.html b/files/pt-br/web/api/window/opendialog/index.html new file mode 100644 index 0000000000..cb2e5f31ba --- /dev/null +++ b/files/pt-br/web/api/window/opendialog/index.html @@ -0,0 +1,90 @@ +--- +title: window.openDialog +slug: Web/API/Window/openDialog +translation_of: Web/API/Window/openDialog +--- +

{{ ApiRef() }}

+ +

Resumo

+ +

window.openDialog é uma extensão para window.open. Ela se comporta da mesma maneira, exceto que pode opcionalmente usar um ou mais parâmetros passado por windowFeatures, e windowFeatures em si é tratado um pouco diferente.

+ +

Parâmetros opcionais, se presentes, serão incluídos no JavaScript Array object e adicionados a nova janela criada como uma propriedade chamada window.arguments. Eles podem ser referenciados no javascript da janela a qualquer momento, incluindo durante a execução da load handler. Esses parâmetros podem ser usados, e depois, para passar argumentos para e da janela de diálogo.

+ +

Note que a chamada para openDialog() retorna imediatamente. Se você quer que a chamada seja bloqueada até o usuário fechar a janela de diálogo, forneça modal como um parâmetro windowFeatures. Note que isso significa que o usuário não poderá interagir com a janela que abriu a janela modal (modal dialog) enquanto o usuário não fechá-la.

+ +

Sintaxe

+ +
newWindow = openDialog(url, name, features, arg1, arg2, ...)
+
+ +
+
newWindow 
+
A janela aberta
+
url 
+
A URL a ser carregada na nova janela aberta.
+
name 
+
O nome da janela (opcional). Veja a descrição de window.open para informações detalhadas.
+
features 
+
Consulte window.open para descrição.
+
arg1, arg2, ... 
+
Os argumentos podem ser passados para a nova janela (opcional).
+
+ +

Exemplo

+ +
var win = openDialog("http://example.tld/zzz.xul", "dlg", "", "pizza", 6.98);
+
+ +

Observações

+ +

Novas funcionalidades

+ +

all - Initially activates (or deactivates ("all=no")) all chrome (except the behaviour flags chrome, dialog and modal). These can be overridden (so "menubar=no,all" turns on all chrome except the menubar.) This feature is explicitly ignored by window.open. window.openDialog finds it useful because of its different default assumptions.

+ +

Comportamento padrão

+ +

The chrome and dialog features are always assumed on, unless explicitly turned off ("chrome=no"). openDialog treats the absence of the features parameter as does window.open, (that is, an empty string sets all features to off) except chrome and dialog, which default to on. If the features parameter is a zero-length string, or contains only one or more of the behaviour features (chrome, dependent, dialog and modal) the chrome features are assumed "OS' choice." That is, window creation code is not given specific instructions, but is instead allowed to select the chrome that best fits a dialog on that operating system.

+ +

Passando parâmetros extras para o diálogo

+ +

Para passar parâmento extra para a janela de diálogo, você pode simplesmente pode fornece=lo depois do parâmetro windowFeatures:

+ +
openDialog("http://example.tld/zzz.xul", "dlg", "", "pizza", 6.98);
+
+ +

Os parâmetros serão empacotados em uma propriedade chamada arguments do tipo Array, e essa propriedade será adicionada para a nova janela de diálogo.

+ +

Para acessar esses parâmetros extras da janela de diálogo, use o seguinte esquema:

+ +
var food  = window.arguments[0];
+var price = window.arguments[1];
+
+ +

Note que você pode acessar esta propriedade de qualwuer lugar do código de diálogo.. (Outro exemplo).

+ +

Retornando valores do diálogo

+ +

Dado que window.close() apaga todas a propriedades associadas com a janela de diálogo (isto é, as variáveis especificadas no código javascript que é carregado a partir da janela de diálogo), não é possível passar os valores retornados depois da operação de fechamento usando variáveis globais (ou qualquer outro construtor).

+ +

Para ser possível passar valores de volta para a janela que chamou, você deve fornecer algum objeto via parâmetros extra. Em seguida, pode acessar esse objeto de dentro do código de diálogo e definir as propriedades nele, que contém os valores que você deseja retornar ou preservar passado a operação window.close().

+ +
var retVals = { address: null, delivery: null };
+openDialog("http://example.tld/zzz.xul", "dlg", "modal", "pizza", 6.98, retVals);
+
+ +

Se você definir as propriedades do objeto retVals no código de diálogo, conforme descrito abaixo, agora você pode acessá-los via array retVals depois do retorno da chamada de openDialog().

+ +

Dentro do código de diálogo, você pode definir as propriedades da seguinte forma:

+ +
var retVals = window.arguments[2];
+retVals.address  = enteredAddress;
+retVals.delivery = "immediate";
+
+ +

Veja também . (Outro exemplo).
+ veja também window.importDialog (mobile).

+ +

Especificação

+ +

{{ DOM0() }}

diff --git a/files/pt-br/web/api/window/performance/index.html b/files/pt-br/web/api/window/performance/index.html new file mode 100644 index 0000000000..6e7edcd558 --- /dev/null +++ b/files/pt-br/web/api/window/performance/index.html @@ -0,0 +1,33 @@ +--- +title: Window.performance +slug: Web/API/Window/performance +translation_of: Web/API/Window/performance +--- +
{{APIREf}}
+ +
A API Web Performance permite páginas da web acessarem algumas funções para medir a performance de páginas e aplicações da web, incluindo a API Navigation Timing e dados de tempo de alta resolução.
+ +
 
+ +

Métodos

+ +
+
{{domxref("Performance.mark()", "performance.mark()")}}
+
Mapeia um {{domxref("DOMHighResTimeStamp")}} para o nome especificado representando a quantidade de milissegundos passados desde um momento de referência.
+
+ +
+
{{domxref("Performance.now()", "performance.now()")}}
+
Retorna um {{domxref("DOMHighResTimeStamp")}} representando a quantidade de milissegundos passados desde um momento de referência.
+
+ +

Propriedades

+ +
+
{{domxref("Performance.timing", "performance.timing")}}
+
É um objeto {{domxref("PerformanceTiming")}} contendo informações de performance relacionadas a latência.
+
{{domxref("Performance.navigation", "performance.navigation")}}
+
É um objeto {{domxref("PerformanceNavigation")}} representando o tipo de navegação que ocorre no contexto de navegação dado, como a quantidade de redirecionamentos necessários para buscar o recurso.
+
performance.memory
+
Uma extensao não-padrão adicionada ao Chrome.
+
diff --git a/files/pt-br/web/api/window/popstate_event/index.html b/files/pt-br/web/api/window/popstate_event/index.html new file mode 100644 index 0000000000..55f493f18b --- /dev/null +++ b/files/pt-br/web/api/window/popstate_event/index.html @@ -0,0 +1,144 @@ +--- +title: popstate +slug: Web/API/Window/popstate_event +translation_of: Web/API/Window/popstate_event +--- +

O evento popstate é disparado quando a entrada do histórico ativa é alterado. Se o histórico de entrada a ser ativado for criado por uma chamada history.pushState() ou for afetada por uma chamada history.replaceState(), a propriedade dos eventos popstate contém uma cópia do histórico de entrada do objeto.
+
+ Note  que apenas chamando history.pushState() ou history.replaceState() não ira disparar um evento popstate. O evento popstate apenas é disparado após uma ação no navegador como um click no botão de voltar (ou chamando history.back() por javascript)
+
+ Navegadores tendem a lidar com o evento popstate diferentemente no carregamento da página. Chrome (anterior versão 34) e Safari sempre emitem um evento popstate no carregamento da página, mas o Firefox não.

+ +

Informação geral

+ +
+
Especificação
+
HTML5
+
Interface
+
PopStateEvent
+
Bubbles
+
Yes
+
Cancelable
+
No
+
Alvo
+
defaultView
+
Ação padrão
+
None
+
+ +

Propriedades

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
target {{readonlyInline}}{{domxref("EventTarget")}}The browsing context (window).
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.
state {{readonlyInline}}anyThe current history entry's state object (if any).
+ +

Compatiblidade com navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatGeckoDesktop("2")}}10.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}[1]
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico3.0[2]{{CompatGeckoMobile("2")}}10.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}[1]
+
+ +

[1] A implementação tem um suporte limitado.

+ +

[2] A implementação em Android 2.2 e 2.3 tem problemas.

+ +

Exemplo

+ +

Um página no http://example.com/example.html roda o código abaixo e irá gerar os logs indicados

+ +
window.onpopstate = function(event) {
+  console.log("location: " + document.location + ", state: " + JSON.stringify(event.state));
+};
+history.pushState({page: 1}, "title 1", "?page=1");
+history.pushState({page: 2}, "title 2", "?page=2");
+history.replaceState({page: 3}, "title 3", "?page=3");
+history.back(); // Logs "location: http://example.com/example.html?page=1, state: {"page":1}"
+history.back(); // Logs "location: http://example.com/example.html, state: null
+history.go(2);  // Logs "location: http://example.com/example.html?page=3, state: {"page":3}
+
+ +

Observe que mesmo que a entrada do histórico inicial(para http://example.com/example.html) não tem nenhum estado associado a ele, um evento popstate é ainda disparado quando nós ativamos essa entrada após a segunda chamada para history.back ().
+  

+ +

Eventos relacionados

+ + diff --git a/files/pt-br/web/api/window/print/index.html b/files/pt-br/web/api/window/print/index.html new file mode 100644 index 0000000000..6bf664bfb0 --- /dev/null +++ b/files/pt-br/web/api/window/print/index.html @@ -0,0 +1,56 @@ +--- +title: Window.print() +slug: Web/API/Window/print +tags: + - DOM + - Window + - print +translation_of: Web/API/Window/print +--- +

{{ ApiRef() }}

+ +

Sumário

+ +

Abre a janela de impressão para imprimir o documento atual.

+ +

Sintaxe

+ +
window.print()
+
+ +

Notas

+ +

Começando com o  Chrome {{CompatChrome(46.0)}} este método é bloqueado dentro de um {{htmlelement("iframe")}} a menos que seu atributo sandbox tem o valor allow-modal .

+ +

Especificação

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG', 'timers-and-user-prompts.html#printing', 'print()')}}{{Spec2('HTML WHATWG')}}
+ +

Compatibilidade entre Navegadores

+ + + +

{{Compat("api.Window.print")}}

+ +

Veja também

+ + + +

{{ languages( { "ja": "ja/DOM/window.print", "it": "it/DOM/window.print" , "zh-cn": "zh-cn/DOM/window.print" } ) }}

diff --git a/files/pt-br/web/api/window/prompt/index.html b/files/pt-br/web/api/window/prompt/index.html new file mode 100644 index 0000000000..e831fbcc4d --- /dev/null +++ b/files/pt-br/web/api/window/prompt/index.html @@ -0,0 +1,66 @@ +--- +title: Window.prompt() +slug: Web/API/Window/prompt +translation_of: Web/API/Window/prompt +--- +
{{ApiRef("Window")}}
+ +
O Window.prompt() exibe uma caixa de diálogo com uma mensagem opcional solicitando ao usuário a entrada de algum texto.
+ +

 

+ +

Sintaxe

+ +
resultado = window.prompt(texto, valor);
+
+ + + +

Exemplo

+ +
var signo = prompt("Qual é o seu signo?");
+
+if (signo.toLowerCase() == "escorpião") {
+  alert("Legal! Eu sou de Escorpião também!");
+}
+
+// há muitas formas de se usar o recurso prompt
+var sign = window.prompt(); // abrir uma janela de promtpt em branco
+var sign = prompt();       //  abrir uma janela de promtpt em branco
+var sign = window.prompt('Você está se sentindo com sorte'); // abrir uma janela com o texto "Você está se sentindo com sorte"
+var sign = window.prompt('Você está se sentindo com sorte', 'certamente'); // abrir uma janela com o texto "Você está se sentindo com sorte" e com o valor padrão "certamente"
+ +

Quando o usuário pressiona o botão OK, o texto digitado no campo de texto é retornado. Se o usuário pressionar OK sem ter digitado qualquer texto, uma cadeia de caracteres vazia é retornada. Se o usuário pressionar o botão Cancelar, esta função retornará null.

+ +

{{todo("external image!")}} O prompt acima aparece da seguinte forma (no Chrome do Windows 7):

+ +

+ +

Notas

+ +

Uma caixa de diálogo prompt contém uma caixa de texto de linha única, um botão Cancelar, e um botão OK, e retorna o (possivelmente vazio) texto que o usuário digitou naquela caixa de texto.

+ +

The following text is shared between this article, DOM:window.confirm and DOM:window.alertAs caixas de diálogo são janelas modais; eles impedem o usuário de acessar o resto da interface do programa até que a caixa de diálogo seja fechada. Por esta razão, você não deve abusar de qualquer função que crie uma caixa de diálogo (ou janela modal).

+ +

Por favor, note que o resultado é uma cadeia de caracteres. Isso significa que você deve, algumas vezes, converter o valor dado pelo usuário. Por exemplo, se a resposta deve ser um número, você deve converter o valor para Number: var aNumber = Number(window.prompt("Digite um número", "")); 

+ +

Os códigos do Mozilla Chrome (e.g. Firefox extensions) ao invés disso, devem usar os métodos da interface {{interface("nsIPromptService")}}.

+ +

No Safari, se o usuário clicar em Cancelar, a função retornará uma cadeia de caracteres vazia. Portanto, ele não diferenciará o cancelamento do usuário de uma cadeia de caracteres vazia na caixa de texto.

+ +

Esta função não tem efeito na versão Modern UI/Metro do Internet Explorer para Windows 8. Ele não exibe o prompt para o usuário, e sempre retornará undefined. Não está claro se é um erro ou um comportamento intencional. Versões desktop do IE implementam esta função.

+ +

Especificação

+ +

Especificado em HTML5.

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/window/requestanimationframe/index.html b/files/pt-br/web/api/window/requestanimationframe/index.html new file mode 100644 index 0000000000..3adca4b22f --- /dev/null +++ b/files/pt-br/web/api/window/requestanimationframe/index.html @@ -0,0 +1,106 @@ +--- +title: window.requestAnimationFrame() +slug: Web/API/Window/requestAnimationFrame +tags: + - API + - DOM + - Intermediário + - Método(2) + - Referência do DOM + - Timers JavaScript +translation_of: Web/API/window/requestAnimationFrame +--- +

{{APIRef}}
+ O método window.requestAnimationFrame() fala para o navegador que deseja-se realizar uma animação e pede que o navegador chame uma função específica para atualizar um quadro de animação antes da próxima repaint (repintura). O método tem como argumento uma callback que deve ser invocado antes da repaint.

+ +
Nota: A rotina callback deve chamar requestAnimationFrame() se quiser animar outro quadro na próxima repaint.
+ +

Deve-se chamar esse método sempre que estiver pronto para atualizar a animação na tela. Isso irá requisitar que a função de animação seja chamada antes que o navegador realize a próxima repaint. O número de callbacks é normalmente 60 por segundo, mas geralmente acompanha a taxa de atualização do display na maioria dos navegadores, como recomenda a W3C. A taxa de callbacks é reduzida quando executados em aba de fundo ou em {{ HTMLElement("iframe") }} escondidos para melhorar performance e vida de bateria.

+ +

Um único argumento é passado para o método callback, um {{domxref("DOMHighResTimeStamp")}}, que indica o tempo atual no qual callbacks enfileiradas por requestAnimationFrame começam a disparar. Múltiplos callbacks em um único quadro, assim, cada um recebe o mesmo carimbo de data/hora . Esse carimbo de data/hora é um número decimal, em milisegundos, mas com precisão mínima de 1ms (1000 µs).

+ +

Sintaxe

+ +
window.requestAnimationFrame(callback);
+
+ +

Parâmetros

+ +
+
callback
+
Parâmetro especificando uma função a ser chamada quando chegar a hora de atualizar a animação para a próxima repaint. O callback possui um único argumento, um {{domxref("DOMHighResTimeStamp")}}, que indica a hora atual (a hora retornada de {{domxref('Performance.now()')}} ) para quando requestAnimationFrame começar a disparar callbacks.
+
+ +

Valor de retorno

+ +

Um valor inteiro long, a id da requisição, que identifica unicamente a entrada na lista de callbacks. Esse é um valor não-zero, mas não deve-se assumir mais nada sobre esse valor. Esse valor pode ser passado para {{domxref("window.cancelAnimationFrame()")}} para cancelar a requisição da atualização do callback.

+ +

Exemplo

+ +
var start = null;
+var element = document.getElementById("ElementoQueVcQuerAnimar");
+element.style.position = 'absolute';
+
+function step(timestamp) {
+  if (!start) start = timestamp;
+  var progress = timestamp - start;
+  element.style.left = Math.min(progress/10, 200) + "px";
+  if (progress < 2000) {
+    window.requestAnimationFrame(step);
+  }
+}
+
+window.requestAnimationFrame(step);
+
+ +

Especificação

+ + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG', '#animation-frames', 'requestAnimationFrame')}}{{Spec2('HTML WHATWG')}}Sem mudanças, substitui a anterior
{{SpecName('RequestAnimationFrame', '#dom-windowanimationtiming-requestanimationframe', 'requestAnimationFrame')}}{{Spec2('RequestAnimationFrame')}}Definição inicial
+ +

Compatibilidade de navegadores

+ +
{{Compat("api.Window.requestAnimationFrame")}}
+ +
+ +

[1] Anteriro ao Gecko 11.0 {{geckoRelease("11.0")}}, mozRequestAnimationFrame() podia ser chamado sem parâmetros de entrada. Isso não é mais suportado, como provavelmente não será parte do padrão

+ +

[2] O parâmetro do callback é {{domxref("DOMTimeStamp")}} ao invés de {{domxref("DOMHighResTimeStamp")}} se a versão prefixada do método foi utilizada DOMTimeStamp possui apenas precisão de milisegundo, mas DOMHighResTimeStamp possui precisão mínima de microsegundos.  Portanto, o tempo zero é diferente: DOMHighResTimeStamp possui o mesmo tempo zero que performance.now(), mas DOMTimeStamp possui o mesmo tempo zero que Date.now().

+ +

[3] A chamada correta no Chrome para cancelar a requisição é currently window.cancelAnimationFrame(). Versões anteriores, window.webkitCancelAnimationFrame() e window.webkitCancelRequestAnimationFrame(), foram descontinuados mas possuem suporte por enquanto.

+ +

[4] Suporte para a versão prefixada foi removida no Firefox 42.

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/window/requestidlecallback/index.html b/files/pt-br/web/api/window/requestidlecallback/index.html new file mode 100644 index 0000000000..cdd2485d84 --- /dev/null +++ b/files/pt-br/web/api/window/requestidlecallback/index.html @@ -0,0 +1,70 @@ +--- +title: window.requestIdleCallback() +slug: Web/API/Window/requestIdleCallback +translation_of: Web/API/Window/requestIdleCallback +--- +
{{APIRef("HTML DOM")}}{{SeeCompatTable}}
+ +

O método window.requestIdleCallback() enfileira uma função para ser executado durante períodos onde o navegador está ocioso. Isso permite que desenvolvedores realizem tarefas de baixa prioridade em relação a o event loop em segundo plano. As funções são geralmente chamadas na ordem first-in-first-out (primeiro-a-entrar-primeiro-a-sair); Contudo, callbacks nos quais tem um timeout especificado, podem ser chamados na ordem out-of-order (fora-de-ordem) se necessário, afim de executar antes do tempo limite.

+ +

Você pode chamar requestIdleCallback() com uma função callback ociosa para agendar outro callback para ter lugar não antes da próxima passagem pelo event loop.

+ +
Um timeout é altamento recomendado, caso contrário, é possível que vários segundos passem antes que a função callback seja chamada.
+ +

Syntax

+ +
var handle = window.requestIdleCallback(callback[, options])
+ +

Return value

+ +

An ID which can be used to cancel the callback by passing it into the {{domxref("window.cancelIdleCallback()")}} method.

+ +

Parameters

+ +
+
callback
+
A reference to a function that should be called in the near future, when the event loop is idle. The callback function is passed an {{domxref("IdleDeadline")}} object describing the amount of time available and whether or not the callback has been run because the timeout period expired.
+
options {{optional_inline}}
+
Contains optional configuration parameters. Currently only one property is defined: +
    +
  • timeout: If timeout is specified and has a positive value, and the callback has not already been called by the time timeout milliseconds have passed, the callback will be called during the next idle period, even if doing so risks causing a negative performance impact.
  • +
+
+
+ +

Example

+ +

See our complete example in the article Cooperative Scheduling of Background Tasks API.

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Background Tasks')}}{{Spec2('Background Tasks')}}Initial definition.
+ +

Browser compatibility

+ + + +

{{Compat("api.Window.requestIdleCallback")}}

+ +

See also

+ + diff --git a/files/pt-br/web/api/window/resize_event/index.html b/files/pt-br/web/api/window/resize_event/index.html new file mode 100644 index 0000000000..ac5214b5a2 --- /dev/null +++ b/files/pt-br/web/api/window/resize_event/index.html @@ -0,0 +1,190 @@ +--- +title: resize +slug: Web/API/Window/resize_event +translation_of: Web/API/Window/resize_event +--- +

O evento resize é disparado quando o document view é redimensionado.

+ +

O evento manipulador pode ser registrado para o evento resize usando o atributo window.onresize ou usando window.addEventListener('resize', ...) 

+ +

Em alguns browsers mais recentes é possível registrar o evento manipulador resize em qualquer elemento HTML.  E ainda é possível adicionar atributos onresize ou usar {{domxref("EventTarget.addEventListener", "addEventListener()")}} para implementar o manipulador em qualquer elemento.  Entretanto, eventos resize  apenas são disparados sobre (enviados para) o objeto {{domxref("Window", "window")}} ({{domxref("document.defaultView")}}). Apenas manipuladores registrados no objeto window recebem os eventos.

+ +

Existe uma nova proposta (2017) para permitir que todos os elementos sejam notificados de alterações de tamanho.  Veja Resize Observer para ler o documento rascunho, e Github issues para ler as discussões do que está ativo.

+ +

Informações gerais

+ +
+
Specifications
+
DOM L3, CSSOM View
+
Interface
+
UIEvent
+
Bubbles
+
Não
+
Cancelable
+
Não
+
Target
+
defaultView (window)
+
Default Action
+
Nenhuma
+
+ +

Properties

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
target {{readonlyInline}}EventTargetO evento alto (o primeiro alvo na árvore DOM).
type {{readonlyInline}}DOMStringO tipo de evento.
bubbles {{readonlyInline}}BooleanSe o evento normalmente bubbles ou não.
cancelable {{readonlyInline}}BooleanSe o evento é cancelado ou não.
view {{readonlyInline}}WindowProxydocument.defaultView (window do documento)
detail {{readonlyInline}}long (float)0.
+ +

Examples

+ +

Como os eventos resize podem ser altamente executados, o evento manipulador não deve executar operações computacionais caras como modificações DOM. Em vez disso, recomenda-se diminuir o impacto do evento usando requestAnimationFrame, setTimeout ou customEvent*, como a seguir:
+
+ * IMPORTANT: Por favor note que IE11 precisa do customEvent polyfill para funcionar corretamente.

+ +

requestAnimationFrame + customEvent

+ +
(function() {
+    var throttle = function(type, name, obj) {
+        obj = obj || window;
+        var running = false;
+        var func = function() {
+            if (running) { return; }
+            running = true;
+             requestAnimationFrame(function() {
+                obj.dispatchEvent(new CustomEvent(name));
+                running = false;
+            });
+        };
+        obj.addEventListener(type, func);
+    };
+
+    /* init - you can init any event */
+    throttle("resize", "optimizedResize");
+})();
+
+// handle event
+window.addEventListener("optimizedResize", function() {
+    console.log("Resource conscious resize callback!");
+});
+
+ +

requestAnimationFrame

+ +
var optimizedResize = (function() {
+
+    var callbacks = [],
+        running = false;
+
+    // fired on resize event
+    function resize() {
+
+        if (!running) {
+            running = true;
+
+            if (window.requestAnimationFrame) {
+                window.requestAnimationFrame(runCallbacks);
+            } else {
+                setTimeout(runCallbacks, 66);
+            }
+        }
+
+    }
+
+    // run the actual callbacks
+    function runCallbacks() {
+
+        callbacks.forEach(function(callback) {
+            callback();
+        });
+
+        running = false;
+    }
+
+    // adds callback to loop
+    function addCallback(callback) {
+
+        if (callback) {
+            callbacks.push(callback);
+        }
+
+    }
+
+    return {
+        // public method to add additional callback
+        add: function(callback) {
+            if (!callbacks.length) {
+                window.addEventListener('resize', resize);
+            }
+            addCallback(callback);
+        }
+    }
+}());
+
+// start process
+optimizedResize.add(function() {
+    console.log('Resource conscious resize callback!')
+});
+
+ +

setTimeout

+ +
(function() {
+
+  window.addEventListener("resize", resizeThrottler, false);
+
+  var resizeTimeout;
+  function resizeThrottler() {
+    // ignore resize events as long as an actualResizeHandler execution is in the queue
+    if ( !resizeTimeout ) {
+      resizeTimeout = setTimeout(function() {
+        resizeTimeout = null;
+        actualResizeHandler();
+
+       // The actualResizeHandler will execute at a rate of 15fps
+       }, 66);
+    }
+  }
+
+  function actualResizeHandler() {
+    // handle the resize event
+    ...
+  }
+
+}());
diff --git a/files/pt-br/web/api/window/scroll/index.html b/files/pt-br/web/api/window/scroll/index.html new file mode 100644 index 0000000000..01ece16bbd --- /dev/null +++ b/files/pt-br/web/api/window/scroll/index.html @@ -0,0 +1,57 @@ +--- +title: Window.scroll() +slug: Web/API/Window/scroll +tags: + - API + - CSSOM View + - Referencia + - metodo +translation_of: Web/API/Window/scroll +--- +
{{APIRef}}
+ +

Resumo

+ +

Rola a janela para uma posição específica no documento.

+ +

Sintaxe

+ +
window.scroll(x-coord, y-coord)
+
+ +

Parâmetros

+ + + +

Exemplo

+ +
<!-- disponha o centésimo pixel vertical no topo da janela -->
+
+<button onClick="scroll(0, 100);">clique para rolar 100 pixels para baixo</button>
+
+ +

Notas

+ +

window.scrollTo é essencialmente equivalente a este método. Para rolar uma distância específica repetidamente, utilize o método window.scrollBy. Veja também window.scrollByLines, window.scrollByPages.

+ +

Especificação

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{ SpecName('CSSOM View', '#dom-window-scroll', 'window.scroll()') }}{{ Spec2('CSSOM View') }}Definição inicial.
diff --git a/files/pt-br/web/api/window/scrollby/index.html b/files/pt-br/web/api/window/scrollby/index.html new file mode 100644 index 0000000000..c3ee906d33 --- /dev/null +++ b/files/pt-br/web/api/window/scrollby/index.html @@ -0,0 +1,53 @@ +--- +title: Window.scrollBy() +slug: Web/API/Window/scrollBy +translation_of: Web/API/Window/scrollBy +--- +

{{ APIRef() }}

+ +

Resumo

+ +

Desloca o documento dentro da janela pelo valor fornecido.

+ +

Sintaxe

+ +
window.scrollBy(X, Y);
+
+ +

Parâmetros

+ + + +

Coordenadas positivas deslocarão para a direita e para baixo. Coordenadas negativas deslocarão para a esquerda e para cima.

+ +

Exemplo

+ +
// Desloca a altura interna da janela
+window.scrollBy(0, window.innerHeight);
+
+ +

Notas

+ +

window.scrollBy desloca uma quantidade específical enquanto window.scroll desloca para uma posição absoluta no documento. Veja Também window.scrollByLines, window.scrollByPages

+ +

Especificações

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSSOM View', '#dom-window-scrollby', 'window.scrollBy()') }}{{ Spec2('CSSOM View') }}Initial definition.
diff --git a/files/pt-br/web/api/window/scrollbypages/index.html b/files/pt-br/web/api/window/scrollbypages/index.html new file mode 100644 index 0000000000..1ad5c70c47 --- /dev/null +++ b/files/pt-br/web/api/window/scrollbypages/index.html @@ -0,0 +1,41 @@ +--- +title: Window.scrollByPages() +slug: Web/API/Window/scrollByPages +translation_of: Web/API/Window/scrollByPages +--- +

{{ ApiRef() }}{{Non-standard_header}}

+ +

Resumo

+ +

Rola o documento atual para a página especificada.

+ +

Sintaxe

+ +
window.scrollByPages(pages)
+
+ +

Parâmetros

+ + + +

Exemplo

+ +
// rola o documento para baixo até a página 1
+window.scrollByPages(1);
+
+// rola o documento para cima até a página 1
+window.scrollByPages(-1);
+
+ +

Notas

+ +

Veja também window.scrollBy, window.scrollByLines, window.scroll, window.scrollTo.

+ +

Specification

+ +

DOM Level 0. Not part of specification.

+ +

{{ languages( { "ja": "ja/DOM/window.scrollByPages", "pl": "pl/DOM/window.scrollByPages", "zh-cn": "zh-cn/DOM/window.scrollByPages" } ) }}

diff --git a/files/pt-br/web/api/window/scrollto/index.html b/files/pt-br/web/api/window/scrollto/index.html new file mode 100644 index 0000000000..10d844a41f --- /dev/null +++ b/files/pt-br/web/api/window/scrollto/index.html @@ -0,0 +1,56 @@ +--- +title: Window.scrollTo() +slug: Web/API/Window/scrollTo +tags: + - API + - CSSOM View + - NeedsCompatTable + - NeedsMarkupWork + - NeedsSpecTable + - Referencia + - metodo +translation_of: Web/API/Window/scrollTo +--- +
{{ APIRef }}
+ +

Resumo

+ +

Realiza a rolagem para um conjunto de coordenadas em particular em um documento.

+ +

Sintaxe

+ +
window.scrollTo(x-coord, y-coord)
+ +

Parâmetros

+ + + +

Exemplo

+ +
window.scrollTo( 0, 1000 );
+ +

Notas

+ +

Essa função é efetivamente a mesma que window.scroll. Para rolagem relativa, veja window.scrollBy, window.scrollByLines e window.scrollByPages.

+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{ SpecName('CSSOM View', '#dom-window-scroll', 'window.scroll()') }}{{ Spec2('CSSOM View') }}Definição inicial.
diff --git a/files/pt-br/web/api/window/scrolly/index.html b/files/pt-br/web/api/window/scrolly/index.html new file mode 100644 index 0000000000..28d7fd8797 --- /dev/null +++ b/files/pt-br/web/api/window/scrolly/index.html @@ -0,0 +1,76 @@ +--- +title: Window.scrollY +slug: Web/API/Window/scrollY +translation_of: Web/API/Window/scrollY +--- +
{{APIRef}}
+ +

Sumário

+ +

Retorna o número de pixels que o documento já rolou verticalmente.

+ +

Sintaxe

+ +
var y = window.scrollY;
+
+ + + +

Exemplo

+ +
// verificar e ir para a segunda página
+if (window.scrollY) {
+  window.scroll(0, 0);  // reinicia a posição do scroll para a posição superior esquerda do documento.
+}
+
+window.scrollByPages(1);
+ +

Notas

+ +

Utilize esta propriedade para verificar se o documento já foi rolado quando funções de rolagem relativa, tais como {{domxref("window.scrollBy")}}, {{domxref("window.scrollByLines")}}, ou {{domxref("window.scrollByPages")}}, forem utilizadas.

+ +

A propriedade pageYOffset é um alias para scrollY:

+ +
window.pageYOffset == window.scrollY; // always true
+ +

For cross-browser compatibility, use window.pageYOffset instead of window.scrollY. Additionally, older versions of Internet Explorer (< 9) do not support either property and must be worked around by checking other non-standard properties. A fully compatible example:

+ +

Para compatibilidade cross-browser, utilize window.pageYOffset em vez de window.scrollY. Além disso, versões inferiores do Internet Explorer 9 não suportam ambas as propriedades, e deve ser contornado verificando outras propriedades não padronizadas.

+ +
var supportPageOffset = window.pageXOffset !== undefined;
+var isCSS1Compat = ((document.compatMode || "") === "CSS1Compat");
+
+var x = supportPageOffset ? window.pageXOffset : isCSS1Compat ? document.documentElement.scrollLeft : document.body.scrollLeft;
+var y = supportPageOffset ? window.pageYOffset : isCSS1Compat ? document.documentElement.scrollTop : document.body.scrollTop;
+
+ +

Especificação

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSSOM View', '#dom-window-scrolly', 'window.scrollY') }}{{ Spec2('CSSOM View') }}
+ +

Browser compatibility

+ +

{{Compat("api.Window.scrollY")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/window/sessionstorage/index.html b/files/pt-br/web/api/window/sessionstorage/index.html new file mode 100644 index 0000000000..b387b8af5b --- /dev/null +++ b/files/pt-br/web/api/window/sessionstorage/index.html @@ -0,0 +1,143 @@ +--- +title: Window.sessionStorage +slug: Web/API/Window/sessionStorage +tags: + - Armazenamento + - Propriedade + - Referencia + - Sessão +translation_of: Web/API/Window/sessionStorage +--- +

{{APIRef()}}

+ +

A propriedade sessionStorage permite acessar um objeto tipo session {{domxref("Storage")}}. A sessionStorage é similar ao localStorage, a única diferença é que enquanto os dados armazenados no localStorage não expiram, os dados no sessionstorage tem os seus dados limpos ao expirar a sessão da página. A sessão da página dura enquanto o browser está aberto e se mantém no recarregamento da página. Abrir a página em uma nova aba ou nova janela irá gerar uma nova sessão, o que diferencia de como os cookies trabalham.

+ +

Sintaxe

+ +
// Salva os dados na sessionStorage
+sessionStorage.setItem('chave', 'valor');
+
+// Obtém os dados da sessionStorage
+var data = sessionStorage.getItem('chave');
+ +

Valor

+ +

Objeto {{domxref("Storage")}}.

+ +

Exemplo

+ +

O seguinte trecho acessa o objeto da sessão do domínio atual {{domxref("Storage")}} e adiciona um item usando o {{domxref("Storage.setItem()")}}.

+ +
sessionStorage.setItem('myCat', 'Tom');
+ +

O exemplo a seguir salva automaticamente o conteúdo da caixa de texto, e caso o browser seja acidentalmente recarregado, o conteúdo da caixa de texto é restaurado.

+ +
// Obtem a caixa de texto que vamos rastrear
+var field = document.getElementById("campo");
+
+// Se tivermos um valor salvo automaticamente
+// (isto só ocorrerá se a página for acidentalmente recarregada)
+if (sessionStorage.getItem("autosave")) {
+  // Restaura o conteúdo da caixa de texto
+  field.value = sessionStorage.getItem("autosave");
+}
+
+// Verifica as mudanças que ocorrem na caixa de texto
+field.addEventListener("change", function() {
+  // E salva o resultado dentro de um objeto session storage
+  sessionStorage.setItem("autosave", field.value);
+});
+ + + +
+

Nota: Por favor use o artigo Using the Web Storage API para um exemplo completo.

+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçõesStatusComentários
{{SpecName('Web Storage', '#the-sessionstorage-attribute', 'sessionStorage')}}{{Spec2('Web Storage')}}
+ +

Browser compatíveis

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
localStorage43.5810.504
sessionStorage52810.504
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support2.1{{ CompatUnknown }}811iOS 3.2
+
+ +

Cada browser tem o seu nível de capacidade de armazenamento para localStorage e sessionStorage. Aqui está um teste detalhado de toda a capacidade de armazenamento de vários browsers.

+ +
+

Nota: desde o iOS 5.1, Safari Mobile armazena os dados do localStorage em uma pasta de cache, o que está sujeito a ocasionalmente ser limpa, de acordo com o SO, se houver pouco espaço.

+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/window/setcursor/index.html b/files/pt-br/web/api/window/setcursor/index.html new file mode 100644 index 0000000000..d85dfb7c01 --- /dev/null +++ b/files/pt-br/web/api/window/setcursor/index.html @@ -0,0 +1,28 @@ +--- +title: Window.setCursor() +slug: Web/API/Window/setCursor +translation_of: Web/API/Window/setCursor +--- +
{{ ApiRef() }}
+ +
 
+ +

Sumário

+ +

Altera o cursor para a janela atual.

+ +

Exemplo

+ +
function setBusyCursor(enable) {
+  window.setCursor(enable ? "wait" : "auto");
+}
+ +

Notas

+ +

O cursor não retornará ao seu padrão até que seja definido novamente para auto.

+ +

Esta função é parte do ChromeWindow interface. Esta função não está habilitada para páginas web, que podem usar a propriedade CSS {{cssxref("cursor")}} em seu lugar.

+ +

Especificação

+ +

{{dom0}}

diff --git a/files/pt-br/web/api/window/setimmediate/index.html b/files/pt-br/web/api/window/setimmediate/index.html new file mode 100644 index 0000000000..693c51619b --- /dev/null +++ b/files/pt-br/web/api/window/setimmediate/index.html @@ -0,0 +1,107 @@ +--- +title: Window.setImmediate() +slug: Web/API/Window/setImmediate +translation_of: Web/API/Window/setImmediate +--- +
{{APIRef("HTML DOM")}}{{Non-standard_header}}
+ +

Esse método é usado para interromper operações de longa duração e executar uma função de retorno de chamada imediatamente após o navegador ter concluído outras operações, como eventos e atualizações de exibição.

+ +
Não se espera que este método se torne padrão, e é implementado somente por compilações recentes do Internet Explorer e Node.js 0.10+. Existem resistencias de ambos Gecko (Firefox) e Webkit (Google/Apple).
+ +

Sintaxe

+ +
var immediateID = setImmediate(func, [param1, param2, ...]);
+var immediateID = setImmediate(func);
+
+ + + +

Todos parametros serão passados diretamente para sua função .

+ +

Notas

+ +

O método {{ domxref("window.clearImmediate") }} pode ser usado para limpar as ações immediate, como por exemplo {{ domxref("window.clearTimeout") }} para {{ domxref("window.setTimeout") }}.

+ +

Esse método pode ser usado ao invés de setTimeout(fn, 0), para executar operações pesadas

+ +

Essa função pode ser emulada de algumas maneiras:

+ + + +

Todas essas técnicas são incorporadas em um setImmediate polyfill.

+ +

Especificações

+ +

Não faz parte de nenhuma especificação e não em uma faixa de padrões.

+ +

Compatibilidade do navegador

+ +

{{ CompatibilityTable }}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatNo }}{{CompatVersionUnknown}}{{ CompatNo }}10{{ CompatNo }}{{ CompatNo }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatNo }}{{CompatVersionUnknown}}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
+
+ +

Ver também

+ +

{{ domxref("window.clearImmediate") }}

+ +

{{ spec("https://dvcs.w3.org/hg/webperf/raw-file/tip/specs/setImmediate/Overview.html", "Specification: Efficient Script Yielding") }}

+ +

Microsoft setImmediate API Demo

+ +

{{ languages( { "zh-cn": "zh-cn/DOM/window.setImmediate" } ) }}

diff --git a/files/pt-br/web/api/window/url/index.html b/files/pt-br/web/api/window/url/index.html new file mode 100644 index 0000000000..5c673ed4b6 --- /dev/null +++ b/files/pt-br/web/api/window/url/index.html @@ -0,0 +1,100 @@ +--- +title: Window.URL +slug: Web/API/Window/URL +translation_of: Web/API/URL +--- +

{{ApiRef("Window")}}{{SeeCompatTable}}

+ +

A propriedade Window.URL retorna um objeto que fornece métodos estáticos usados para criar e gerenciar URLs de objeto. Também pode ser chamado como um construtor para construir objetos {{domxref("URL")}}.

+ +

{{AvailableInWorkers}}

+ +

Sintaxe

+ +

Chamando um método estático:

+ +
img.src = URL.{{domxref("URL.createObjectURL", "createObjectURL")}}(blob);
+ +

Construindo um novo objeto:

+ +
var url = new {{domxref("URL.URL", "URL")}}("../cats/", "https://www.example.com/dogs/");
+ +

Especificação

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('URL', '#dom-url', 'URL')}}{{Spec2('URL')}}Initial definition
+ +

Compatibilidade do navegador

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support8.0[2]{{CompatGeckoDesktop("2.0")}}[1]
+ {{CompatGeckoDesktop("19.0")}}
10.015.0[2]6.0[2]
+ 7.0
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}[2]{{CompatGeckoMobile("14.0")}}[1]
+ {{CompatGeckoMobile("19.0")}}
{{CompatVersionUnknown}}15.0[2]6.0[2]
+
+ +

[1] Do Gecko 2 (Firefox 4) ao Gecko 18 incluído, o Gecko retornou um objeto com o tipo interno nsIDOMMozURLProperty não padrão. Na prática, isso não fez diferença.

+ +

[2] Implementado sob o nome não padronizado webkitURL.

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/window/window.localstorage/index.html b/files/pt-br/web/api/window/window.localstorage/index.html new file mode 100644 index 0000000000..8c7c379435 --- /dev/null +++ b/files/pt-br/web/api/window/window.localstorage/index.html @@ -0,0 +1,123 @@ +--- +title: Window.localStorage +slug: Web/API/Window/Window.localStorage +tags: + - API + - Armazenamento + - Propriedade + - Referencia + - WindowLocalStorage + - localStorage +translation_of: Web/API/Window/localStorage +--- +

{{APIRef()}}

+ +

A propriedade localStorage permite acessar um objeto {{domxref("Storage")}} local. A localStorage é similar ao sessionStorage. A única diferença é que enquanto os dados armazenados no localStorage não expiram, os dados no sessionStorage tem os seus dados limpos ao expirar a sessão da página — ou seja, quando a página (aba ou janela) é fechada.

+ +

Sintaxe

+ +
meuStorage = localStorage;
+ +

Valor

+ +

Objeto {{domxref("Storage")}}.

+ +

Exemplo

+ +

O seguinte trecho acessa o objeto {{domxref("Storage")}} local do domínio atual e adiciona um item usando o {{domxref("Storage.setItem()")}}.

+ +
localStorage.setItem('meuGato', 'Tom');
+ +
+

Nota: Por favor veja o artigo Using the Web Storage API para um exemplo completo.

+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('Web Storage', '#dom-localstorage', 'localStorage')}}{{Spec2('Web Storage')}} 
+ + + +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
localStorage43.5810.504
sessionStorage52810.504
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support2.1{{ CompatUnknown }}811iOS 3.2
+
+ +

Cada navegador tem o seu nível de capacidade de armazenamento para localStorage e {{domxref("sessionStorage")}}. Aqui está um teste detalhado de toda a capacidade de armazenamento de vários browsers.

+ +
+

Nota: desde o iOS 5.1, Safari Mobile armazena os dados do localStorage em uma pasta de cache, o que está sujeito a ocasionalmente ser limpa, de acordo com o SO, se houver pouco espaço. O modo de Navegação Privada do Safari Mobile não permite escrever no localStorage de forma alguma.

+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/windowbase64/atob/index.html b/files/pt-br/web/api/windowbase64/atob/index.html new file mode 100644 index 0000000000..cb9058abe5 --- /dev/null +++ b/files/pt-br/web/api/windowbase64/atob/index.html @@ -0,0 +1,72 @@ +--- +title: WindowBase64.atob() +slug: Web/API/WindowBase64/atob +tags: + - API + - Referencia + - WindowBase64 + - metodo +translation_of: Web/API/WindowOrWorkerGlobalScope/atob +--- +
{{APIRef("HTML DOM")}}
+ +

A função WindowBase64.atob() decodifica uma string de dados que foi codificada através da codificação base-64. Você pode usar o método {{domxref("WindowBase64.btoa","window.btoa()")}} para codificar e transmitir dados que, se não codificados, podem causar problemas de comunicação. Após transmití-los pode-se usar o método window.atob() para decodificar os dados novamente. Por exemplo, você pode codificar, transmitir,  e decodificar caracteres de controle como valores ASCII de 0 a 31.

+ +

Para utilizar com strings Unicode ou UTF-8, veja esta nota em Base64 encoding and decoding e essa nota em window.btoa().

+ +

Sintaxe

+ +
var dadoDecodificado = window.atob(dadoCodificado);
+ +

Exemplo

+ +
var dadoCodificado = window.btoa("Olá, mundo"); // codifica a string
+var dadoDecodificado = window.atob(dadoCodificado); // decodifica a string
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG', '#dom-windowbase64-atob', 'WindowBase64.atob()')}}{{Spec2('HTML WHATWG')}}Nenhuma mudança desde a última versão, {{SpecName("HTML5.1")}}.
{{SpecName('HTML5.1', '#dom-windowbase64-atob', 'WindowBase64.atob()')}}{{Spec2('HTML5.1')}}Versão de {{SpecName("HTML WHATWG")}}. Nenhuma mudança.
{{SpecName("HTML5 W3C", "#dom-windowbase64-atob", "WindowBase64.atob()")}}{{Spec2('HTML5 W3C')}}Versão de {{SpecName("HTML WHATWG")}}. Criação do WindowBase64 (antes as propriedades ficavam no target).
+ +

Compatibilidade de navegadores

+ +
{{Compat("api.WindowOrWorkerGlobalScope.atob")}}
+ +
+ +

[1] atob() também está disponível para os componentes do XPCOM implementado em JavaScript, porém o objeto window não é global nos componentes.

+ +

[2] A partir do Firefox 27, atob() ignora todos os caracteres de espaço no argumento para seguir as últimas especificações do HTML5. ({{bug(711180)}})

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/windowbase64/index.html b/files/pt-br/web/api/windowbase64/index.html new file mode 100644 index 0000000000..40051820b4 --- /dev/null +++ b/files/pt-br/web/api/windowbase64/index.html @@ -0,0 +1,120 @@ +--- +title: WindowBase64 +slug: Web/API/WindowBase64 +tags: + - API + - HTML-DOM + - Helper + - NeedsTranslation + - TopicStub + - WindowBase64 +translation_of: Web/API/WindowOrWorkerGlobalScope +--- +

{{APIRef("HTML DOM")}}

+ +

The WindowBase64 helper contains utility methods to convert data to and from base64, a binary-to-text encoding scheme. For example it is used in data URIs.

+ +

There is no object of this type, though the context object, either the {{domxref("Window")}} for regular browsing scope, or the {{domxref("WorkerGlobalScope")}}  for workers, implements it.

+ +

Properties

+ +

This helper neither defines nor inherits any properties.

+ +

Methods

+ +

This helper does not inherit any methods.

+ +
+
{{domxref("WindowBase64.atob()")}}
+
Decodes a string of data which has been encoded using base-64 encoding.
+
{{domxref("WindowBase64.btoa()")}}
+
Creates a base-64 encoded ASCII string from a string of binary data.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#windowbase64', 'WindowBase64')}}{{Spec2('HTML WHATWG')}}No change since the latest snapshot, {{SpecName("HTML5.1")}}.
{{SpecName('HTML5.1', '#windowbase64', 'WindowBase64')}}{{Spec2('HTML5.1')}}Snapshot of {{SpecName("HTML WHATWG")}}. No change.
{{SpecName("HTML5 W3C", "#windowbase64", "WindowBase64")}}{{Spec2('HTML5 W3C')}}Snapshot of {{SpecName("HTML WHATWG")}}. Creation of WindowBase64 (properties where on the target before it).
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Basic support{{CompatGeckoDesktop(1)}} [1]{{CompatVersionUnknown}}10.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari Mobile
Basic support{{CompatGeckoMobile(1)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

[1]  atob() is also available to XPCOM components implemented in JavaScript, even though {{domxref("Window")}} is not the global object in components.

+ +

See also

+ + diff --git a/files/pt-br/web/api/windoweventhandlers/index.html b/files/pt-br/web/api/windoweventhandlers/index.html new file mode 100644 index 0000000000..5eff621233 --- /dev/null +++ b/files/pt-br/web/api/windoweventhandlers/index.html @@ -0,0 +1,189 @@ +--- +title: WindowEventHandlers +slug: Web/API/WindowEventHandlers +tags: + - API + - HTML-DOM + - Interface + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/API/WindowEventHandlers +--- +
{{APIRef("HTML DOM")}}
+ +

WindowEventHandlers descreve os manipuladores de eventos comuns a várias interfaces como {{domxref("Window")}}, ou {{domxref("HTMLBodyElement")}} e  {{domxref("HTMLFrameSetElement")}}. Cada uma dessas interfaces podendo implementar manipuladores de eventos específicos adicionais.

+ +

WindowEventHandlers não é uma interface e nenhum objeto desse tipo pode ser criado.

+ +

Properties

+ +

As propriedades de evento, no formulário onXYZ, são definidas no {{domxref("WindowEventHandlers")}}, e implementadas por {{domxref("Window")}}, e {{domxref("WorkerGlobalScope")}} para desenvolvedores web.

+ +
+
{{domxref("WindowEventHandlers.onafterprint")}}
+
É uma {{domxref("EventHandler")}} representando o código que será chamando quando o evento {{event("afterprint")}} é invocado.
+
{{domxref("WindowEventHandlers.onbeforeprint")}}
+
É um {{domxref("EventHandler")}} representando o código que será chamado quando o evento {{event("beforeprint")}} é invocado.
+
{{domxref("WindowEventHandlers.onbeforeunload")}}
+
É um {{domxref("EventHandler")}} representando o código que será chamado quando o evento  {{event("beforeunload")}} é invocado.
+
{{domxref("WindowEventHandlers.onhashchange")}}
+
É um {{domxref("EventHandler")}} representando o código que será chamado quando o evento {{event("hashchange")}} é invocado.
+
{{domxref("WindowEventHandlers.onlanguagechange")}} {{experimental_inline}}
+
É um {{domxref("EventHandler")}} representando o código que será chamado quando o evento {{event("languagechange")}} é invocado.
+
{{domxref("WindowEventHandlers.onmessage")}}
+
É um {{domxref("EventHandler")}} representando o código que será chamado quando o evento  {{event("message")}} é invocado.
+
{{domxref("WindowEventHandlers.onoffline")}}
+
É um {{domxref("EventHandler")}} representando o código que será chamado quando o evento  {{event("offline")}} é invocado.
+
{{domxref("WindowEventHandlers.ononline")}}
+
É um {{domxref("EventHandler")}} representando o código que será chamado quando o evento  {{event("online")}} é invocado.
+
{{domxref("WindowEventHandlers.onpagehide")}}
+
É um {{domxref("EventHandler")}} representando o código que será chamado quando o evento {{event("pagehide")}} é invocado.
+
{{domxref("WindowEventHandlers.onpageshow")}}
+
É um {{domxref("EventHandler")}} representando o código que será chamado quando o evento {{event("pageshow")}} é invocado.
+
{{domxref("WindowEventHandlers.onpopstate")}}
+
É um {{domxref("EventHandler")}} representando o código que será chamado quando o evento {{event("popstate")}} é invocado.
+
{{domxref("WindowEventHandlers.onresize")}}
+
É um {{domxref("EventHandler")}} representando o código que será chamado quando o evento {{event("resize")}} é invocado.
+
{{domxref("WindowEventHandlers.onstorage")}}
+
É um {{domxref("EventHandler")}} representando o código que será chamado quando o evento {{event("storage")}} é invocado.
+
{{domxref("WindowEventHandlers.onunload")}}
+
É um {{domxref("EventHandler")}} representando o código que será chamado quando o evento {{event("unload")}} é invocado.
+
+ +

Métodos

+ +

Esta interface não define métodos.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#windoweventhandlers', 'GlobalEventHandlers')}}{{Spec2('HTML WHATWG')}}No change since the latest snapshot, {{SpecName("HTML5.1")}}.
{{SpecName('HTML5.1', '#windoweventhandlers', 'GlobalEventHandlers')}}{{Spec2('HTML5.1')}}Snapshot of {{SpecName("HTML WHATWG")}}. Added onlanguage since the {{SpecName("HTML 5")}} snapshot.
{{SpecName("HTML5 W3C", "#windoweventhandlers", "GlobalEventHandlers")}}{{Spec2('HTML5 W3C')}}Snapshot of {{SpecName("HTML WHATWG")}}. Creation of WindowEventHandlers (properties where on the target before it).
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
onhashchange{{CompatGeckoDesktop(1.9.2)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
onlanguage{{experimental_inline}}{{CompatGeckoDesktop(32)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
onstorage{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
onhashchange{{CompatGeckoMobile(1.9.2)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
onlanguage{{experimental_inline}}{{CompatGeckoMobile(32)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
onstorage{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/windoweventhandlers/onhashchange/index.html b/files/pt-br/web/api/windoweventhandlers/onhashchange/index.html new file mode 100644 index 0000000000..5cca998fbe --- /dev/null +++ b/files/pt-br/web/api/windoweventhandlers/onhashchange/index.html @@ -0,0 +1,158 @@ +--- +title: WindowEventHandlers.onhashchange +slug: Web/API/WindowEventHandlers/onhashchange +translation_of: Web/API/WindowEventHandlers/onhashchange +--- +
+
{{APIRef("HTML DOM")}}
+
+ +

O evento hashchange é disparado quando a hash da window muda. (ver {{domxref("Window.location", "location.hash")}}).

+ +

Sintaxe

+ +
window.onhashchange = funcRef;
+
+ +

ou

+ +
<body onhashchange="funcRef();">
+
+ +

ou

+ +
window.addEventListener("hashchange", funcRef, false);
+
+ +

Parâmetros

+ +
+
funcRef
+
Referência a uma função
+
+ +

Exemplo

+ +
if ("onhashchange" in window) {
+    alert("O browser têm suporte ao evento hashchange!");
+}
+
+function locationHashChanged() {
+    if (location.hash === "#algointeressante") {
+        algoInteressante();
+    }
+}
+
+window.onhashchange = locationHashChanged;
+
+ +

O evento hashchange

+ +

O evento hashchange disparado possui os seguintes campos

+ + + + + + + + + + + + + + + + + + + +
CampoTipoDescrição
newURL {{gecko_minversion_inline("6.0")}}DOMStringA nova URL para a qual a janela está navegando.
oldURL {{gecko_minversion_inline("6.0")}}DOMStringA antiga URL da qual a janela veio.
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG', '#windoweventhandlers', 'GlobalEventHandlers')}}{{Spec2('HTML WHATWG')}} 
{{SpecName('HTML5.1', '#windoweventhandlers', 'GlobalEventHandlers')}}{{Spec2('HTML5.1')}} 
{{SpecName("HTML5 W3C", "#windoweventhandlers", "GlobalEventHandlers")}}{{Spec2('HTML5 W3C')}} 
+ +

Compatibilidade dos Browsers

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte Básico5.0{{CompatGeckoDesktop("1.9.2")}} +

8.0

+ +

atributos oldURL/newURL não são suportados.

+
10.65.0
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte Básico2.2{{CompatGeckoMobile("1.9.2")}}9.011.05.0
+
+ + diff --git a/files/pt-br/web/api/windoweventhandlers/onpopstate/index.html b/files/pt-br/web/api/windoweventhandlers/onpopstate/index.html new file mode 100644 index 0000000000..78bfa8fdc1 --- /dev/null +++ b/files/pt-br/web/api/windoweventhandlers/onpopstate/index.html @@ -0,0 +1,61 @@ +--- +title: WindowEventHandlers.onpopstate +slug: Web/API/WindowEventHandlers/onpopstate +translation_of: Web/API/WindowEventHandlers/onpopstate +--- +
{{APIRef}} {{gecko_minversion_header("2")}}
+ +

Sumário

+ +

Um evento manipulador para um evento popstate na janela

+ +

Um evento popstate é disparado para a janela toda vez que o histórico de atividades mudar entre dois históricos de entradas para o mesmo documento. Se o histórico de entrada a ser ativo for criado por uma chamada para history.pushState() ou for afetado por um chamada history.replaceState(), o estado do evento popstate contém uma cópia do histórico do estado de entrada do objeto.

+ +

Note que apenas chamando history.pushState() ou history.replaceState() não irá desencadear um evento popstate. O evento popstate é apenas desencadeado  por uma ação do navegador com clicar em um botão de voltar (ou chamar history.back() em JavaScript). E o evento é apenas desencadeado quando o usuário navega entre dois históricos de entrada do mesmo documento.
+
+ Navegadores tendem a lidar com o evento popstate diferente no carregamento da página. Chrome (anterior versão 34) e Safari sempre emite um evento popstate no carregamento da página, mas Firefox não.

+ +

Sintaxe

+ +
window.onpopstate = funcRef;
+
+ + + +

O evento popstate

+ +

Como um exemplo, a página no http://example.com/example.html roda o seguinte código que vai gerar alertas conforme indicado:

+ +
window.onpopstate = function(event) {
+  alert("location: " + document.location + ", state: " + JSON.stringify(event.state));
+};
+
+history.pushState({page: 1}, "title 1", "?page=1");
+history.pushState({page: 2}, "title 2", "?page=2");
+history.replaceState({page: 3}, "title 3", "?page=3");
+history.back(); // alertas "location: http://example.com/example.html?page=1, state: {"page":1}"
+history.back(); // alertas "location: http://example.com/example.html, state: null
+history.go(2);  // alertas "location: http://example.com/example.html?page=3, state: {"page":3}
+
+ +
+
Observe que mesmo que a entrada do histórico inicial (para http://example.com/example.html) não tem objeto estado associado com ele, um evento popstate é ainda disparado quando nós ativamos essa entrada depois da segunda chamada do history.back().
+
+
+ +

Especificação

+ + + +

Veja também

+ + diff --git a/files/pt-br/web/api/windoweventhandlers/onstorage/index.html b/files/pt-br/web/api/windoweventhandlers/onstorage/index.html new file mode 100644 index 0000000000..48820c0bfa --- /dev/null +++ b/files/pt-br/web/api/windoweventhandlers/onstorage/index.html @@ -0,0 +1,101 @@ +--- +title: WindowEventHandlers.onstorage +slug: Web/API/WindowEventHandlers/onstorage +tags: + - API + - Armazenamento web + - Propriedade + - Referencia + - WindowEventHandlers +translation_of: Web/API/WindowEventHandlers/onstorage +--- +
{{ ApiRef() }}
+ +

A propriedade WindowEventHandlers.onstorage contém um manipulador de eventos que executa quando o evento {{event("storage")}} dispara. Isto ocorre quando a área de armazenamento é mudada. (ex. um novo item é armazenado.)

+ +

Sintaxe

+ +
windowObj.onstorage = function() { ... };
+ +

Exemplos

+ +
window.onstorage = function(e) {
+  console.log('The ' + e.key + ' key has been changed from ' + e.oldValue + ' to ' + e.newValue + '.');
+};
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG','webappapis.html#handler-window-onstorage','onstorage')}}{{Spec2('HTML WHATWG')}} 
+ +

Compatibilidade entre navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop(45)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidAndroid WebviewEdgeFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome para Android
Suporte básico{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile(45)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
diff --git a/files/pt-br/web/api/windoworworkerglobalscope/fetch/index.html b/files/pt-br/web/api/windoworworkerglobalscope/fetch/index.html new file mode 100644 index 0000000000..804f04fc45 --- /dev/null +++ b/files/pt-br/web/api/windoworworkerglobalscope/fetch/index.html @@ -0,0 +1,305 @@ +--- +title: WindowOrWorkerGlobalScope.fetch() +slug: Web/API/WindowOrWorkerGlobalScope/fetch +translation_of: Web/API/WindowOrWorkerGlobalScope/fetch +--- +
{{APIRef("Fetch API")}}
+ +

O método fetch() do mixin {{domxref("WindowOrWorkerGlobalScope")}} inicia um processo de busca de um recurso da rede. Este, retorna uma promessa que resolve o objeto {{domxref("Response")}} que representa a resposta a sua requisição. 

+ +

WorkerOrGlobalScope é implementado por {{domxref("Window")}} e {{domxref("WorkerGlobalScope")}}, o que significa que o método fetch() está disponível em praticamente qualquer contexto em que você possa querer obter recursos.

+ +

Uma promessa {{domxref("WindowOrWorkerGlobalScope.fetch","fetch()")}} rejeita com um {{jsxref("TypeError")}} quando um erro de rede é encontrado, embora isso geralmente signifique um problema de permissões ou similar. Uma verificação precisa de um fetch() bem-sucedido incluiria a verificação de uma promessa resolvida, e depois verificando se a propriedade {{domxref("Response.ok")}} possui valor true. Um status HTTP 404 não constitui um erro de rede.

+ +

O método fetch() é controlado pela diretiva connect-src da Content Security Policy em vez da diretiva dos recursos que está recuperando.

+ +
+

Nota: Os parâmetros do método fetch() são idênticos aos do construtor {{domxref("Request.Request","Request()")}}.

+
+ +

Sintaxe

+ +
Promise<Response> fetch(input[, init]);
+ +

Parâmetros

+ +
+
input
+
Isto define o recurso que você deseja buscar. Isto pode ser: +
    +
  • Um {{domxref("USVString")}} contendo uma URL direta para o recurso que você quer obter. Alguns navegadores aceitam blob: e data: como esquemas.
  • +
  • Um objeto {{domxref("Request")}}.
  • +
+
+
init {{optional_inline}}
+
Um objeto opcional que contém configurações personalizadas que você pode aplicar à requisição. As opções possíveis são: +
    +
  • method: Método HTTP, por exemplo, GET, POST.
  • +
  • headers: Qualquer cabeçalho que você queira adicionar à sua requisição, contido dentro de um objeto {{domxref("Headers")}} ou um objeto literal com valores {{domxref("ByteString")}}.
  • +
  • body: Qualquer corpo que você queira adicionar à sua requisição: podendo ser um {{domxref("Blob")}}, {{domxref("BufferSource")}}, {{domxref("FormData")}}, {{domxref("URLSearchParams")}}, ou um objeto {{domxref("USVString")}}. Note que uma requisição usando os métodos GET ou HEAD não pode ter um corpo.
  • +
  • mode: O modo que deseja usar para a requisição, por exemplo, cors, no-cors, ou same-origin.
  • +
  • credentials: A credencial que deseja usar para a requisição: omit, same-origin, ou include. Para enviar automaticamente cookies para o domínio atual, esta opção deve ser fornecida. Começando com o Chrome 50, essa propriedade também usa uma instância {{domxref("FederatedCredential")}} ou uma instância {{domxref("PasswordCredential")}}.
  • +
  • cache: O modo de cache que deseja usar na requisição: default, no-store, reload, no-cache, force-cache, ou only-if-cached.
  • +
  • redirect: O modo de redirecionamento pode usar: follow (segue automaticamente o redirecionamento), error (aborta com um erro se ocorrer um redirecionamento), ou manual (manipula redirecionamentos manualmente). No Chrome o padrão foi follow antes do Chrome 47 e manual a partir do Chrome 47.
  • +
  • referrer: Um {{domxref("USVString")}} especificando no-referrerclient, ou uma URL. O padrão é client.
  • +
  • referrerPolicy: Especifica o valor do cabeçalho HTTP referer. Pode ser um destes: no-referrer, no-referrer-when-downgrade, origin, origin-when-cross-origin, unsafe-url.
  • +
  • integrity: Contém o valor de integridade de subrecurso da requisição (por exemplo, sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=).
  • +
  • signal: Uma instância do objeto {{domxref("FetchSignal")}}; permite que você se comunique com um pedido de busca e controle-o através de um {{domxref("FetchController")}}. {{non-standard_inline}}
  • +
  • observe: Um objeto {{domxref("ObserverCallback")}} — o objetivo exclusivo deste objeto é fornecer uma função de retorno de chamada que é executada quando a solicitação fetch é executada. Isto retorna um objeto {{domxref("FetchObserver")}} que pode ser usado para recuperar informações sobre o status de uma solicitação fetch. {{non-standard_inline}}
  • +
+
+
+ +

Valor de Retorno

+ +

Uma {{domxref("Promise")}} que resolve um objeto {{domxref("Response")}}.

+ +

Exceptions

+ + + + + + + + + + + + + + +
TipoDescrição
TypeErrorDesdo o Firefox 43, fetch()
+ lançará um TypeError se a URL tiver credenciais, como http://user:password@example.com.
+ +

Example

+ +

In our Fetch Request example (see Fetch Request live) we create a new {{domxref("Request")}} object using the relevant constructor, then fetch it using a fetch() call. Since we are fetching an image, we run {{domxref("Body.blob()")}} on the response to give it the proper MIME type so it will be handled properly, then create an Object URL of it and display it in an {{htmlelement("img")}} element.

+ +
var myImage = document.querySelector('img');
+
+var myRequest = new Request('flowers.jpg');
+
+fetch(myRequest).then(function(response) {
+  return response.blob();
+}).then(function(response) {
+  var objectURL = URL.createObjectURL(response);
+  myImage.src = objectURL;
+});
+ +

In our Fetch with init then Request example (see Fetch Request init live) we do the same thing except that we pass in an init object when we invoke fetch():

+ +
var myImage = document.querySelector('img');
+
+var myHeaders = new Headers();
+myHeaders.append('Content-Type', 'image/jpeg');
+
+var myInit = { method: 'GET',
+               headers: myHeaders,
+               mode: 'cors',
+               cache: 'default' };
+
+var myRequest = new Request('flowers.jpg');
+
+fetch(myRequest,myInit).then(function(response) {
+  ...
+});
+ +

Note that you could also pass the init object in with the Request constructor to get the same effect, e.g.:

+ +
var myRequest = new Request('flowers.jpg', myInit);
+ +

You can also use an object literal as headers in init.

+ +
var myInit = { method: 'GET',
+               headers: {
+                   'Content-Type': 'image/jpeg'
+               },
+               mode: 'cors',
+               cache: 'default' };
+
+var myRequest = new Request('flowers.jpg', myInit);
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fetch','#fetch-method','fetch()')}}{{Spec2('Fetch')}}Defined in a WindowOrWorkerGlobalScope partial in the newest spec.
{{SpecName('Fetch','#dom-global-fetch','fetch()')}}{{Spec2('Fetch')}}Initial definition
{{SpecName('Credential Management')}}{{Spec2('Credential Management')}}Adds {{domxref("FederatedCredential")}} or {{domxref("PasswordCredential")}} instance as a possible value for init.credentials.
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(42)}}14{{CompatGeckoDesktop(34)}}[1]
+ {{CompatGeckoDesktop(39)}}
+ {{CompatGeckoDesktop(52)}}[2]
{{CompatNo}}29
+ 28[1]
{{CompatNo}}
Streaming response body{{CompatChrome(43)}}14{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Support for blob: and data:{{CompatChrome(48)}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
referrerPolicy{{CompatChrome(52)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}39{{CompatUnknown}}
signal and observer{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}[3]{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatChrome(42)}}14{{CompatGeckoMobile(52)}}[2]{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatChrome(42)}}
Streaming response body{{CompatNo}}{{CompatChrome(43)}}14{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(43)}}
Support for blob: and data:{{CompatNo}}{{CompatChrome(43)}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(43)}}
referrerPolicy{{CompatNo}}{{CompatChrome(52)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}39{{CompatUnknown}}{{CompatChrome(52)}}
signal and observer{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}[3]{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
+
+ +

[1] API is implemented behind a preference.

+ +

[2] fetch() now defined on {{domxref("WindowOrWorkerGlobalScope")}} mixin.

+ +

[3] Hidden behind a preference in 55+ Nightly. In about:config, you need to create two new boolean prefs — dom.fetchObserver.enabled and dom.fetchController.enabled — and set the values of both to true.

+ +

See also

+ + diff --git a/files/pt-br/web/api/windoworworkerglobalscope/index.html b/files/pt-br/web/api/windoworworkerglobalscope/index.html new file mode 100644 index 0000000000..d1321eb031 --- /dev/null +++ b/files/pt-br/web/api/windoworworkerglobalscope/index.html @@ -0,0 +1,189 @@ +--- +title: WindowOrWorkerGlobalScope +slug: Web/API/WindowOrWorkerGlobalScope +tags: + - API + - DOM + - DOM API + - NeedsTranslation + - Service Worker + - TopicStub + - Window + - WindowOrWorkerGlobalScope + - Worker + - WorkerGlobalScope +translation_of: Web/API/WindowOrWorkerGlobalScope +--- +
{{ApiRef()}}
+ +

O mixin WindowOrWorkerGlobalScope descreve vários recursos comuns às interfaces Window e WorkerGlobalScope. Cada uma dessas interfaces pode, obviamente, adicionar mais recursos além dos listados abaixo.

+ +
+

Nota: WindowOrWorkerGlobalScope é um mixin e não uma interface; você não pode atualmente criar um objeto do tipo WindowOrWorkerGlobalScope.

+
+ +

Properties

+ +

These properties are defined on the {{domxref("WindowOrWorkerGlobalScope")}} mixin, and implemented by {{domxref("Window")}} and {{domxref("WorkerGlobalScope")}}.

+ +
+
+
{{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 origin of the global scope, serialized as a string.
+
+
+ +

Methods

+ +

These properties are defined on the {{domxref("WindowOrWorkerGlobalScope")}} mixin, and implemented by {{domxref("Window")}} and {{domxref("WorkerGlobalScope")}}.

+ +
+
{{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("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.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("HTML WHATWG",'webappapis.html#windoworworkerglobalscope-mixin', 'WindowOrWorkerGlobalScope mixin')}}{{Spec2('HTML WHATWG')}}This is where the main mixin is defined.
{{SpecName('Fetch','#fetch-method','fetch()')}}{{Spec2('Fetch')}}Definition of the fetch() method.
{{SpecName('Service Workers', '#self-caches', 'caches')}}{{Spec2('Service Workers')}}Definition of the caches property.
{{SpecName('IndexedDB 2', '#dom-windoworworkerglobalscope-indexeddb', 'indexedDB')}}{{Spec2('IndexedDB 2')}}Definition of the indexedDB property.
{{SpecName('Secure Contexts', 'webappapis.html#dom-origin', 'isSecureContext')}}{{Spec2('Secure Contexts')}}Definition of the isSecureContext property.
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureFirefox (Gecko)ChromeEdgeInternet ExplorerOperaSafari
Basic support{{CompatGeckoDesktop(52)}}54{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
origin{{CompatGeckoDesktop(54)}}59{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewEdgeFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(52)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}54
origin{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(54)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}59
+
+ +

 

+ +

See also

+ + diff --git a/files/pt-br/web/api/windoworworkerglobalscope/setinterval/index.html b/files/pt-br/web/api/windoworworkerglobalscope/setinterval/index.html new file mode 100644 index 0000000000..b7ade5307d --- /dev/null +++ b/files/pt-br/web/api/windoworworkerglobalscope/setinterval/index.html @@ -0,0 +1,629 @@ +--- +title: WindowOrWorkerGlobalScope.setInterval() +slug: Web/API/WindowOrWorkerGlobalScope/setInterval +translation_of: Web/API/WindowOrWorkerGlobalScope/setInterval +--- +
{{APIRef("HTML DOM")}}
+ +
 
+ +

O método setInterval() oferecido das interfaces {{domxref("Window")}} e {{domxref("Worker")}}, repetem chamadas de funções or executam trechos de código, com um tempo de espera fixo entre cada chamada. Isso retorna um ID único para o intervalo, podendo remove-lo mais tarde apenas o chamando {{domxref("WindowOrWorkerGlobalScope.clearInterval", "clearInterval()")}}. Este metodo é definido pelo mixin {{domxref("WindowOrWorkerGlobalScope")}}.

+ +

Sintaxe.

+ +
var intervalID = scope.setInterval(func, delay[, param1, param2, ...]);
+var intervalID = scope.setInterval(code, delay);
+
+ +

Parâmetros

+ +
+
func
+
Uma {{jsxref("function")}} para ser executada a cada delay em milisegundos.  Não é passado nenhum parâmetro para a função, e não retorna nenhum valor esperado.
+
code
+
Uma sintaxe opcional permite você incuir uma string ao invés de uma função, no qual é compilado e executada a cada delay em milisegundos. Esta sintaxe não é recomendada pelos mesmos motivos que envolvem riscos de segurança de {{jsxref("eval", "eval()")}}.
+
delay
+
O tempo, em milisegundos (milésimos de segundo), o temporizador deve atrasar entre cada execução de uma especifica função ou código. Se esse parâmetro for menos que 10, um valor de 10 é usado. Note que o atraso pode vir a ser mais longo; veja {{SectionOnPage("/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout", "Reasons for delays longer than specified")}} para exemplos.
+
param1, ..., paramN {{optional_inline}}
+
Parâmetros adicionais que são passados através da função especificada pela func quando o temporizador expirar.
+
+ +
+

Note: Passing additional parameters to setInterval() in the first syntax does not work in Internet Explorer 9 and earlier. If you want to enable this functionality on that browser, you must use a polyfill (see the Callback arguments section).

+
+ +

Return value

+ +

intervalID retornado é um número, non-zero valor que identifica o temporizador criado pela chamada do setInterval(); este valor pode ser passado para {{domxref("WindowOrWorkerGlobalScope.clearInterval()")}} afim de cancelar o timeout.

+ +

Isso pode ser útil, estar ciente que o setInterval() e {{domxref("WindowOrWorkerGlobalScope.setTimeout", "setTimeout()")}} compartilham o mesmo grupo de IDs, e que o clearInterval() e {{domxref("WindowOrWorkerGlobalScope.clearTimeout", "clearTimeout()")}} podem tecnicamente serem usados em conjunto. Para deixar claro, contudo, você deve sempre tentar evitar combina-los, afim de evitar confusão na manutenção do seu código.

+ +
Note: The delay parameter is converted to a signed 32-bit integer. This effectively limits delay to 2147483647 ms, since it's specified as a signed integer in the IDL.
+ +

Exemplos

+ +

Exemplo 1: Sintaxe básica

+ +

O seguinte exemplo mostra a sintaxe básica do setInterval()

+ +
var intervalID = window.setInterval(myCallback, 500);
+
+function myCallback() {
+  // Your code here
+}
+
+ +

Exemplo 2: Alternando duas cores

+ +

O seguinte exemplo chama a função flashtext() uma vez por segundo até o botão de parar ser pressionado.

+ +
<!DOCTYPE html>
+<html>
+<head>
+  <meta charset="UTF-8" />
+  <title>setInterval/clearInterval example</title>
+
+  <script>
+    var nIntervId;
+
+    function changeColor() {
+      nIntervId = setInterval(flashText, 1000);
+    }
+
+    function flashText() {
+      var oElem = document.getElementById('my_box');
+      oElem.style.color = oElem.style.color == 'red' ? 'blue' : 'red';
+      // oElem.style.color == 'red' ? 'blue' : 'red' is a ternary operator.
+    }
+
+    function stopTextColor() {
+      clearInterval(nIntervId);
+    }
+  </script>
+</head>
+
+<body onload="changeColor();">
+  <div id="my_box">
+    <p>Hello World</p>
+  </div>
+
+  <button onclick="stopTextColor();">Stop</button>
+</body>
+</html>
+
+ +

Exemplo 3: Simulação de máquina de escrever

+ +

O seguinte exemplo simula uma máquina de escrever primeiro limpando e digitando lentamente o conteúdo para  NodeList que corresponde a um grupo especificado de seletores.

+ +
<!DOCTYPE html>
+<html>
+<head>
+<meta charset="UTF-8" />
+<title>JavaScript Typewriter - MDN Example</title>
+<script>
+  function Typewriter (sSelector, nRate) {
+
+  function clean () {
+    clearInterval(nIntervId);
+    bTyping = false;
+    bStart = true;
+    oCurrent = null;
+    aSheets.length = nIdx = 0;
+  }
+
+  function scroll (oSheet, nPos, bEraseAndStop) {
+    if (!oSheet.hasOwnProperty('parts') || aMap.length < nPos) { return true; }
+
+    var oRel, bExit = false;
+
+    if (aMap.length === nPos) { aMap.push(0); }
+
+    while (aMap[nPos] < oSheet.parts.length) {
+      oRel = oSheet.parts[aMap[nPos]];
+
+      scroll(oRel, nPos + 1, bEraseAndStop) ? aMap[nPos]++ : bExit = true;
+
+      if (bEraseAndStop && (oRel.ref.nodeType - 1 | 1) === 3 && oRel.ref.nodeValue) {
+        bExit = true;
+        oCurrent = oRel.ref;
+        sPart = oCurrent.nodeValue;
+        oCurrent.nodeValue = '';
+      }
+
+      oSheet.ref.appendChild(oRel.ref);
+      if (bExit) { return false; }
+    }
+
+    aMap.length--;
+    return true;
+  }
+
+  function typewrite () {
+    if (sPart.length === 0 && scroll(aSheets[nIdx], 0, true) && nIdx++ === aSheets.length - 1) { clean(); return; }
+
+    oCurrent.nodeValue += sPart.charAt(0);
+    sPart = sPart.slice(1);
+  }
+
+  function Sheet (oNode) {
+    this.ref = oNode;
+    if (!oNode.hasChildNodes()) { return; }
+    this.parts = Array.prototype.slice.call(oNode.childNodes);
+
+    for (var nChild = 0; nChild < this.parts.length; nChild++) {
+      oNode.removeChild(this.parts[nChild]);
+      this.parts[nChild] = new Sheet(this.parts[nChild]);
+    }
+  }
+
+  var
+    nIntervId, oCurrent = null, bTyping = false, bStart = true,
+    nIdx = 0, sPart = "", aSheets = [], aMap = [];
+
+  this.rate = nRate || 100;
+
+  this.play = function () {
+    if (bTyping) { return; }
+    if (bStart) {
+      var aItems = document.querySelectorAll(sSelector);
+
+      if (aItems.length === 0) { return; }
+      for (var nItem = 0; nItem < aItems.length; nItem++) {
+        aSheets.push(new Sheet(aItems[nItem]));
+        /* Uncomment the following line if you have previously hidden your elements via CSS: */
+        // aItems[nItem].style.visibility = "visible";
+      }
+
+      bStart = false;
+    }
+
+    nIntervId = setInterval(typewrite, this.rate);
+    bTyping = true;
+  };
+
+  this.pause = function () {
+    clearInterval(nIntervId);
+    bTyping = false;
+  };
+
+  this.terminate = function () {
+    oCurrent.nodeValue += sPart;
+    sPart = "";
+    for (nIdx; nIdx < aSheets.length; scroll(aSheets[nIdx++], 0, false));
+    clean();
+  };
+}
+
+/* usage: */
+var oTWExample1 = new Typewriter(/* elements: */ '#article, h1, #info, #copyleft', /* frame rate (optional): */ 15);
+
+/* default frame rate is 100: */
+var oTWExample2 = new Typewriter('#controls');
+
+/* you can also change the frame rate value modifying the "rate" property; for example: */
+// oTWExample2.rate = 150;
+
+onload = function () {
+  oTWExample1.play();
+  oTWExample2.play();
+};
+</script>
+<style type="text/css">
+span.intLink, a, a:visited {
+  cursor: pointer;
+  color: #000000;
+  text-decoration: underline;
+}
+
+#info {
+  width: 180px;
+  height: 150px;
+  float: right;
+  background-color: #eeeeff;
+  padding: 4px;
+  overflow: auto;
+  font-size: 12px;
+  margin: 4px;
+  border-radius: 5px;
+  /* visibility: hidden; */
+}
+</style>
+</head>
+
+<body>
+
+<p id="copyleft" style="font-style: italic; font-size: 12px; text-align: center;">CopyLeft 2012 by <a href="https://developer.mozilla.org/" target="_blank">Mozilla Developer Network</a></p>
+<p id="controls" style="text-align: center;">[&nbsp;<span class="intLink" onclick="oTWExample1.play();">Play</span> | <span class="intLink" onclick="oTWExample1.pause();">Pause</span> | <span class="intLink" onclick="oTWExample1.terminate();">Terminate</span>&nbsp;]</p>
+<div id="info">
+Vivamus blandit massa ut metus mattis in fringilla lectus imperdiet. Proin ac ante a felis ornare vehicula. Fusce pellentesque lacus vitae eros convallis ut mollis magna pellentesque. Pellentesque placerat enim at lacus ultricies vitae facilisis nisi fringilla. In tincidunt tincidunt tincidunt.
+</div>
+<h1>JavaScript Typewriter</h1>
+
+<div id="article">
+<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam ultrices dolor ac dolor imperdiet ullamcorper. Suspendisse quam libero, luctus auctor mollis sed, malesuada condimentum magna. Quisque in ante tellus, in placerat est. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Donec a mi magna, quis mattis dolor. Etiam sit amet ligula quis urna auctor imperdiet nec faucibus ante. Mauris vel consectetur dolor. Nunc eget elit eget velit pulvinar fringilla consectetur aliquam purus. Curabitur convallis, justo posuere porta egestas, velit erat ornare tortor, non viverra justo diam eget arcu. Phasellus adipiscing fermentum nibh ac commodo. Nam turpis nunc, suscipit a hendrerit vitae, volutpat non ipsum.</p>
+<form>
+<p>Phasellus ac nisl lorem: <input type="text" /><br />
+<textarea style="width: 400px; height: 200px;">Nullam commodo suscipit lacus non aliquet. Phasellus ac nisl lorem, sed facilisis ligula. Nam cursus lobortis placerat. Sed dui nisi, elementum eu sodales ac, placerat sit amet mauris. Pellentesque dapibus tellus ut ipsum aliquam eu auctor dui vehicula. Quisque ultrices laoreet erat, at ultrices tortor sodales non. Sed venenatis luctus magna, ultricies ultricies nunc fringilla eget. Praesent scelerisque urna vitae nibh tristique varius consequat neque luctus. Integer ornare, erat a porta tempus, velit justo fermentum elit, a fermentum metus nisi eu ipsum. Vivamus eget augue vel dui viverra adipiscing congue ut massa. Praesent vitae eros erat, pulvinar laoreet magna. Maecenas vestibulum mollis nunc in posuere. Pellentesque sit amet metus a turpis lobortis tempor eu vel tortor. Cras sodales eleifend interdum.</textarea></p>
+<p><input type="submit" value="Send" />
+</form>
+<p>Duis lobortis sapien quis nisl luctus porttitor. In tempor semper libero, eu tincidunt dolor eleifend sit amet. Ut nec velit in dolor tincidunt rhoncus non non diam. Morbi auctor ornare orci, non euismod felis gravida nec. Curabitur elementum nisi a eros rutrum nec blandit diam placerat. Aenean tincidunt risus ut nisi consectetur cursus. Ut vitae quam elit. Donec dignissim est in quam tempor consequat. Aliquam aliquam diam non felis convallis suscipit. Nulla facilisi. Donec lacus risus, dignissim et fringilla et, egestas vel eros. Duis malesuada accumsan dui, at fringilla mauris bibStartum quis. Cras adipiscing ultricies fermentum. Praesent bibStartum condimentum feugiat.</p>
+<p>Nam faucibus, ligula eu fringilla pulvinar, lectus tellus iaculis nunc, vitae scelerisque metus leo non metus. Proin mattis lobortis lobortis. Quisque accumsan faucibus erat, vel varius tortor ultricies ac. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nec libero nunc. Nullam tortor nunc, elementum a consectetur et, ultrices eu orci. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque a nisl eu sem vehicula egestas.</p>
+</div>
+</body>
+</html>
+ +

View this demo in action. See also: clearInterval().

+ +

Argumentos callback

+ +

Como já foi discutido, Internet Explorer 9 e versões anteriores não suportam passar argumentos para a função callback em ambos setTimeout() ou setInterval(). O seguinte código IE-specific demonstra um método para superar esta limitação. Para usar, apenas adicione o seguinte código no topo do seu script.

+ +
/*\
+|*|
+|*|  IE-specific polyfill that enables the passage of arbitrary arguments to the
+|*|  callback functions of javascript timers (HTML5 standard syntax).
+|*|
+|*|  https://developer.mozilla.org/en-US/docs/Web/API/window.setInterval
+|*|  https://developer.mozilla.org/User:fusionchess
+|*|
+|*|  Syntax:
+|*|  var timeoutID = window.setTimeout(func, delay[, param1, param2, ...]);
+|*|  var timeoutID = window.setTimeout(code, delay);
+|*|  var intervalID = window.setInterval(func, delay[, param1, param2, ...]);
+|*|  var intervalID = window.setInterval(code, delay);
+|*|
+\*/
+
+if (document.all && !window.setTimeout.isPolyfill) {
+  var __nativeST__ = window.setTimeout;
+  window.setTimeout = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */) {
+    var aArgs = Array.prototype.slice.call(arguments, 2);
+    return __nativeST__(vCallback instanceof Function ? function () {
+      vCallback.apply(null, aArgs);
+    } : vCallback, nDelay);
+  };
+  window.setTimeout.isPolyfill = true;
+}
+
+if (document.all && !window.setInterval.isPolyfill) {
+  var __nativeSI__ = window.setInterval;
+  window.setInterval = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */) {
+    var aArgs = Array.prototype.slice.call(arguments, 2);
+    return __nativeSI__(vCallback instanceof Function ? function () {
+      vCallback.apply(null, aArgs);
+    } : vCallback, nDelay);
+  };
+  window.setInterval.isPolyfill = true;
+}
+
+ +

Outra possibilidade é uso uma função anônima para chama o callback, apesar de que esta solução seja um pouco mais pesada. Exemplo:

+ +
var intervalID = setInterval(function() { myFunc('one', 'two', 'three'); }, 1000);
+ +

Outra possibilidade é usar o function's bind. Exemplo:

+ +
var intervalID = setInterval(function(arg1) {}.bind(undefined, 10), 1000);
+ +

{{h3_gecko_minversion("Inactive tabs", "5.0")}}

+ +

Starting in Gecko 5.0 {{geckoRelease("5.0")}}, intervals are clamped to fire no more often than once per second in inactive tabs.

+ +

O problema do "this"

+ +

Quando você passa um método para setInterval() ou qualquer outra função, ela é chamada com o valor do this errado. Este problema é explicado em detalhes em JavaScript reference.

+ +

Explicação

+ +

O código executado pelo setInterval() roda em um contexto de execução separado da função que foi chamada. Como uma consequência, o this da função chamada, é setado como o objeto window (ou global), esse não é o mesmo valor do this para a função chamada em setTimeout. veja o seguinte exemplo (que usa setTimeout() ao invés de setInterval() - o problema segue para ambos os temporizadores)

+ +
myArray = ['zero', 'one', 'two'];
+
+myArray.myMethod = function (sProperty) {
+    alert(arguments.length > 0 ? this[sProperty] : this);
+};
+
+myArray.myMethod(); // prints "zero,one,two"
+myArray.myMethod(1); // prints "one"
+setTimeout(myArray.myMethod, 1000); // prints "[object Window]" after 1 second
+setTimeout(myArray.myMethod, 1500, "1"); // prints "undefined" after 1,5 seconds
+// passing the 'this' object with .call won't work
+// because this will change the value of this inside setTimeout itself
+// while we want to change the value of this inside myArray.myMethod
+// in fact, it will be an error because setTimeout code expects this to be the window object:
+setTimeout.call(myArray, myArray.myMethod, 2000); // error: "NS_ERROR_XPC_BAD_OP_ON_WN_PROTO: Illegal operation on WrappedNative prototype object"
+setTimeout.call(myArray, myArray.myMethod, 2500, 2); // same error
+
+ +

 

+ +

Como você pode ver, não há maneiras de passar o objeto this para a função callback.

+ +

 

+ +

Uma possível solução

+ +

Um possível caminho para resolver o problema do this, é sobreescrever as duas funções globais nativas setTimeout() ou setInterval() com duas non-native que permitem sua invocação através do método Function.prototype.call. O seguinte exemplo mostra a possível substituição.

+ +
// Enable the passage of the 'this' object through the JavaScript timers
+
+var __nativeST__ = window.setTimeout, __nativeSI__ = window.setInterval;
+
+window.setTimeout = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */) {
+  var oThis = this, aArgs = Array.prototype.slice.call(arguments, 2);
+  return __nativeST__(vCallback instanceof Function ? function () {
+    vCallback.apply(oThis, aArgs);
+  } : vCallback, nDelay);
+};
+
+window.setInterval = function (vCallback, nDelay /*, argumentToPass1, argumentToPass2, etc. */) {
+  var oThis = this, aArgs = Array.prototype.slice.call(arguments, 2);
+  return __nativeSI__(vCallback instanceof Function ? function () {
+    vCallback.apply(oThis, aArgs);
+  } : vCallback, nDelay);
+};
+ +
These two replacements also enable the HTML5 standard passage of arbitrary arguments to the callback functions of timers in IE. So they can be used as non-standard-compliant polyfills also. See the callback arguments paragraph for a standard-compliant polyfill.
+ +

Teste da nova implementação:

+ +
myArray = ['zero', 'one', 'two'];
+
+myArray.myMethod = function (sProperty) {
+    alert(arguments.length > 0 ? this[sProperty] : this);
+};
+
+setTimeout(alert, 1500, 'Hello world!'); // the standard use of setTimeout and setInterval is preserved, but...
+setTimeout.call(myArray, myArray.myMethod, 2000); // prints "zero,one,two" after 2 seconds
+setTimeout.call(myArray, myArray.myMethod, 2500, 2); // prints "two" after 2,5 seconds
+
+ +

Outra, mais complexa, solução para o problema do this é the following framework.

+ +
JavaScript 1.8.5 introduces the Function.prototype.bind() method, which lets you specify the value that should be used as this for all calls to a given function. This lets you easily bypass problems where it's unclear what this will be, depending on the context from which your function was called. Also, ES2015 supports arrow functions, with lexical this allowing us to write setInterval( () => this.myMethod) if we're inside myArray method.
+ +

MiniDaemon - A framework for managing timers

+ +

In pages requiring many timers, it can often be difficult to keep track of all of the running timer events. One approach to solving this problem is to store information about the state of a timer in an object. Following is a minimal example of such an abstraction. The constructor architecture explicitly avoids the use of closures. It also offers an alternative way to pass the this object to the callback function (see The "this" problem for details). The following code is also available on GitHub.

+ +
For a more complex but still modular version of it (Daemon) see JavaScript Daemons Management. This more complex version is nothing but a big and scalable collection of methods for the Daemon constructor. However, the Daemon constructor itself is nothing but a clone of MiniDaemon with an added support for init and onstart functions declarable during the instantiation of the daemon. So the MiniDaemon framework remains the recommended way for simple animations, because Daemon without its collection of methods is essentially a clone of it.
+ +

minidaemon.js

+ +
/*\
+|*|
+|*|  :: MiniDaemon ::
+|*|
+|*|  Revision #2 - September 26, 2014
+|*|
+|*|  https://developer.mozilla.org/en-US/docs/Web/API/window.setInterval
+|*|  https://developer.mozilla.org/User:fusionchess
+|*|  https://github.com/madmurphy/minidaemon.js
+|*|
+|*|  This framework is released under the GNU Lesser General Public License, version 3 or later.
+|*|  http://www.gnu.org/licenses/lgpl-3.0.html
+|*|
+\*/
+
+function MiniDaemon (oOwner, fTask, nRate, nLen) {
+  if (!(this && this instanceof MiniDaemon)) { return; }
+  if (arguments.length < 2) { throw new TypeError('MiniDaemon - not enough arguments'); }
+  if (oOwner) { this.owner = oOwner; }
+  this.task = fTask;
+  if (isFinite(nRate) && nRate > 0) { this.rate = Math.floor(nRate); }
+  if (nLen > 0) { this.length = Math.floor(nLen); }
+}
+
+MiniDaemon.prototype.owner = null;
+MiniDaemon.prototype.task = null;
+MiniDaemon.prototype.rate = 100;
+MiniDaemon.prototype.length = Infinity;
+
+  /* These properties should be read-only */
+
+MiniDaemon.prototype.SESSION = -1;
+MiniDaemon.prototype.INDEX = 0;
+MiniDaemon.prototype.PAUSED = true;
+MiniDaemon.prototype.BACKW = true;
+
+  /* Global methods */
+
+MiniDaemon.forceCall = function (oDmn) {
+  oDmn.INDEX += oDmn.BACKW ? -1 : 1;
+  if (oDmn.task.call(oDmn.owner, oDmn.INDEX, oDmn.length, oDmn.BACKW) === false || oDmn.isAtEnd()) { oDmn.pause(); return false; }
+  return true;
+};
+
+  /* Instances methods */
+
+MiniDaemon.prototype.isAtEnd = function () {
+  return this.BACKW ? isFinite(this.length) && this.INDEX < 1 : this.INDEX + 1 > this.length;
+};
+
+MiniDaemon.prototype.synchronize = function () {
+  if (this.PAUSED) { return; }
+  clearInterval(this.SESSION);
+  this.SESSION = setInterval(MiniDaemon.forceCall, this.rate, this);
+};
+
+MiniDaemon.prototype.pause = function () {
+  clearInterval(this.SESSION);
+  this.PAUSED = true;
+};
+
+MiniDaemon.prototype.start = function (bReverse) {
+  var bBackw = Boolean(bReverse);
+  if (this.BACKW === bBackw && (this.isAtEnd() || !this.PAUSED)) { return; }
+  this.BACKW = bBackw;
+  this.PAUSED = false;
+  this.synchronize();
+};
+
+ +
MiniDaemon passes arguments to the callback function. If you want to work on it with browsers that natively do not support this feature, use one of the methods proposed above.
+ +

Syntax

+ +

var myDaemon = new MiniDaemon(thisObject, callback[, rate[, length]]);

+ +

Description

+ +

Returns a JavaScript Object containing all information needed by an animation (like the this object, the callback function, the length, the frame-rate).

+ +

Parameters

+ +
+
thisObject
+
The this object on which the callback function is called. It can be an object or null.
+
callback
+
The function that is repeatedly invoked . It is called with three parameters: index (the iterative index of each invocation), length (the number of total invocations assigned to the daemon - finite or Infinity) and backwards (a boolean expressing whether the index is increasing or decreasing). It is something like callback.call(thisObject, index, length, backwards). If the callback function returns a false value the daemon is paused.
+
rate (optional)
+
The time lapse (in number of milliseconds) between each invocation. The default value is 100.
+
length (optional)
+
The total number of invocations. It can be a positive integer or Infinity. The default value is Infinity.
+
+ +

MiniDaemon instances properties

+ +
+
myDaemon.owner
+
The this object on which is executed the daemon (read/write). It can be an object or null.
+
myDaemon.task
+
The function that is repeatedly invoked (read/write). It is called with three arguments: index (the iterative index of each invocation), length (the number of total invocations assigned to the daemon - finite or Infinity) and backwards (a boolean expressing whether the index is decreasing or not) – see above. If the myDaemon.task function returns a false value the daemon is paused.
+
myDaemon.rate
+
The time lapse (in number of milliseconds) between each invocation (read/write).
+
myDaemon.length
+
The total number of invocations. It can be a positive integer or Infinity (read/write).
+
+ +

MiniDaemon instances methods

+ +
+
myDaemon.isAtEnd()
+
Returns a boolean expressing whether the daemon is at the start/end position or not.
+
myDaemon.synchronize()
+
Synchronize the timer of a started daemon with the time of its invocation.
+
myDaemon.pause()
+
Pauses the daemon.
+
myDaemon.start([reverse])
+
Starts the daemon forward (index of each invocation increasing) or backwards (index decreasing).
+
+ +

MiniDaemon global object methods

+ +
+
MiniDaemon.forceCall(minidaemon)
+
Forces a single callback to the minidaemon.task function regardless of the fact that the end has been reached or not. In any case the internal INDEX property is increased/decreased (depending on the actual direction of the process).
+
+ +

Example usage

+ +

Your HTML page:

+ +
<!DOCTYPE html>
+<html>
+<head>
+  <meta charset="UTF-8" />
+  <title>MiniDaemin Example - MDN</title>
+  <script type="text/javascript" src="minidaemon.js"></script>
+  <style type="text/css">
+    #sample_div {
+      visibility: hidden;
+    }
+  </style>
+</head>
+
+<body>
+  <p>
+    <input type="button" onclick="fadeInOut.start(false /* optional */);" value="fade in" />
+    <input type="button" onclick="fadeInOut.start(true);" value="fade out">
+    <input type="button" onclick="fadeInOut.pause();" value="pause" />
+  </p>
+
+  <div id="sample_div">Some text here</div>
+
+  <script type="text/javascript">
+    function opacity (nIndex, nLength, bBackwards) {
+      this.style.opacity = nIndex / nLength;
+      if (bBackwards ? nIndex === 0 : nIndex === 1) {
+        this.style.visibility = bBackwards ? 'hidden' : 'visible';
+      }
+    }
+
+    var fadeInOut = new MiniDaemon(document.getElementById('sample_div'), opacity, 300, 8);
+  </script>
+</body>
+</html>
+ +

View this example in action

+ +

Notes

+ +

The setInterval() function is commonly used to set a delay for functions that are executed again and again, such as animations.

+ +

You can cancel the interval using {{domxref("WindowOrWorkerGlobalScope.clearInterval()")}}.

+ +

If you wish to have your function called once after the specified delay, use {{domxref("WindowOrWorkerGlobalScope.setTimeout()")}}.

+ +

Ensure that execution duration is shorter than interval frequency

+ +

If there is a possibility that your logic could take longer to execute than the interval time, it is recommended that you recursively call a named function using {{domxref("WindowOrWorkerGlobalScope.setTimeout")}}. For example, if using setInterval to poll a remote server every 5 seconds, network latency, an unresponsive server, and a host of other issues could prevent the request from completing in its allotted time. As such, you may find yourself with queued up XHR requests that won't necessarily return in order.

+ +

In these cases, a recursive setTimeout() pattern is preferred:

+ +
(function loop(){
+   setTimeout(function() {
+      // Your logic here
+
+      loop();
+  }, delay);
+})();
+
+ +

In the above snippet, a named function loop() is declared and is immediately executed. loop() is recursively called inside setTimeout() after the logic has completed executing. While this pattern does not guarantee execution on a fixed interval, it does guarantee that the previous interval has completed before recursing.

+ +

Throttling of intervals

+ +

setInterval() is subject to the same throttling restrictions in Firefox as {{domxref("WindowOrWorkerGlobalScope.setTimeout","setTimeout()")}}; see Reasons for delays longer than specified.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'webappapis.html#dom-setinterval', 'WindowOrWorkerGlobalScope.setInterval()')}}{{Spec2("HTML WHATWG")}}Method moved to the WindowOrWorkerGlobalScope mixin in the latest spec.
{{SpecName("HTML WHATWG", "webappapis.html#dom-setinterval", "WindowTimers.setInterval()")}}{{Spec2("HTML WHATWG")}}Initial definition (DOM Level 0)
+ +

Browser compatibility

+ +
+ + +

{{Compat("api.WindowOrWorkerGlobalScope.setInterval")}}

+
+ +

See also

+ + diff --git a/files/pt-br/web/api/windowtimers/cleartimeout/index.html b/files/pt-br/web/api/windowtimers/cleartimeout/index.html new file mode 100644 index 0000000000..f03f43979f --- /dev/null +++ b/files/pt-br/web/api/windowtimers/cleartimeout/index.html @@ -0,0 +1,100 @@ +--- +title: WindowTimers.clearTimeout() +slug: Web/API/WindowTimers/clearTimeout +tags: + - API + - Method + - Window +translation_of: Web/API/WindowOrWorkerGlobalScope/clearTimeout +--- +
+
+
{{APIRef("HTML DOM")}}
+
+
+ +

Sumário

+ +

O método clearTimeout() do escopo {{domxref("WindowOrWorkerGlobalScope")}} cancela um timeout previamente estabelecido pela função {{domxref("WindowOrWorkerGlobalScope.setTimeout", "setTimeout()")}}.

+ +

Síntaxe

+ +
escopo.clearTimeout(timeoutID)
+
+ +

Parâmetros

+ +
+
timeoutID
+
O ID do timeout que você deseja cancelar. Esse ID é o retorno da função setTimeout().
+
+ +

É interessante ressaltar que os conjuntso de IDs usados pelos métodos {{domxref("WindowOrWorkerGlobalScope.setTimeout", "setTimeout()")}} e {{domxref("WindowOrWorkerGlobalScope.setInterval", "setInterval()")}} são compartilhados, o que significa que clearTimeout() e {{domxref("WindowOrWorkerGlobalScope.clearInterval", "clearInterval()")}} podem ser tecnicamente utilizados de forma intercambiável. No entanto, para obter-se maior clareza, isso deve ser evitado.

+ +

Exemplo

+ +

Execute o script abaixo em uma página web e clique na página uma vez. Você verá uma mensagem aparecer um segundo depois. Se você continuar clicando na página várias vezes nesse intervalo de tempo, a mensagem aparecerá uma única vez.

+ +
var alarme = {
+  relembrar: function(aMessage) {
+    alert(aMessage);
+    delete this.timeoutID;
+  },
+
+  setup: function() {
+    if (typeof this.timeoutID === 'number') {
+        this.cancelar();
+    }
+
+    this.timeoutID = window.setTimeout(function(msg) {
+        this.relembrar(msg);
+    }.bind(this), 1000, 'Wake up!');
+  },
+
+  cancelar: function() {
+    window.clearTimeout(this.timeoutID);
+  }
+};
+window.onclick = function() { alarme.setup() };
+ +

Notas

+ +

Passar um ID inválido para clearTimeout não causa nenhum efeito (não lança nenhuma exceção).

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG', 'webappapis.html#dom-cleartimeout', 'WindowOrWorkerGlobalScope.clearTimeout()')}}{{Spec2("HTML WHATWG")}}Método movido para WindowOrWorkerGlobalScope .
{{SpecName('HTML WHATWG', 'webappapis.html#dom-cleartimeout', 'clearTimeout()')}}{{Spec2('HTML WHATWG')}} 
+ +

Compatibilidade

+ + + +

{{Compat("api.WindowOrWorkerGlobalScope.clearTimeout")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/windowtimers/index.html b/files/pt-br/web/api/windowtimers/index.html new file mode 100644 index 0000000000..bd995e8f74 --- /dev/null +++ b/files/pt-br/web/api/windowtimers/index.html @@ -0,0 +1,116 @@ +--- +title: WindowTimers +slug: Web/API/WindowTimers +translation_of: Web/API/WindowOrWorkerGlobalScope +--- +
{{APIRef("HTML DOM")}}
+ +

WindowTimers contains utility methods to set and clear timers.

+ +

There is no object of this type, though the context object, either the {{domxref("Window")}} for regular browsing scope, or the {{domxref("WorkerGlobalScope")}}  for workers, implements it.

+ +

Properties

+ +

This interface do not define any property, nor inherit any.

+ +

Methods

+ +

This interface do not inherit any method.

+ +
+
{{domxref("WindowTimers.clearInterval()")}}
+
Cancels the repeated execution set using {{domxref("WindowTimers.setInterval()")}}.
+
{{domxref("WindowTimers.clearTimeout()")}}
+
Cancels the repeated execution set using {{domxref("WindowTimers.setTimeout()")}}.
+
{{domxref("WindowTimers.setInterval()")}}
+
Schedules the execution of a function each X milliseconds.
+
{{domxref("WindowTimers.setTimeout()")}}
+
Sets a delay for executing a function.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#windowtimers', 'WindowTimers')}}{{Spec2('HTML WHATWG')}}No change since the latest snapshot, {{SpecName("HTML5.1")}}.
{{SpecName('HTML5.1', '#windowtimers', 'WindowTimers')}}{{Spec2('HTML5.1')}}Snapshot of {{SpecName("HTML WHATWG")}}. No change.
{{SpecName("HTML5 W3C", "#windowtimers", "WindowTimers")}}{{Spec2('HTML5 W3C')}}Snapshot of {{SpecName("HTML WHATWG")}}. Creation of WindowBase64 (properties where on the target before it).
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Basic support{{CompatGeckoDesktop(1)}}1.04.04.01.0
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari Mobile
Basic support{{CompatGeckoMobile(1)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

 

+ +

See also

+ + diff --git a/files/pt-br/web/api/worker/index.html b/files/pt-br/web/api/worker/index.html new file mode 100644 index 0000000000..8cf54eccb0 --- /dev/null +++ b/files/pt-br/web/api/worker/index.html @@ -0,0 +1,166 @@ +--- +title: Worker +slug: Web/API/Worker +translation_of: Web/API/Worker +--- +

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

+ +

A interface Worker da API do Web Worker representa uma tarefa em background (segundo plano) que pode ser facilmente criada e emitir mensagens de volta ao seu criador. Criar um worker é possível chamando o construtor Worker("path/to/worker/script") e especificando um script para ser executado em sua própria thread.

+ +

Um worker pode, por sua vez, gerar outros workers, contanto que estes estejam hospedados na mesma origem da página principal (Nota: workers aninhados não estão atualmente implementados no Blink). Além disso, workers podem utilizar XMLHttpRequest para E/S de rede, desde que seja estipulado que os atributos responseXML e channel em XMLHttpRequest retornem sempre null.

+ +

Não são todas as interfaces e funções que estão disponíveis para o script associado a um Worker.

+ +
+

No Firefox, se você deseja utilizar workers em extensões e gostaria de ter acesso a js-ctypes, você deveria utilizar o objeto {{ domxref("ChromeWorker") }} .

+
+ +

Construtores

+ +
+
{{domxref("Worker.Worker", "Worker()")}}
+
Cria um worker dedicado da web que executa o script especificado na URL. Workers também podem ser construídos usando Blobs.
+
+ +

Propriedades

+ +

Herda as propriedades do pai, {{domxref("EventTarget")}}, e implementa as propriedades que compõem o {{domxref("AbstractWorker")}}.

+ +

Manipuladores de Eventos

+ +
+
{{domxref("AbstractWorker.onerror")}}
+
Um {{ domxref("EventListener") }} é chamado sempre quando um {{domxref("ErrorEvent")}} do tipo error é passado através do worker. Este é herdado pelo {{domxref("AbstractWorker")}}.
+
{{domxref("Worker.onmessage")}}
+
Um {{ domxref("EventListener") }} é chamado sempre quando um {{domxref("MessageEvent")}} do tipo message é passado através do worker — ou seja, quando uma mensagem é enviada para o documento pai do worker via {{domxref("DedicatedWorkerGlobalScope.postMessage")}}. A mensagem é armazenada na propriedade de dados do evento {{domxref("MessageEvent.data", "data")}}.
+
+ +

Métodos

+ +

Os métodos são herdados de seu pai. {{domxref("EventTarget")}}, e implementa os métodos de {{domxref("AbstractWorker")}}.

+ +
+
{{domxref("Worker.postMessage()")}}
+
Envia uma mensagem — qual pode consistir de qualquer objeto do JavaScript — para o escopo interno do worker.
+
{{domxref("Worker.terminate()")}}
+
Imediatamente encerra o worker. Isso não oferece ao worker a oportunidade de concluir suas operações; imediatamente o interrompe. ServiceWorker não suportam esse método.
+
+ +

Eventos

+ +
+
message
+
O evento é disparado quando o script pai do worker recebe uma mensagem do mesmo.
+ Também é disponibilizado via onmessage.
+
messageerror
+
Dispara quando um Worker recebe uma mensagem que não pode ser deserializada
+ Também é disponibilizado via onmessageerror.
+
rejectionhandled
+
Dispara sempre que um {{jsxref("Promise")}} é rejeitado, indenpendentemente de haver ou não um manipulador para capturar sua rejeição.
+ Também é disponibilizado via onrejectionhandled.
+
unhandledrejection
+
Dispara sempre que um {{jsxref ("Promise")}} rejeita, independentemente de haver ou não um manipulador para capturar a rejeição. Também disponível por meio da propriedade do manipulador de eventos onunhandledrejection.
+
.
+
+ +

Exemplos

+ +

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('input#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).

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "#worker", "Worker")}}{{Spec2('HTML WHATWG')}}No change from {{SpecName("Web Workers")}}.
{{SpecName('Web Workers', "#worker", "Worker")}}{{Spec2('Web Workers')}}Initial definition.
+ +

Browser compatibility

+ +

Support varies for different types of workers. See each worker type's page for specifics.

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support43.510.010.64
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support4.43.51.0.110.011.55.1{{CompatUnknown}}
+
+ +

See also

+ + diff --git a/files/pt-br/web/api/xmldocument/async/index.html b/files/pt-br/web/api/xmldocument/async/index.html new file mode 100644 index 0000000000..63de77faea --- /dev/null +++ b/files/pt-br/web/api/xmldocument/async/index.html @@ -0,0 +1,37 @@ +--- +title: Document.async +slug: Web/API/XMLDocument/async +translation_of: Web/API/XMLDocument/async +--- +

{{APIRef("DOM")}}{{Deprecated_header}} {{Non-standard_header}}

+ +

document.async pode ser configurado para indicar se uma chamada {{domxref ("document.load")}} deve ser uma solicitação assíncrona ou síncrona. True é o valor padrão, indicando que os documentos devem ser carregados de forma assíncrona.

+ +

 

+ +

(Carregamento de documentos assicronos a partir da versão 1.4 alpha.)

+ +

Exemplo

+ +
function loadXMLData(e) {
+  alert(new XMLSerializer().serializeToString(e.target)); // Retorna o conteúdo de querydata.xml em String
+}
+
+var xmlDoc = document.implementation.createDocument("", "test", null);
+
+xmlDoc.async = false;
+xmlDoc.onload = loadXMLData;
+xmlDoc.load('querydata.xml');
+ +

Especificação

+ + + +

Veja também

+ + diff --git a/files/pt-br/web/api/xmldocument/index.html b/files/pt-br/web/api/xmldocument/index.html new file mode 100644 index 0000000000..ddfbeaaac3 --- /dev/null +++ b/files/pt-br/web/api/xmldocument/index.html @@ -0,0 +1,61 @@ +--- +title: DocumentoXML +slug: Web/API/XMLDocument +tags: + - API + - DOM + - DocumentoXML + - Experimental + - Interface +translation_of: Web/API/XMLDocument +--- +
{{APIRef("DOM")}}{{SeeCompatTable}}
+ +

A interface XMLDocument representa um document XML. Ele herda de {{DOMxRef("Document")}} e não adiciona nenhum método específico ou propriedades para este: no entanto, alguns algoritmos tem comportamento diferente com os dois tipos de documentos.

+ +

Propridades

+ +

Esta interface não tem e nem herda nenhuma propriedade específica.

+ +

Metodos

+ +

Esta interface não adiciona nenhum método novo.

+ +
+
{{DOMxRef("XMLDocument.load()")}} {{Non-standard_Inline}} {{Deprecated_Inline}}
+
Carrega um documento XML
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName("DOM WHATWG", "#xmldocument", "XMLDocument")}}{{Spec2("DOM WHATWG")}}Sem alterações.
{{SpecName("DOM4", "#xmldocument", "XMLDocument")}}{{Spec2("DOM4")}}Definição Inicial.
+ +

Compatibilidade com Navegadores

+ + + +

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

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/xmlhttprequest/abort/index.html b/files/pt-br/web/api/xmlhttprequest/abort/index.html new file mode 100644 index 0000000000..52c1a52068 --- /dev/null +++ b/files/pt-br/web/api/xmlhttprequest/abort/index.html @@ -0,0 +1,118 @@ +--- +title: XMLHttpRequest.abort() +slug: Web/API/XMLHttpRequest/abort +tags: + - AJAX + - API + - HTTP + - HttpRequest + - Referencia + - XMLHttpRequest + - cancelando +translation_of: Web/API/XMLHttpRequest/abort +--- +

{{APIRef('XMLHttpRequest')}}

+ +

O método XMLHttpRequest.abort() aborta a requisição se ela já tiver sido enviada. Quando uma requisição é abortada, o seu readyState é modificado para 0 (Desativado), mas o evento readystatechange não é disparado.

+ +

Sitaxe

+ +
xhrInstance.abort();
+ +

Parâmetros

+ +

Nenhum.

+ +

Retorno

+ +

Nenhum.

+ +

Exemplo

+ +
var xhr = new XMLHttpRequest(),
+    method = "GET",
+    url = "https://developer.mozilla.org/";
+xhr.open(method,url,true);
+
+xhr.send();
+
+xhr.abort();
+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('XMLHttpRequest', '#the-abort()-method')}}{{Spec2('XMLHttpRequest')}}WHATWG living standard
+ +

Compatibilidade entre navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(1)}}{{CompatUnknown}}{{CompatIe('5')}}[1]
+ {{CompatIe('7')}}
{{CompatVersionUnknown}}{{CompatSafari('1.2')}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}1.0{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Esse recurso foi implementado através de ActiveXObject (). O Internet Explorer implementa o padrão XMLHttpRequest desde a versão 7.

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/xmlhttprequest/index.html b/files/pt-br/web/api/xmlhttprequest/index.html new file mode 100644 index 0000000000..de045c5314 --- /dev/null +++ b/files/pt-br/web/api/xmlhttprequest/index.html @@ -0,0 +1,724 @@ +--- +title: XMLHttpRequest +slug: Web/API/XMLHttpRequest +tags: + - AJAX + - Fixit + - HTTP + - MakeBrowserAgnostic + - NeedsCleanup + - NeedsMobileBrowserCompatibility + - NeedsTranslation + - TopicStub + - XMLHttpRequest +translation_of: Web/API/XMLHttpRequest +--- +

{{APIRef("XMLHttpRequest")}}

+ +

XMLHttpRequest é um objeto que fornece funcionalidade ao cliente para transferir dados entre um cliente e um servidor. Ele fornece uma maneira fácil de recuperar dados de um URL sem ter que fazer uma atualização de página inteira. Isso permite que uma página da Web atualize apenas uma parte do conteúdo sem interromper o que o usuário esteja fazendo. XMLHttpRequest é usado constantemente na programação de AJAX.

+ +

XMLHttpRequest foi originalmente projetado pela Microsoft e adotado pela Mozilla, Apple e Google. Está sendo padronizado pela WHATWG. Apesar do nome, XMLHttpRequest pode ser usado para recuperar qualquer tipo de dados, e não apenas XML, suportando também, protocolos diferentes de HTTP (incluindo file e ftp ).

+ +

Para criar uma instância de XMLHttpRequest , basta fazer isso:

+ +
var myRequest = new XMLHttpRequest();
+
+ +

Para obter detalhes sobre como usar XMLHttpRequest , consulte Usando XMLHttpRequest.

+ +

Métodos

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
XMLHttpRequest(JSObject objParameters);
void abort();
DOMString getAllResponseHeaders();
DOMString? getResponseHeader(DOMString header);
void open(DOMString method, DOMString url, optional boolean async, optional DOMString? user, optional DOMString? password);
void overrideMimeType(DOMString mime);
void send();
+ void send(ArrayBuffer data);
+ void send(Blob data);
+ void send(Document data);
+ void send(DOMString? data);
+ void send(FormData data);
void setRequestHeader(DOMString header, DOMString value);
Métodos não-padrão
[noscript] void init(in nsIPrincipal principal, in nsIScriptContext scriptContext, in nsPIDOMWindow ownerWindow);
[noscript] void openRequest(in AUTF8String method, in AUTF8String url, in boolean async, in AString user, in AString password);
void sendAsBinary(in DOMString body);
+ +

Propriedades

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
AtributoTipoDescrição
+

onreadystatechange

+
Function? +

A função de objeto JavaScript que é chamado sempre que o atributo readyState sofre alteração. A função de callback é chamada a partir da thread existente na interface de usuário.

+ +
Aviso: Este não deve ser usado com chamadas síncronas e não deve ser utilizado a partir do código nativo.
+
readyStateretorna o cabeçalho da requisição. +

 

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ValorEstadoDescrição
0UNSENTopen() não foi chamado ainda.
1OPENEDsend() não foi chamado ainda.
2HEADERS_RECEIVEDsend() foi chamado, e cabeçalhos e status estão disponíveis.
3LOADINGDownload; responseText contém dados parciais.
4DONEA operação está concluída.
+
responseArrayBuffer, Document,Blob, DOMString +

Retorna um objeto JavaScript de tipo {{domxref("ArrayBuffer")}}, {{domxref("Blob")}} ou {{domxref("Document")}}, de acordo com  o que estiver contido no responseTypeRetorna null se a request não esteja completa ou não obteve sucesso.

+
responseText {{ReadOnlyInline()}}DOMStringA resposta à request, em formato texto, retorna null se a solicitação não teve êxito ou que ainda não foi enviada.
responseTypeXMLHttpRequestResponseType +

Pode ser configurado para alterar o tipo de resposta.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ValorTipo de dados de resposta de propriedade
"" (string vazia)String (este é o padrão)
"arraybuffer"ArrayBuffer
"blob"{{ domxref("Blob") }}
"document"{{ domxref("Document") }}
"json"Objeto JavaScript, analisado a partir de uma seqüência de caracteres JSON retornado pelo servidor.
"text"String
"moz-blob"Usado pelo Firefox para permitir recuperar dados parciais do tipo {{ domxref("Blob") }},de eventos de progresso. Isso permite que o manipulador de eventos de progresso iniciar o processamento de dados enquanto ele ainda está sendo recebido.
"moz-chunked-text" +

Semelhante ao "text" , mas o streaming ainda está fluindo. Isto significa que o valor na response , só está disponível durante a expedição do "progress" do evento e contém apenas os dados recebidos desde a última "progress" do evento.

+ +

Quando response é acessado durante um evento "progress", este contém uma string com os dados. Caso contrário, retorna null .

+ +

Este modo atualmente só funciona no Firefox.

+
"moz-chunked-arraybuffer" +

Semelhante ao "arraybuffer", mas está fluindo. Isto significa que o valor na response , só está disponível durante a expedição do "progress" do evento e contém apenas os dados recebidos desde a última "progress" do evento.

+ +

Quando response é acessado durante um "progress" evento que contém uma seqüência com os dados. Caso contrário, retorna null .

+ +

Este modo atualmente só funciona no Firefox.

+ +

.

+
+ +
Nota:  Começando com 11,0 Gecko (Firefox 11.0 / 11.0 Thunderbird / SeaMonkey 2.8), bem como WebKit construir 528, esses navegadores não permitem que você use o atributo responseType ao executar solicitações síncronas. Tentativas de fazer isso geram uma exceção do tipo NS_ERROR_DOM_INVALID_ACCESS_ERR. Esta mudança foi proposta para padronização junto à W3C.
+
responseXML {{ReadOnlyInline()}}Document? +

A resposta ao pedido como um DOM Document objeto, ou null se o pedido não foi bem sucedida, ainda não foi enviado, ou não pode ser analisado como XML ou HTML. A resposta é analisado como se fosse um text/html stream. Quando o responseType está definido para "document" e que a solicitação tenha sido feita de forma assíncrona, a resposta é analisado como se fosse um text/html stream.

+ +
Nota: Se o servidor não se aplica o text/xml cabeçalho Content-Type, você pode usar overrideMimeType() para forçar XMLHttpRequest para analisá-lo como XML de qualquer maneira.
+
status {{ReadOnlyInline()}}unsigned shortO status de resposta da requisição. Este é o retorno do codigo da requisição HTTP (por exemplo, status é 200 qual a solicitação for bem-sucedida).
statusText {{ReadOnlyInline()}}DOMStringA cadeia de resposta retornado pelo servidor HTTP. Ao contrário do status , o que inclui todo o texto da mensagem de resposta (" 200 OK ", por exemplo).
timeoutunsigned long +

    
+ O número de milissegundos de um pedido pode tomar antes de ser automaticamente encerrada. Um valor de 0 (que é o padrão) significa que não há tempo limite.

+ +
Nota: Você não pode usar um tempo limite para solicitações síncronas com uma janela proprietária.
+
uploadXMLHttpRequestUploadO processo de upload pode ser rastreado através da ação de retorno de um evento para upload.
withCredentialsboolean +

Indica se ou não de cross-site Access-Control solicitações devem ser feitas usando credenciais, como cookies ou cabeçalhos de autorização. O padrão é false .

+ +
Nota: Esta não afeta as solicitações no mesmo local.
+ +
Nota: Começando com 11,0 Gecko (Firefox 11.0 / 11.0 Thunderbird / SeaMonkey 2.8), Gecko não permite que você use os atributos withCredentials ao realizar solicitações síncronas. Ao tentar fazer isso o sistema gera uma exceção do tipo NS_ERROR_DOM_INVALID_ACCESS_ERR.
+
+ +

Propriedades não-padrão

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
AttributeTypeDescription
channel {{ReadOnlyInline()}}{{Interface("nsIChannel")}}O canal utilizado pelo objecto aquando da execução do pedido. Esta é null se o canal não foi criado ainda. No caso de um pedido de múltiplas partes, isto é o canal inicial, não as diferentes partes do pedido de várias partes. Requer privilégios elevados para o acesso.​​
mozAnon {{ReadOnlyInline()}}boolean +

Se for verdadeiro (true) o pedido será enviado sem cabeçalhos de cookies e autenticação.

+
mozSystem {{ReadOnlyInline()}}boolean +

Se for verdadeiro (true) , a política de mesma origem não será aplicada sobre o pedido.

+
mozBackgroundRequestboolean +

Indica se o objeto representa uma solicitação de serviço de fundo. Se true , nenhum grupo carga está associada com o pedido, e diálogos de segurança estão impedidos de ser mostrado para o usuário. Requer privilégios elevados para o acesso.

+ +

Nos casos em que uma caixa de diálogo de segurança (como a autenticação ou uma notificação certificado ruim) normalmente seriam mostrados, o pedido simplesmente falhar em seu lugar.

+ +
Nota: Esta propriedade deve ser definida antes de chamar open().
+
mozResponseArrayBuffer {{ obsolete_inline("6") }} {{ReadOnlyInline()}}ArrayBufferA resposta ao pedido, como uma matriz de JavaScript digitado. Esta é NULL se o pedido não foi bem-sucedida, ou se não foi enviada ainda.
multipart {{ obsolete_inline("22") }}boolean +

Este Gecko somente recurso foi removido no Firefox / Gecko 22. Por favor Utilize Server-Sent Events, Web Sockets ou responseText de eventos de progresso em seu lugar.

+ +

Indica se ou não a resposta está prevista para ser uma corrente de, possivelmente, vários documentos XML. Se definido como true , o tipo de conteúdo da resposta inicial deve ser multipart/x-mixed-replace ou ocorrerá um erro. Todos os pedidos devem ser assíncrona.

+ +

Isso permite o suporte para servidor push; para cada documento XML que está escrito a este pedido, um novo documento XML DOM é criado eo onload manipulador é chamado entre os documentos.

+ +
Nota: Quando este estiver definido, o onload manipulador e outros manipuladores de eventos não são repostas após a primeira XmlDocument é carregado, eo onload manipulador é chamado após cada parte da resposta é recebida.
+
+ +

Construtor

+ +

XMLHttpRequest()

+ +

O construtor inicia um XMLHttpRequest. Ele deve ser chamado antes de quaisquer outras chamadas de método.

+ +

Gecko/Firefox 16 acrescenta um parâmetro não-padrão para o construtor que pode ativar o modo anônimo (veja Bug 692677). Definir o mozAnon bandeira de true eficácia se assemelha a AnonXMLHttpRequest() construtor descrito na especificação XMLHttpRequest que não tenha sido implementado em qualquer navegador ainda (em setembro de 2012).

+ +
XMLHttpRequest (
+  JSObject objParameters
+);
+ +
Parâmetros (não-padrão)
+ +
+
objParameters
+
Há dois sinalizadores que você pode definir: +
+
mozAnon
+
Boolean: Definir esse sinalizador de true fará com que o navegador para não expor a origem e as credenciais do usuário ao buscar recursos. Mais importante, isto significa que os cookies não será enviado a menos que explicitamente adicionado usando setRequestHeader.
+
mozSystem
+
Boolean: Definir esse sinalizador de true . permite fazer conexões entre sites sem a necessidade de o servidor para opt-in usando CORS requer a configuração mozAnon: true . Ou seja, este não pode ser combinada com o envio de cookies ou outras credenciais do usuário. Isso só funciona em privilegiados (revisto) Apps;ele não funciona em páginas da web arbitrários carregados no Firefox.
+
+
+
+ +

Métodos

+ +

abort()

+ +

Aborta o pedido, se já foi enviada.

+ +

getAllResponseHeaders()

+ +
DOMString getAllResponseHeaders();
+ +

Retorna todos os cabeçalhos de resposta como uma string, ou null se nenhuma resposta foi recebida. Nota: Para os pedidos de várias partes, isso retorna os cabeçalhos da parte atual da solicitação, não a partir do canal original.

+ +

getResponseHeader()

+ +
DOMString? getResponseHeader(DOMString header);
+ +

Retorna a string contendo o texto do cabeçalho especificado, ou null se quer a resposta ainda não foi recebida ou o cabeçalho não existe na resposta.

+ +

open()

+ +

Inicializa um pedido. Este método é para ser usado a partir do código JavaScript; para inicializar um pedido do código nativo, use openRequest() em seu lugar.​

+ +
Nota: Chamar esse método uma solicitação já está ativo (aquele para o qual open() ou openRequest() já foi chamado) é o equivalente de chamar abort().
+ +
void open(
+   DOMString method,
+   DOMString url,
+   optional boolean async,
+   optional DOMString user,
+   optional DOMString password
+);
+
+ +
Parameters
+ +
+
method
+
O método HTTP para usar, como "GET", "POST", "PUT", "DELETE", etc. ignorado para URLs não-HTTP (S).
+
url
+
O URL para o qual enviar a solicitação.
+
async
+
Um parâmetro booleano opcional, por padrão true , indicando se a operação deve ou não ser executada de forma assíncrona. Se esse valor for false , o send() método não retorna até que a resposta seja recebida. Se true , a notificação de uma transação concluída é fornecida usando ouvintes de evento. Isso deve ser true se o multipart atributo for true , ou uma exceção será lançada.
+
user
+
O nome de usuário opcional para usar para fins de autenticação; por padrão, essa é uma seqüência vazia.
+
password
+
A senha opcional para usar para fins de autenticação; por padrão, essa é uma seqüência vazia.
+
+ +

overrideMimeType()

+ +

Substitui o tipo de MIME retornado pelo servidor. Isto pode ser utilizado, por exemplo, para forçar uma corrente a ser tratada e analisada como text/xml, mesmo que o servidor não relatam como método. Este método deve ser chamado antes send() .

+ +
void overrideMimeType(DOMString mimetype);
+ +

send()

+ +

Envia a solicitação. Se o pedido é assíncrono (que é o padrão), este método retorna assim que o pedido for enviado. Se o pedido é síncrono, este método não retorna até a resposta chegar.

+ +
Nota:  Qualquer ouvintes de eventos que pretende definir tem de ser definida antes de chamar send().
+ +
void send();
+void send(ArrayBuffer data);
+void send(Blob data);
+void send(Document data);
+void send(DOMString? data);
+void send(FormData data);
+ +
Notas
+ +

Se os dados são um Document , ele é serializado antes de serem enviados. Ao enviar um documento, as versões do Firefox antes da versão 3 sempre enviavam a solicitação usando codificação UTF-8; Firefox 3 envia corretamente o documento usando a codificação especificada por body.xmlEncoding , ou UTF-8 se nenhum encoding é especificado.

+ +

Se são uma nsIInputStream , deve ser compatível com nsIUploadChannel 's setUploadStream() método. Nesse caso, um cabeçalho Content-Length é adicionado ao pedido, com o seu valor obtido usando nsIInputStream 's available() método. Quaisquer cabeçalhos incluídos na parte superior da corrente são tratados como parte do corpo da mensagem. MIMEType da transmissão deve ser especificado definindo o cabeçalho Content-Type usando o setRequestHeader() método antes de chamar send().

+ +

A melhor maneira de enviar conteúdo binário (como em arquivos de upload) está usandoArrayBuffers ou Blobs  em conjuncton com o send() método. No entanto, se você quiser enviar uma stringifiable dados brutos, use o sendAsBinary() método em vez disso.

+ +

setRequestHeader()

+ +

Define o valor de uma solicitação HTTP header. Você deve chamar setRequestHeader() após open() , mas antes de send().

+ +
void setRequestHeader(
+   DOMString header,
+   DOMString value
+);
+
+ +
Parametros
+ +
+
header
+
O nome do cabeçalho cujo valor deve ser definido.
+
value
+
O valor definido como o corpo do cabeçalho.
+
+ +

Métodos não-padrão

+ +

init()

+ +

Inicializa o objeto para uso a partir do código C ++.

+ +
Nota: Este método não deve ser chamado a partir do JavaScript.
+ +
[noscript] void init(
+   in nsIPrincipal principal,
+   in nsIScriptContext scriptContext,
+   in nsPIDOMWindow ownerWindow
+);
+
+ +
Parametros
+ +
+
principal
+
O principal a ser usado para o pedido; não deve ser null.
+
scriptContext
+
O contexto de script a ser usada para o pedido; não deve ser null.
+
ownerWindow
+
A janela associada com o pedido; pode ser null.
+
+ +

openRequest()

+ +

Inicializa um pedido. Este método é para ser usado a partir do código nativo; para inicializar um pedido do código JavaScript, usar open() em seu lugar. Consulte a documentação do open() .

+ +

sendAsBinary()

+ +

Uma variante do send() método que envia dados binários.

+ +
void sendAsBinary(
+   in DOMString body
+);
+
+ +

Este método, usado em conjuncton com o readAsBinaryString  método do FileReader API tornar possível read and upload any type of file e para  stringify os dados brutos.

+ +
Parametros
+ +
+
body
+
O corpo da solicitação como um DOMString. Estes dados poderão ser convertidos para uma seqüência de caracteres de byte único por truncamento (removendo o byte de mais alta ordem de cada personagem).
+
+ +
sendAsBinary() polyfill
+ +

Desde sendAsBinary() é um recurso experimental, aqui está uma polyfill para navegadores que não suportam o sendAsBinary() método, mas o apoio typed arrays.

+ +
/*\
+|*|
+|*|  :: XMLHttpRequest.prototype.sendAsBinary() Polifyll ::
+|*|
+|*|  https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#sendAsBinary()
+|*|
+\*/
+
+if (!XMLHttpRequest.prototype.sendAsBinary) {
+  XMLHttpRequest.prototype.sendAsBinary = function (sData) {
+    var nBytes = sData.length, ui8Data = new Uint8Array(nBytes);
+    for (var nIdx = 0; nIdx < nBytes; nIdx++) {
+      ui8Data[nIdx] = sData.charCodeAt(nIdx) & 0xff;
+    }
+    /* send as ArrayBufferView...: */
+    this.send(ui8Data);
+    /* ...or as ArrayBuffer (legacy)...: this.send(ui8Data.buffer); */
+  };
+}
+ +
Nota: É possível construir este polyfill colocar dois tipos de dados como argumento para send() : um ArrayBuffer (ui8Data.buffer - o código comentado) ou um ArrayBufferView ( ui8Data , que é uma typed array of 8-bit unsigned integers – descomentada código). No entanto, no Google Chrome, quando você tenta enviar uma ArrayBuffer , a seguinte mensagem de aviso aparecerá: ArrayBuffer is deprecated in XMLHttpRequest.send(). Use ArrayBufferView instead. ArrayBuffer is deprecated in XMLHttpRequest.send(). Use ArrayBufferView instead.
+ +

Notas

+ + + +

Eventos

+ +

onreadystatechange como uma propriedade do XMLHttpRequest instância é suportado em todos os navegadores.

+ +

Desde então, foram implementadas uma série de manipuladores de eventos adicionais em vários navegadores ( onload , onerror , onprogress , etc.). Estes são suportados no Firefox. Em particular, veja {{ interface("nsIXMLHttpRequestEventTarget") }} and Using XMLHttpRequest.

+ +

avegadores mais recentes, incluindo o Firefox, também suporta ouvir as XMLHttpRequest eventos via padrão addEventListener APIs Além de definir on* propriedades para uma função de manipulador.

+ +

Compatibilidade do navegador

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support (XHR1)11.05 (via ActiveXObject)
+ 7 (XMLHttpRequest)
{{ CompatVersionUnknown() }}1.2
send(ArrayBuffer)99{{ compatUnknown() }}11.60{{ compatUnknown() }}
send(Blob)73.6{{ compatUnknown() }}12{{ compatUnknown() }}
send(FormData)64{{ compatUnknown() }}12{{ compatUnknown() }}
sendAsBinary(DOMString){{ compatNo() }} – use the polyfill1.9{{ compatUnknown() }}{{ compatUnknown() }}{{ compatUnknown() }}
response1061011.60{{ compatUnknown() }}
responseType = 'arraybuffer'1061011.60{{ compatUnknown() }}
responseType = 'blob'1961012{{ compatUnknown() }}
responseType = 'document'181110{{ CompatNo() }}{{ CompatNo() }}
responseType = 'json'{{ CompatNo() }}10{{ CompatNo() }}12{{ CompatNo() }}
Progress Events73.51012{{ compatUnknown() }}
withCredentials33.510124
timeout{{ CompatNo() }}12.08{{ compatUnknown() }}{{ CompatNo() }}
responseType = 'moz-blob'{{ CompatNo() }}12.0{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}0.16{{ CompatVersionUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

Notas Gecko

+ +

Gecko 11.0 {{ geckoRelease("11.0") }} removeu o suporte para o uso do responseTypewithCredentials atribui ao realizar solicitações síncronas. Tentativa de fazer isso gera uma NS_ERROR_DOM_INVALID_ACCESS_ERR exception. Esta mudança foi proposta para o W3C para a normalização.

+ +

Gecko 12.0 {{ geckoRelease("12.0") }} e suporte posteriormente usando XMLHttpRequest para ler a partir data: URLs.

+ +

Veja também

+ + + +

{{ languages( { "es": "es/XMLHttpRequest", "fr": "fr/XMLHttpRequest", "it": "it/XMLHttpRequest", "ja": "ja/XMLHttpRequest", "ko": "ko/XMLHttpRequest", "pl": "pl/XMLHttpRequest", "zh-cn": "zh-cn/DOM/XMLHttpRequest" } ) }}

diff --git a/files/pt-br/web/api/xmlhttprequest/onreadystatechange/index.html b/files/pt-br/web/api/xmlhttprequest/onreadystatechange/index.html new file mode 100644 index 0000000000..b67e816ae4 --- /dev/null +++ b/files/pt-br/web/api/xmlhttprequest/onreadystatechange/index.html @@ -0,0 +1,120 @@ +--- +title: XMLHttpRequest.onreadystatechange +slug: Web/API/XMLHttpRequest/onreadystatechange +tags: + - AJAX + - API + - Evento + - Manipulador de eventos + - XHR + - XMLHttpRequest +translation_of: Web/API/XMLHttpRequest/onreadystatechange +--- +
{{APIRef}}
+ +

Um EventHandler é chamado sempre que o atributo readyState é modificado. O callback é chamado a partir da interface do usuário. A propriedade XMLHttpRequest.onreadystatechange contém o manipulador de eventos que é chamado quando o evento readystatechange é disparado, ou seja, toda vez que a propriedade {{domxref("XMLHttpRequest.readyState", "readyState")}} do {{domxref("XMLHttpRequest")}} é modificada.

+ +
+

Atenção: Isso não deve ser usado com solicitações síncronas e não deve ser usado como código nativo.

+
+ +

O evento readystatechange não será chamado quando a XMLHttpRequest request for cancelada pelo método abort().

+ +
+

Atualização: Está disparando na última versão de navegadores (Firefox 51.0.1, Opera 43.0.2442.991, Safari 10.0.3 (12602.4.8), Chrome 54.0.2840.71, Edge, IE11). Exemplo aqui - basta recarregar a página algumas vezes.

+
+ +

Sitaxe

+ +
XMLHttpRequest.onreadystatechange = callback;
+ +

Valores

+ + + +

Exemplo

+ +
var xhr = new XMLHttpRequest(),
+    method = "GET",
+    url = "https://developer.mozilla.org/";
+
+xhr.open(method, url, true);
+xhr.onreadystatechange = function () {
+        if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
+            console.log(xhr.responseText);
+        }
+    };
+xhr.send();
+ +

Especificação

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('XMLHttpRequest', '#handler-xhr-onreadystatechange')}}{{Spec2('XMLHttpRequest')}}WHATWG living standard
+ +

Compatibilidade entre navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(1)}}{{CompatGeckoDesktop(1.0)}}{{CompatIe(7)}}[1]{{CompatVersionUnknown}}{{CompatSafari(1.2)}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}1.0{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Internet Explorer versão 5 e 6 suportam chamadas ajax usando ActiveXObject().

diff --git a/files/pt-br/web/api/xmlhttprequest/open/index.html b/files/pt-br/web/api/xmlhttprequest/open/index.html new file mode 100644 index 0000000000..131d78d21f --- /dev/null +++ b/files/pt-br/web/api/xmlhttprequest/open/index.html @@ -0,0 +1,72 @@ +--- +title: XMLHttpRequest.open() +slug: Web/API/XMLHttpRequest/open +tags: + - Referencia + - metodo +translation_of: Web/API/XMLHttpRequest/open +--- +
{{APIRef('XMLHttpRequest')}}
+ +

O {{domxref("XMLHttpRequest")}} métodoopen() inicializa uma nova requisição, ou reinicializa uma requisição já existente.

+ +
Note: Chamar este método para uma requisição já ativada  (uma que open() já tenha sido chamada) é equivalente a chamar {{domxref("XMLHttpRequest.abort", "abort()")}}.
+ +

Sintaxe

+ +
XMLHttpRequest.open(method, url)
+XMLHttpRequest.open(method, url, async)
+XMLHttpRequest.open(method, url, async, user)
+XMLHttpRequest.open(method, url, async, user, password)
+
+ +

Parâmetros

+ +
+
method
+
O método de requisição HTTP para ser usado, como "GET", "POST", "PUT", "DELETE", etc. Ignorado para URLs não-HTTP(S).
+
url
+
Um {{domxref("DOMString")}} representando a URL para enviar a requisição.
+
async {{optional_inline}}
+
Parâmetro booleano opcional, valor padrão true, indica quando realizar a operação de forma assíncrona. Se este valor for false, o método send() não retorna nada até que a resposta da requisição seja recebida. Se o valor for true, notificação de uma transação concluída é provida usando event listeners. Isso deve ser verdadeiro se o atributo multipart é true, ou uma exceção será lançada. +
Nota: Requisições Síncronas no thread principal podem ser facilmente disruptivas para a experiência de usuário e devem ser evitadas; de fato, muitos navegadores descontinuaram inteiramente o suporte para XHR síncrono no thread principal. Requisições síncronas são permitidas nos {{domxref("Worker")}}s.
+
+
user {{optional_inline}}
+
O nome de usuário opcional para ser usado em autenticação; por padrão, isso é o valor null.
+
password {{optional_inline}}
+
A senha de usuário opcional para ser usado em autenticação; por padrão, isso é o valor null.
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('XMLHttpRequest', '#the-open()-method', 'open()')}}{{Spec2('XMLHttpRequest')}} +

Padrão WHATWG

+
+ +

Compatibilidade de Navegador

+ + + +

{{Compat("api.XMLHttpRequest.open")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/xmlhttprequest/readystate/index.html b/files/pt-br/web/api/xmlhttprequest/readystate/index.html new file mode 100644 index 0000000000..77474ae587 --- /dev/null +++ b/files/pt-br/web/api/xmlhttprequest/readystate/index.html @@ -0,0 +1,154 @@ +--- +title: XMLHttpRequest.readyState +slug: Web/API/XMLHttpRequest/readyState +tags: + - AJAX + - Property + - Reference + - XML + - XMLHttpRequest +translation_of: Web/API/XMLHttpRequest/readyState +--- +

{{APIRef('XMLHttpRequest')}}

+ +

A propriedade XMLHttpRequest.readyState retorna o estado de um XMLHttpRequest. Uma requisição XHR que existe em um dos seguintes estados:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ValorEstadoDescrição
0UNSENTUm cliente foi criado. Mas o método open()  não foi chamado ainda.
1OPENEDO método open() foi chamado.
2HEADERS_RECEIVEDo método send() foi chamado e os cabeçalhos e status estão disponíveis .
3LOADINGBaixando e responseText contem os dados parciais.
4DONEOperação concluída.
+ +
+
UNSENT
+
O XMLHttpRequest foi criado. Mas o método open() não foi chamado ainda.
+
OPENED
+
O método open() foi invocado. Durante esse estado, os headers da requisição podem ser inseridos usando o método setRequestHeader()  e o método send() pode ser chamado, iniciando a busca.
+
HEADERS_RECEIVED
+
O método send() foi chamado e os cabeçalhos de respostas foram recebidos.
+
LOADING
+
A resposta da requisição está sendo recebida. se o responseType for "text" ou  um texto em branco, o responseText terá o texto parcial da resposta conforme seu carregamento.
+
DONE
+
A Operação de busca está completa. Isso pode significar que a trasferência foi concluída com êxito ou que falhou.
+
+ +
+

Os nomes de estado são diferentes no Internet Explorer. Ao invés de UNSENT, OPENED, HEADERS_RECEIVED, LOADING DONE, os nomes usados são: READYSTATE_UNINITIALIZED (0), READYSTATE_LOADING (1), READYSTATE_LOADED (2), READYSTATE_INTERACTIVE (3) e READYSTATE_COMPLETE (4).

+
+ +

Exemplo

+ +
var xhr = new XMLHttpRequest();
+console.log('UNSENT', xhr.readyState); // readyState will be 0
+
+xhr.open('GET', '/api', true);
+console.log('OPENED', xhr.readyState); // readyState will be 1
+
+xhr.onprogress = function () {
+    console.log('LOADING', xhr.readyState); // readyState will be 3
+};
+
+xhr.onload = function () {
+    console.log('DONE', xhr.readyState); // readyState will be 4
+};
+
+xhr.send(null);
+
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusCommentários
{{SpecName('XMLHttpRequest', '#states')}}{{Spec2('XMLHttpRequest')}}WHATWG living standard
+ +

Compatibilidade entre navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
SuporteChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico{{CompatChrome(1)}}{{CompatGeckoDesktop("1.0")}}[1]{{CompatIe(7)}}{{CompatVersionUnknown}}{{CompatSafari("1.2")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
SuporteAndroidChrome para AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatUnknown}}1.0{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
diff --git a/files/pt-br/web/api/xmlhttprequest/requisicoes_sincronas_e_assincronas/index.html b/files/pt-br/web/api/xmlhttprequest/requisicoes_sincronas_e_assincronas/index.html new file mode 100644 index 0000000000..81b8fb8d3e --- /dev/null +++ b/files/pt-br/web/api/xmlhttprequest/requisicoes_sincronas_e_assincronas/index.html @@ -0,0 +1,234 @@ +--- +title: Requisições síncronas e assíncronas +slug: Web/API/XMLHttpRequest/Requisicoes_sincronas_e_assincronas +translation_of: Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests +--- +

XMLHttpRequest suporta comunicações síncronas e assíncronas. No geral, entretando, requisições assíncronas devem prevalecer sobre requisições síncronas por questões de performance.

+ +

Requisições síncronas podem bloquear a execução do codigo, gerando um "congelamento" da tela, prejudicando a experiência do usuário. 

+ +

Requisição assíncrona

+ +

Se você usa XMLHttpRequest de uma extensão, você deveria usá-la de forma assíncrona. Neste caso, você recebe um callback quando os dados forem recebidos, o que permite que o browser continue seu trabalho normalmente enquanto sua requisição estiver sendo processada.

+ +

Exemplo: envie um arquivo para o console de log

+ +

Esse é o exemplo mais simples de uso do XMLHttpRequest assíncrono.

+ +
var xhr = new XMLHttpRequest();
+xhr.open("GET", "/bar/foo.txt", true);
+xhr.onload = function (e) {
+  if (xhr.readyState === 4) {
+    if (xhr.status === 200) {
+      console.log(xhr.responseText);
+    } else {
+      console.error(xhr.statusText);
+    }
+  }
+};
+xhr.onerror = function (e) {
+  console.error(xhr.statusText);
+};
+xhr.send(null); 
+ +

A Linha 2 define o terceiro parâmetro como true, indicando que a requisição deve ser tratada assincronamente.

+ +

A Linha 3 cria um objeto função do tipo event handler e atribui ele ao atributo onload da requisição.

+ +

Na LInha 4, Este handler verifica o estado da requisição, através da variável readyState, para ver se a transação está completa, e se o status do HTTP é 200. Em caso positivo lê o conteúdo recebido. Se um erro ocorrer, uma mensagem de erro será exibida no console.

+ +

A requisição é, de fato, realizada na Linha 15. A rotina de callback é invocada quando o estado da requisição muda.

+ +

Exemplo: Criando uma função standard para ler arquivos externos

+ +

Em alguns casos, você pode precisar ler muitos arquivos externos. Esta é uma função padrão que utiliza o objeto XMLHttpRequest de forma assíncrona para alternar o conteúdo do arquivo legível para um listener especificado.

+ +
function xhrSuccess () { this.callback.apply(this, this.arguments); }
+
+function xhrError () { console.error(this.statusText); }
+
+function loadFile (sURL, fCallback /*, argumentToPass1, argumentToPass2, etc. */) {
+  var oReq = new XMLHttpRequest();
+  oReq.callback = fCallback;
+  oReq.arguments = Array.prototype.slice.call(arguments, 2);
+  oReq.onload = xhrSuccess;
+  oReq.onerror = xhrError;
+  oReq.open("get", sURL, true);
+  oReq.send(null);
+}
+
+ +

Uso:

+ +
function showMessage (sMsg) {
+  alert(sMsg + this.responseText);
+}
+
+loadFile("message.txt", showMessage, "New message!\n\n");
+
+ +

A assinatura da função loadFile declara (i) uma URL de destino que será lida (via HTTP GET), (ii) uma função de callback para executar na conclusão bem-sucedida da instância xhr, e (iii) uma lista opcional de argumentos adicionais que são "passados através" do objeto XHR caso a função de callback seja bem-sucedida.

+ +

A linha 1 declara uma função que será invocada quando a operação XHR for completada com sucesso.  Isso, por sua vez, invoca uma função de callback especificada na invocação da função loadFile (neste caso, a função showMessage) que foi atribuída a propriedade do objeto XHR (Linha 7). Os  argumentos adicionais (caso existam) fornecem a invocação da função loadFile são "aplicados" para a execução da função de callback..

+ +

A linha 3 declara uma função que será invocada quando a operação XHR não for completada com sucesso.

+ +

A linha 7 define no objeto XHR  the success callback function given as the second argument to loadFile.

+ +

Line 8 slices the arguments array given to the invocation of loadFile. Starting with the third argument, all remaining arguments are collected, assigned to the arguments property of the variable oReq, passed to the success callback function xhrSuccess., and ultimately supplied to the callback function (in this case, showMessage) which is invoked by function xhrSuccess.

+ +

Line 9 designates the function xhrSuccess as the callback to be invoked when the onload event fires, that is, when the XHR sucessfully completes.  

+ +

Line 10 designates the function xhrError as the callback to be invoked when the XHR requests fails to complete.

+ +

Line 11 specifies true for its third parameter to indicate that the request should be handled asynchronously.

+ +

Line 12 actually initiates the request.

+ +

Example: using a timeout

+ +

You can use a timeout to prevent hanging your code forever while waiting for a read to occur. This is done by setting the value of the timeout property on the XMLHttpRequest object, as shown in the code below:

+ +
function loadFile(sUrl, timeout, callback){
+
+    var args = arguments.slice(3);
+    var xhr = new XMLHttpRequest();
+    xhr.ontimeout = function () {
+        console.error("The request for " + url + " timed out.");
+    };
+    xhr.onload = function() {
+        if (xhr.readyState === 4) {
+            if (xhr.status === 200) {
+                callback.apply(xhr, args);
+            } else {
+                console.error(xhr.statusText);
+            }
+        }
+    };
+    xhr.open("GET", url, true);
+    xhr.timeout = timeout;
+    xhr.send(null);
+}
+ +

Notice the addition of code to handle the "timeout" event by setting the ontimeout handler.

+ +

Usage:

+ +
function showMessage (sMsg) {
+  alert(sMsg + this.responseText);
+}
+
+loadFile("message.txt", 2000, showMessage, "New message!\n");
+
+ +

Here, we're specifying a timeout of 2000 ms.

+ +
+

Note: Support for timeout was added in {{Gecko("12.0")}}.

+
+ +

Synchronous request

+ +
Note: Starting with Gecko 30.0 {{ geckoRelease("30.0") }}, synchronous requests on the main thread have been deprecated due to the negative effects to the user experience.
+ +

Em casos raros, o uso do método síncrono é preferível ao invés do método assíncrono.

+ +

Example: HTTP synchronous request

+ +

This example demonstrates how to make a simple synchronous request.

+ +
var request = new XMLHttpRequest();
+request.open('GET', '/bar/foo.txt', false);  // `false` makes the request synchronous
+request.send(null);
+
+if (request.status === 200) {
+  console.log(request.responseText);
+}
+
+ +

Line 3 sends the request.  The null parameter indicates that no body content is needed for the GET request.

+ +

Line 5 checks the status code after the transaction is completed.  If the result is 200 -- HTTP's "OK" result -- the document's text content is output to the console.

+ +

Example: Synchronous HTTP request from a Worker

+ +

One of the few cases in which a synchronous request does not usually block execution is the use of XMLHttpRequest within a Worker.

+ +

example.html (the main page):

+ +
<!doctype html>
+<html>
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
+<title>MDN Example</title>
+<script type="text/javascript">
+  var worker = new Worker("myTask.js");
+  worker.onmessage = function(event) {
+    alert("Worker said: " + event.data);
+  };
+
+  worker.postMessage("Hello");
+</script>
+</head>
+<body></body>
+</html>
+
+ +

myFile.txt (the target of the synchronous XMLHttpRequest invocation):

+ +
Hello World!!
+
+ +

myTask.js (the Worker):

+ +
self.onmessage = function (event) {
+  if (event.data === "Hello") {
+    var xhr = new XMLHttpRequest();
+    xhr.open("GET", "myFile.txt", false);  // synchronous request
+    xhr.send(null);
+    self.postMessage(xhr.responseText);
+  }
+};
+
+ +
Note: The effect, because of the use of the Worker, is however asynchronous.
+ +

It could be useful in order to interact in background with the server or to preload some content. See Using web workers for examples and details.

+ +

Adapting Sync XHR usecases to the Beacon API

+ +

There are some cases in which the synchronous usage of XMLHttpRequest was not replaceable, like during the window.onunload and window.onbeforeunload events.  The navigator.sendBeacon API can support these usecases typically while delivering a good UX.

+ +

The following example (from the sendBeacon docs) shows a theoretical analytics code that attempts to submit data to a server by using a synchronous XMLHttpRequest in an unload handler. This results in the unload of the page to be delayed.

+ +
window.addEventListener('unload', logData, false);
+
+function logData() {
+    var client = new XMLHttpRequest();
+    client.open("POST", "/log", false); // third parameter indicates sync xhr. :(
+    client.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
+    client.send(analyticsData);
+}
+
+ +

Using the sendBeacon() method, the data will be transmitted asynchronously to the web server when the User Agent has had an opportunity to do so, without delaying the unload or affecting the performance of the next navigation.

+ +

The following example shows a theoretical analytics code pattern that submits data to a server using the by using the sendBeacon() method.

+ +
window.addEventListener('unload', logData, false);
+
+function logData() {
+    navigator.sendBeacon("/log", analyticsData);
+}
+
+ +

See also

+ + + +

{{ languages( {"zh-cn": "zh-cn/DOM/XMLHttpRequest/Synchronous_and_Asynchronous_Requests" } ) }}

diff --git a/files/pt-br/web/api/xmlhttprequest/send/index.html b/files/pt-br/web/api/xmlhttprequest/send/index.html new file mode 100644 index 0000000000..21fa359025 --- /dev/null +++ b/files/pt-br/web/api/xmlhttprequest/send/index.html @@ -0,0 +1,129 @@ +--- +title: XMLHttpRequest.send() +slug: Web/API/XMLHttpRequest/send +tags: + - AJAX + - API + - Método HTTP + - NeedsExample + - Referencia + - Requisição HTTP + - Requisição XHR + - XHR + - XMLHttpRequest + - send +translation_of: Web/API/XMLHttpRequest/send +--- +

{{APIRef('XMLHttpRequest')}}

+ +

O método send(), do {{domxref("XMLHttpRequest")}}, envia uma requisição para o servidor.Se a solicitação for assíncrona (que é o padrão), esse método retornará assim que a solicitação for enviada e o resultado for entregue usando eventos. Se a solicitação for síncrona, esse método não retornará até que a resposta chegue.

+ +

send() aceita um parâmetro opcional que permite especificar o corpo da solicitação; isso é usado principalmente para solicitações como {{HTTPMethod("PUT")}}. Se o método de solicitação for {{HTTPMethod("GET")}} ou {{HTTPMethod("HEAD")}}, o parâmetro body será ignorado e o corpo da solicitação será definido como null.

+ +

Se nenhum cabeçalho {{HTTPHeader("Accept")}} tiver sido definido usando {{domxref("XMLHttpRequest.setRequestHeader", "setRequestHeader()")}}, um cabeçalho Accept com o tipo "*/*" (qualquer tipo) é enviado.

+ +

Sintaxe

+ +
XMLHttpRequest.send(body)
+
+ +

Parâmetros

+ +
+
body {{optional_inline}}
+
Um corpo de dados a ser enviado na solicitação XHR. Isso pode ser: +
    +
  • Um {{domxref("Document")}}, caso em que é serializado antes de ser enviado.
  • +
  • Um BodyInit, que conforme a espeficicação Fetch, pode ser um objeto {{domxref("Blob")}}, {{domxref("BufferSource")}}, {{domxref("FormData")}}, {{domxref("URLSearchParams")}}, {{domxref("ReadableStream")}} ou {{domxref("USVString")}}.
  • +
+ Se nenhum valor for  espeficicado para o corpo, o valor padrão de null é usado.
+
+ +

A melhor maneira de enviar conteúdo binário (por exemplo, em uploads de arquivos) é usando um {{domxref("ArrayBufferView")}} ou {{domxref("Blob")}} em conjunto com o método send().

+ +

Valor retornado

+ +

undefined.

+ +

Exceções

+ + + + + + + + + + + + + + + + + + +
ExceçãoDescrição
InvalidStateErrorsend() já foi invocado para a requisição, e/ou a requisição está completa.
NetworkErrorO tipo de recurso a ser buscada é um {{domxref("Blob")}} e o método não é GET.
+ +

Exemplo: GET

+ +
var xhr = new XMLHttpRequest();
+xhr.open('GET', '/server', true);
+
+xhr.onload = function () {
+  // Requisição finalizada. Faça o processamento aqui.
+};
+
+xhr.send(null);
+// xhr.send('string');
+// xhr.send(new Blob());
+// xhr.send(new Int8Array());
+// xhr.send(document);
+ +

Exemplo: POST

+ +
var xhr = new XMLHttpRequest();
+xhr.open("POST", '/server', true);
+
+// Envia a informação do cabeçalho junto com a requisição.
+xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
+
+xhr.onreadystatechange = function() { // Chama a função quando o estado mudar.
+    if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
+        // Requisição finalizada. Faça o processamento aqui.
+    }
+}
+xhr.send("foo=bar&lorem=ipsum");
+// xhr.send(new Int8Array());
+// xhr.send(document);
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('XMLHttpRequest', '#the-send()-method', 'send()')}}{{Spec2('XMLHttpRequest')}}WHATWG living standard
+ +

Compatibilidade com os navegadores

+ +
{{Compat("api.XMLHttpRequest.send")}}
+ +

Veja também

+ + diff --git a/files/pt-br/web/api/xmlhttprequest/setrequestheader/index.html b/files/pt-br/web/api/xmlhttprequest/setrequestheader/index.html new file mode 100644 index 0000000000..246692fa09 --- /dev/null +++ b/files/pt-br/web/api/xmlhttprequest/setrequestheader/index.html @@ -0,0 +1,77 @@ +--- +title: XMLHttpRequest.setRequestHeader() +slug: Web/API/XMLHttpRequest/setRequestHeader +tags: + - API + - Cabeçalho HTTP + - HTTP + - XHR + - XMLHttpRequest + - header + - metodo + - setRequestHeader +translation_of: Web/API/XMLHttpRequest/setRequestHeader +--- +
{{APIRef('XMLHttpRequest')}}
+ +
 
+ +

O método setRequestHeader() de {{domxref("XMLHttpRequest")}} define o valor do cabeçalho de uma requisição HTTP. Ao usar setRequestHeader(), você deve chamá-lo depois de chamar o método {{domxref("XMLHttpRequest.open", "open()")}}, mas antes de chamar o método {{domxref("XMLHttpRequest.send", "send()")}}. Se esse método é chamado muitas vezes com o mesmo cabeçalho, os valores são somados em um único cabeçalho de requisição HTTP.

+ +

A cada vez que você chama setRequestHeader() depois de ter chamado-o pelo menos uma vez, o texto especificado é somado ao final do conteúdo do cabeçalho existente.

+ +

Se nenhum cabeçalho {{HTTPHeader("Accept")}} foi definido usando este método, um cabeçalho Accept com o tipo "*/*" é enviado com a requisição quando {{domxref("XMLHttpRequest.send", "send()")}} é chamado.

+ +

Por razões de segurança, alguns cabeçalhos só podem ser controlados pelo agente do usuário. Esses cabeçalhos incluem o cabeçalho {{Glossary("Forbidden_header_name", "forbidden header names", 1)}} e o cabeçalho {{Glossary("Forbidden_response_header_name", "forbidden response header names", 1)}}.

+ +
+

Observação: Para seu campos personalizados, você pode encontrar uma exceção "not allowed by Access-Control-Allow-Headers in preflight response" quando você envia requisições através de domínios. Neste caso, você precisa definir o cabeçalho {{HTTPHeader("Access-Control-Allow-Headers")}} no seu cabeçalho de resposta no lado do servidor.

+
+ +

Sintaxe

+ +
XMLHttpRequest.setRequestHeader(header, value)
+
+ +

Parâmetros

+ +
+
header
+
O nome do cabeçalho cujo valor está para ser definido.
+
value
+
O valor a ser definido como o corpo do cabeçalho.
+
+ +

Valor de retorno

+ +

undefined.

+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('XMLHttpRequest', '#the-setRequestHeader()-method', 'setRequestHeader()')}}{{Spec2('XMLHttpRequest')}}WHATWG living standard
+ +

Compatibilidade com navegadores

+ + + +

{{Compat("api.XMLHttpRequest.setRequestHeader")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/api/xmlhttprequest/timeout/index.html b/files/pt-br/web/api/xmlhttprequest/timeout/index.html new file mode 100644 index 0000000000..d80b67d77d --- /dev/null +++ b/files/pt-br/web/api/xmlhttprequest/timeout/index.html @@ -0,0 +1,51 @@ +--- +title: XMLHttpRequest.timeout +slug: Web/API/XMLHttpRequest/timeout +translation_of: Web/API/XMLHttpRequest/timeout +--- +
{{APIRef('XMLHttpRequest')}}
+ +

A propriedade XMLHttpRequest.timeout é um unsigned long que representa o número de milisegundos que uma requisição deve esperar até ser automaticamente terminada. O valor padrão para essa propriedade é 0, o que significa que o navegador deverá esperar uma resposta indefinidamente. A propriedade Timeout não deveria ser usada para requisições XMLHttpRequests síncronas em um {{Glossary('document environment')}} ou uma exceção do tipo InvalidAccessError será lançada. Quando um timeout ocorre, o evento timeout é disparado. {{gecko_minversion_inline("12.0")}}

+ +
+
+
Nota: Você não pode usar um timeout para requisições síncronas dentro de uma janela.
+
+
Utilizando um timeout com uma requisição assíncrona 
+
+ +

No Internet Explorer, a propriedade timeout pode ser usada apenas depois de o método open() ter sido invocado e antes de se chamar o método send().

+ +

Exemplo

+ +
var xhr = new XMLHttpRequest();
+xhr.open('GET', '/server', true);
+
+xhr.timeout = 2000; // tempo em milisegundos
+
+xhr.onload = function () {
+  // Requisição finalizada. O processamento deve ser colocado aqui.
+};
+
+xhr.ontimeout = function (e) {
+  // Timeout na chamada XMLHttpRequest. Ação de timeout aqui.
+};
+
+xhr.send(null);
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentários
{{SpecName('XMLHttpRequest', '#the-timeout-attribute')}}{{Spec2('XMLHttpRequest')}}WHATWG living standard
diff --git a/files/pt-br/web/api/xmlhttprequest/usando_xmlhttprequest/index.html b/files/pt-br/web/api/xmlhttprequest/usando_xmlhttprequest/index.html new file mode 100644 index 0000000000..b541e64bc1 --- /dev/null +++ b/files/pt-br/web/api/xmlhttprequest/usando_xmlhttprequest/index.html @@ -0,0 +1,688 @@ +--- +title: Usando XMLHttpRequest +slug: Web/API/XMLHttpRequest/Usando_XMLHttpRequest +translation_of: Web/API/XMLHttpRequest/Using_XMLHttpRequest +--- +

XMLHttpRequest torna o envio de requisições HTTP muito fácil.  Basta criar uma instância do objeto, abrir uma url e enviar uma requisição. O status HTTP do resultado assim como o seu conteúdo estarão disponíveis quando a transação for completada. Esta página descreve alguns casos comuns de uso desse poderoso objeto JavaScript.

+ +
function reqListener () {
+  console.log(this.responseText);
+};
+
+var oReq = new XMLHttpRequest();
+oReq.onload = reqListener;
+oReq.open("get", "yourFile.txt", true);
+oReq.send();
+ +

Tipos de Requisições

+ +

Uma requisição feita via XMLHttpRequest pode buscar dados de duas maneiras, sícrona e assíncrona. O tipo de requisição é dado pelo argumento async que é opcional (terceiro argumento) e é definido no método XMLHttpRequest open(). Se esse argumento for true ou não especificado, o XMLHttpRequest será processado de maneira assíncrona, caso contrário o processamento será síncrono. Uma discussão detalhada e demonstrações desses dois tipos podem ser encontradas na página requisições síncronas e assíncronas. No geral a melhor prática é a das solicitações assíncronas.

+ +

Manipulando Respostas

+ +

Existem vários tipos de atributos de resposta definidos pela especificação da W3C para o  XMLHttpRequest.  Eles informam ao cliente que efetuou a requisição XMLHttpRequest informações importantes sobre o status da resposta. Em alguns casos onde se lida com tipos de resposa de não-texto, os tipos de resposta podem envolver alguma manipulação e/ou análise conforme descrito nas seções seguintes.

+ +

Analisando e manipulando a propriedade responseXML

+ +

Se você utiliza o XMLHttpRequest para obter o conteúdo de um documento XML remoto, a propriedade responseXML será um objeto DOM que contém um documento XML, o que pode dificultar a manipulação e análise.

+ +

As cinco formas mais utilizadas para análisar e manipular um arquivo XML são:

+ +
    +
  1. Usando XPath para análisar parte deles.
  2. +
  3. Usando JXON para converter em um Objeto JavaScript.
  4. +
  5. Manualmente Parsing and serializing XML para strings ou objetos.
  6. +
  7. Usando XMLSerializer para serializar árvores do DOM para strings ou para arquivos.
  8. +
  9. RegExp pode ser usado se você souber de antemão qual é o conteúdo do XML. Você pode remover quebras de linhas, usando a RegExp para procurar as quebras de linha. No entanto, este é o "último método", caso o código do XML sofra alterações, o método se torna falho.
  10. +
+ +

Analisando e manipulando uma propriedade responseText contendo um documento HTML

+ +
Nota: A especificação W3C do XMLHttpRequest permite analisar HTML através da propriedade XMLHttpRequest.responseXML . Leia o artigo sobre HTML in XMLHttpRequest para maiores detalhes.
+ +

Se você usa o XMLHttpRequest para recuperar o conteúdo de uma página HTML remota, a propriedade responseText será uma string contendo um a "sopa" de todos as tags HTML, o que pode ser difícil de manipular e analizar. Existem três formas básicas para analizar esta sopa de string HTML:

+ +
    +
  1. Use a propriedade  XMLHttpRequest.responseXML.
  2. +
  3. Introduza o conteúdo dentro do corpo de um document fragment Através de fragment.body.innerHTML e percorra o fragmento do DOM.
  4. +
  5. RegExp pode se usada se você sempre conhece o conteúdo HTML responseText de que tem em mãos. Você pode quere remover quebras de linha, se você usar RegExp para varrer no que diz respeito a quebra de linhas. Contudo, este método é um "último recurso" uma vez que se o código HTML mudar um pouco, o método provavelmente irá falhar.
  6. +
+ +

Manipulação de dados binários

+ +

Apesar de XMLHttpRequest ser mais comumente usado para enviar e receber dados textual, ele pode ser utilizado para enviar e receber conteúdo binário. Existem vários métodos bem testados para forçar a resposta de um XMLHttpRequest para o envio de dados binário. Eles envolvem a utilização do método  .overrideMimeType()  sobre o objeto  XMLHttpRequest e é uma solução viável.

+ +
var oReq = new XMLHttpRequest();
+oReq.open("GET", url, true);
+// recupera dados não processados como uma string binária
+oReq.overrideMimeType("text/plain; charset=x-user-defined");
+/* ... */
+
+ +

A especificação XMLHttpRequest Level 2  adiciona novo responseType attributes que tornam o envio e recebimento de dados muito mais fácil.

+ +
var oReq = new XMLHttpRequest();
+
+oReq.open("GET", url, true);
+oReq.responseType = "arraybuffer";
+oReq.onload = function(e) {
+  var arraybuffer = oReq.response; // não é responseText
+  /* ... */
+}
+oReq.send();
+
+ +

Para mais exemplos confira a página Sending and Receiving Binary Data.

+ +

Monitorando o progresso

+ +

XMLHttpRequest fornece a capacidade de ouvir vários eventos que podem ocorrer enquanto o pedido está sendo processado. Isso inclui notificações periódicas de progresso, notificações de erro e assim por diante.

+ +

Suporte para evento de progresso DOM monitorando a conexão XMLHttpRequest transfers siga a Web API specification for progress events: estes eventos implementam a interface {{domxref("ProgressEvent")}} .

+ +
var oReq = new XMLHttpRequest();
+
+oReq.addEventListener("progress", updateProgress, false);
+oReq.addEventListener("load", transferComplete, false);
+oReq.addEventListener("error", transferFailed, false);
+oReq.addEventListener("abort", transferCanceled, false);
+
+oReq.open();
+
+// ...A transferência foi cancelada pelo usuário
+
+// progresso de transferências do servidor para o cliente (downloads)
+function updateProgress (oEvent) {
+  if (oEvent.lengthComputable) {
+    var percentComplete = oEvent.loaded / oEvent.total;
+    // ...
+  } else {
+    // Não é possível calcular informações de progresso uma vez que a dimensão total é desconhecida
+  }
+}
+
+function transferComplete(evt) {
+  alert("A transferência foi concluída.");
+}
+
+function transferFailed(evt) {
+  alert("Um erro ocorreu durante a transferência do arquivo.");
+}
+
+function transferCanceled(evt) {
+  alert("A transferência foi cancelada pelo usuário.");
+}
+ +

Lines 3-6 adiciona receptores de eventos (event listeners) para os vários que são enviados ao executar uma transferência de dados usando XMLHttpRequest.

+ +
Nota: Você precisa adicionar os receptores de eventos (event listeners) antes de chamar open() sobre a requisição.  Caso contrário, os eventos de prograsso não dispararão..
+ +

O manipulador de evento  de prograsso, especificado pela função updateProgress() neste exemplo, recebe o número total de bytes para transferir, bem como o número de bytes transferidos até o momento em total de eventos e campos  carregados . No entanto, se o campo lengthComputable é false, o comprimento total não é conhecido e será zero..

+ +

Eventos de progresso existem para ambos as transferências de download e upload. The download events are fired on the XMLHttpRequest object itself, as shown in the above sample. The upload events are fired on the XMLHttpRequest.upload object, as shown below:

+ +
var oReq = new XMLHttpRequest();
+
+oReq.upload.addEventListener("progress", updateProgress, false);
+oReq.upload.addEventListener("load", transferComplete, false);
+oReq.upload.addEventListener("error", transferFailed, false);
+oReq.upload.addEventListener("abort", transferCanceled, false);
+
+oReq.open();
+
+ +
Nota: eventos de progresso não estão disponíveis para o arquivo: protocol.
+ +
Nota: Atualmente, existem bugs em aberto para o evento de progresso que continua fetando a versão 25 do Firefox sobre OS X e Linux.
+ +
+

Nota: Iniciando no {{Gecko("9.0")}}, eventos de progresso agora podem ser invocados a entrar para cada pedaço de dados recebidos, incluindo o último bloco, nos casos em que o último pacote é recebido e a conexão fechada antes do evento progresso ser disparado. Neste caso, o evento de progresso é automaticamente acionado quando o evento load ocorre para esse pacote. Isso permite que você agora acompanhe de forma confiável apenas observando o evento de progresso

+
+ +
+

Nota: A partir do {{Gecko("12.0")}}, se o seu evento de progresso e chamado com um responseType de "moz-blob", o valor da resposta será um {{domxref("Blob")}} contendo os dados recebidos até agorar.

+
+ +

POde-se também detectar todas as três condições de fim de carga (abort, load, or error) usando o evento loadend:

+ +
req.addEventListener("loadend", loadEnd, false);
+
+function loadEnd(e) {
+  alert("A transferência terminou (embora não sabemos se ele conseguiu ou não).");
+}
+
+ +

Note que não há nenhuma maneira de ter certeza a partir da informação recebida pelo evento loadend sobre qual condição causou a operação de encerrar; no entanto, você pode usar isso para lidar com tarefas que precisam ser realizadas em todos os cenários de fim-de-transferência.

+ +

Submitting forms and uploading files

+ +

Instances of XMLHttpRequest can be used to submit forms in two ways:

+ + + +

The second way (using the FormData API) is the simplest and the fastest, but has the disadvantage that the data thus collected can not be stringified: they are in every way a blob. It is the best solution for simple cases.
+ The first way (pure AJAX) is instead the most complex, but in compensation is also the most flexible and powerful: it lends itself to wider uses and the data thus collected can be stringified and reused for other purposes such as, for example, populating the status object during a manipulation of the browser history, or other.

+ +

Using nothing but pure AJAX

+ +

Submitting forms without the FormData API does not require other APIs, except that, only if you want to upload one or more files, the FileReader API.

+ +

A brief introduction to the submit methods

+ +

An html {{ HTMLElement("form") }} can be sent in four ways:

+ + + +

Now, consider to submit a form containing only two fields, named foo and baz. If you are using the POST method, the server will receive a string similar to one of the following three ones depending on the encoding type you are using:

+ + + +

Instead, if you are using the GET method, a string like the following will be simply added to the URL:

+ +
?foo=bar&baz=The%20first%20line.%0AThe%20second%20line.
+ +

A little vanilla framework

+ +

All these things are done automatically by the web browser whenever you submit a {{ HTMLElement("form") }}. But if you want to do the same things using JavaScript you have to instruct the interpreter about all things. So, how to send forms in pure AJAX is too complex to be explained in detail here. For this reason we posted here a complete (but still didactic) framework, which is able to use all the four ways of submit and, also, to upload files:

+ +
+
<!doctype html>
+<html>
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
+<title>Sending forms with pure AJAX &ndash; MDN</title>
+<script type="text/javascript">
+
+"use strict";
+
+/*\
+|*|
+|*|  :: XMLHttpRequest.prototype.sendAsBinary() Polifyll ::
+|*|
+|*|  https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#sendAsBinary()
+\*/
+
+if (!XMLHttpRequest.prototype.sendAsBinary) {
+  XMLHttpRequest.prototype.sendAsBinary = function (sData) {
+    var nBytes = sData.length, ui8Data = new Uint8Array(nBytes);
+    for (var nIdx = 0; nIdx < nBytes; nIdx++) {
+      ui8Data[nIdx] = sData.charCodeAt(nIdx) & 0xff;
+    }
+    /* send as ArrayBufferView...: */
+    this.send(ui8Data);
+    /* ...or as ArrayBuffer (legacy)...: this.send(ui8Data.buffer); */
+  };
+}
+
+/*\
+|*|
+|*|  :: AJAX Form Submit Framework ::
+|*|
+|*|  https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest/Using_XMLHttpRequest
+|*|
+|*|  This framework is released under the GNU Public License, version 3 or later.
+|*|  http://www.gnu.org/licenses/gpl-3.0-standalone.html
+|*|
+|*|  Syntax:
+|*|
+|*|   AJAXSubmit(HTMLFormElement);
+\*/
+
+var AJAXSubmit = (function () {
+
+  function ajaxSuccess () {
+    /* console.log("AJAXSubmit - Success!"); */
+    alert(this.responseText);
+    /* you can get the serialized data through the "submittedData" custom property: */
+    /* alert(JSON.stringify(this.submittedData)); */
+  }
+
+  function submitData (oData) {
+    /* the AJAX request... */
+    var oAjaxReq = new XMLHttpRequest();
+    oAjaxReq.submittedData = oData;
+    oAjaxReq.onload = ajaxSuccess;
+    if (oData.technique === 0) {
+      /* method is GET */
+      oAjaxReq.open("get", oData.receiver.replace(/(?:\?.*)?$/, oData.segments.length > 0 ? "?" + oData.segments.join("&") : ""), true);
+      oAjaxReq.send(null);
+    } else {
+      /* method is POST */
+      oAjaxReq.open("post", oData.receiver, true);
+      if (oData.technique === 3) {
+        /* enctype is multipart/form-data */
+        var sBoundary = "---------------------------" + Date.now().toString(16);
+        oAjaxReq.setRequestHeader("Content-Type", "multipart\/form-data; boundary=" + sBoundary);
+        oAjaxReq.sendAsBinary("--" + sBoundary + "\r\n" + oData.segments.join("--" + sBoundary + "\r\n") + "--" + sBoundary + "--\r\n");
+      } else {
+        /* enctype is application/x-www-form-urlencoded or text/plain */
+        oAjaxReq.setRequestHeader("Content-Type", oData.contentType);
+        oAjaxReq.send(oData.segments.join(oData.technique === 2 ? "\r\n" : "&"));
+      }
+    }
+  }
+
+  function processStatus (oData) {
+    if (oData.status > 0) { return; }
+    /* the form is now totally serialized! do something before sending it to the server... */
+    /* doSomething(oData); */
+    /* console.log("AJAXSubmit - The form is now serialized. Submitting..."); */
+    submitData (oData);
+  }
+
+  function pushSegment (oFREvt) {
+    this.owner.segments[this.segmentIdx] += oFREvt.target.result + "\r\n";
+    this.owner.status--;
+    processStatus(this.owner);
+  }
+
+  function plainEscape (sText) {
+    /* how should I treat a text/plain form encoding? what characters are not allowed? this is what I suppose...: */
+    /* "4\3\7 - Einstein said E=mc2" ----> "4\\3\\7\ -\ Einstein\ said\ E\=mc2" */
+    return sText.replace(/[\s\=\\]/g, "\\$&");
+  }
+
+  function SubmitRequest (oTarget) {
+    var nFile, sFieldType, oField, oSegmReq, oFile, bIsPost = oTarget.method.toLowerCase() === "post";
+    /* console.log("AJAXSubmit - Serializing form..."); */
+    this.contentType = bIsPost && oTarget.enctype ? oTarget.enctype : "application\/x-www-form-urlencoded";
+    this.technique = bIsPost ? this.contentType === "multipart\/form-data" ? 3 : this.contentType === "text\/plain" ? 2 : 1 : 0;
+    this.receiver = oTarget.action;
+    this.status = 0;
+    this.segments = [];
+    var fFilter = this.technique === 2 ? plainEscape : escape;
+    for (var nItem = 0; nItem < oTarget.elements.length; nItem++) {
+      oField = oTarget.elements[nItem];
+      if (!oField.hasAttribute("name")) { continue; }
+      sFieldType = oField.nodeName.toUpperCase() === "INPUT" ? oField.getAttribute("type").toUpperCase() : "TEXT";
+      if (sFieldType === "FILE" && oField.files.length > 0) {
+        if (this.technique === 3) {
+          /* enctype is multipart/form-data */
+          for (nFile = 0; nFile < oField.files.length; nFile++) {
+            oFile = oField.files[nFile];
+            oSegmReq = new FileReader();
+            /* (custom properties:) */
+            oSegmReq.segmentIdx = this.segments.length;
+            oSegmReq.owner = this;
+            /* (end of custom properties) */
+            oSegmReq.onload = pushSegment;
+            this.segments.push("Content-Disposition: form-data; name=\"" + oField.name + "\"; filename=\""+ oFile.name + "\"\r\nContent-Type: " + oFile.type + "\r\n\r\n");
+            this.status++;
+            oSegmReq.readAsBinaryString(oFile);
+          }
+        } else {
+          /* enctype is application/x-www-form-urlencoded or text/plain or method is GET: files will not be sent! */
+          for (nFile = 0; nFile < oField.files.length; this.segments.push(fFilter(oField.name) + "=" + fFilter(oField.files[nFile++].name)));
+        }
+      } else if ((sFieldType !== "RADIO" && sFieldType !== "CHECKBOX") || oField.checked) {
+        /* field type is not FILE or is FILE but is empty */
+        this.segments.push(
+          this.technique === 3 ? /* enctype is multipart/form-data */
+            "Content-Disposition: form-data; name=\"" + oField.name + "\"\r\n\r\n" + oField.value + "\r\n"
+          : /* enctype is application/x-www-form-urlencoded or text/plain or method is GET */
+            fFilter(oField.name) + "=" + fFilter(oField.value)
+        );
+      }
+    }
+    processStatus(this);
+  }
+
+  return function (oFormElement) {
+    if (!oFormElement.action) { return; }
+    new SubmitRequest(oFormElement);
+  };
+
+})();
+
+</script>
+</head>
+<body>
+
+<h1>Sending forms with pure AJAX</h1>
+
+<h2>Using the GET method</h2>
+
+<form action="register.php" method="get" onsubmit="AJAXSubmit(this); return false;">
+  <fieldset>
+    <legend>Registration example</legend>
+    <p>
+      First name: <input type="text" name="firstname" /><br />
+      Last name: <input type="text" name="lastname" />
+    </p>
+    <p>
+      <input type="submit" value="Submit" />
+    </p>
+  </fieldset>
+</form>
+
+<h2>Using the POST method</h2>
+<h3>Enctype: application/x-www-form-urlencoded (default)</h3>
+
+<form action="register.php" method="post" onsubmit="AJAXSubmit(this); return false;">
+  <fieldset>
+    <legend>Registration example</legend>
+    <p>
+      First name: <input type="text" name="firstname" /><br />
+      Last name: <input type="text" name="lastname" />
+    </p>
+    <p>
+      <input type="submit" value="Submit" />
+    </p>
+  </fieldset>
+</form>
+
+<h3>Enctype: text/plain</h3>
+
+<form action="register.php" method="post" enctype="text/plain" onsubmit="AJAXSubmit(this); return false;">
+  <fieldset>
+    <legend>Registration example</legend>
+    <p>
+      Your name: <input type="text" name="user" />
+    </p>
+    <p>
+      Your message:<br />
+      <textarea name="message" cols="40" rows="8"></textarea>
+    </p>
+    <p>
+      <input type="submit" value="Submit" />
+    </p>
+  </fieldset>
+</form>
+
+<h3>Enctype: multipart/form-data</h3>
+
+<form action="register.php" method="post" enctype="multipart/form-data" onsubmit="AJAXSubmit(this); return false;">
+  <fieldset>
+    <legend>Upload example</legend>
+    <p>
+      First name: <input type="text" name="firstname" /><br />
+      Last name: <input type="text" name="lastname" /><br />
+      Sex:
+      <input id="sex_male" type="radio" name="sex" value="male" /> <label for="sex_male">Male</label>
+      <input id="sex_female" type="radio" name="sex" value="female" /> <label for="sex_female">Female</label><br />
+      Password: <input type="password" name="secret" /><br />
+      What do you prefer:
+      <select name="image_type">
+        <option>Books</option>
+        <option>Cinema</option>
+        <option>TV</option>
+      </select>
+    </p>
+    <p>
+      Post your photos:
+      <input type="file" multiple name="photos[]">
+    </p>
+    <p>
+      <input id="vehicle_bike" type="checkbox" name="vehicle[]" value="Bike" /> <label for="vehicle_bike">I have a bike</label><br />
+      <input id="vehicle_car" type="checkbox" name="vehicle[]" value="Car" /> <label for="vehicle_car">I have a car</label>
+    </p>
+    <p>
+      Describe yourself:<br />
+      <textarea name="description" cols="50" rows="8"></textarea>
+    </p>
+    <p>
+      <input type="submit" value="Submit" />
+    </p>
+  </fieldset>
+</form>
+
+</body>
+</html>
+
+ +

To test it, please, create a page named register.php (which is the action attribute of these sample forms) and just put the following minimalistic content:

+ +
<?php
+
+  /* register.php */
+
+  header("Content-type: text/plain");
+
+  echo ":: data received via GET ::\n\n";
+  print_r($_GET);
+
+  echo "\n\n:: Data received via POST ::\n\n";
+  print_r($_POST);
+
+  echo "\n\n:: Data received as \"raw\" (text/plain encoding) ::\n\n";
+  if (isset($HTTP_RAW_POST_DATA)) { echo $HTTP_RAW_POST_DATA; }
+
+  echo "\n\n:: Files received ::\n\n";
+  print_r($_FILES);
+
+?>
+ +

The syntax of this script is the following:

+ +
AJAXSubmit(myForm);
+ +
Note: This little vanilla framework uses the FileReader API, which is a recent technique (but only when there are files to upload, the method of the {{ HTMLElement("form") }} is POST and the enctype attribute is setted to multipart/form-data). For this reason, the pure-AJAX upload is to be considered an experimental technique. Instead, if you don't want to upload files, this framework will not use any recent API.
+Note also that the best way to send binary content is using ArrayBuffers or Blobs in conjuncton with the send() method and, possibly, with the readAsArrayBuffer() method of the FileReader API. But, since the aim of this little script is to work with a stringifiable raw data, we used the sendAsBinary() method in conjunction with the readAsBinaryString() method of the FileReader API. So, this is the best solution when working with a relatively few data which must be stringified in order to be reused later. Anyhow, since working with strings instead of typed arrays implies a greater waste of resources, this script makes sense only when you are dealing with small files (like images, documents, mp3, etc.). Otherwise, if you don't want to stringify the submitted or uploaded data, in addition to typed arrays, consider also the use of the FormData API.
+ +

Using FormData objects

+ +

The FormData constructor lets you compile a set of key/value pairs to send using XMLHttpRequest. Its primarily intended for use in sending form data, but can be used independently from forms in order to transmit keyed data. The transmitted data 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". FormData objects can be utilized in a number of ways with an XMLHttpRequest. For examples and explanations of how one can utilize FormData with XMLHttpRequests see the Using FormData Objects page. For didactic purpose only we post here a translation of the previous example transformed so as to make use of the FormData API. Note the brevity of the code:

+ +
+
<!doctype html>
+<html>
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
+<title>Sending forms with FormData &ndash; MDN</title>
+<script type="text/javascript">
+"use strict";
+
+function ajaxSuccess () {
+  alert(this.responseText);
+}
+
+function AJAXSubmit (oFormElement) {
+  if (!oFormElement.action) { return; }
+  var oReq = new XMLHttpRequest();
+  oReq.onload = ajaxSuccess;
+  if (oFormElement.method.toLowerCase() === "post") {
+    oReq.open("post", oFormElement.action, true);
+    oReq.send(new FormData(oFormElement));
+  } else {
+    var oField, sFieldType, nFile, sSearch = "";
+    for (var nItem = 0; nItem < oFormElement.elements.length; nItem++) {
+      oField = oFormElement.elements[nItem];
+      if (!oField.hasAttribute("name")) { continue; }
+      sFieldType = oField.nodeName.toUpperCase() === "INPUT" ? oField.getAttribute("type").toUpperCase() : "TEXT";
+      if (sFieldType === "FILE") {
+        for (nFile = 0; nFile < oField.files.length; sSearch += "&" + escape(oField.name) + "=" + escape(oField.files[nFile++].name));
+      } else if ((sFieldType !== "RADIO" && sFieldType !== "CHECKBOX") || oField.checked) {
+        sSearch += "&" + escape(oField.name) + "=" + escape(oField.value);
+      }
+    }
+    oReq.open("get", oFormElement.action.replace(/(?:\?.*)?$/, sSearch.replace(/^&/, "?")), true);
+    oReq.send(null);
+  }
+}
+</script>
+</head>
+<body>
+
+<h1>Sending forms with FormData</h1>
+
+<h2>Using the GET method</h2>
+
+<form action="register.php" method="get" onsubmit="AJAXSubmit(this); return false;">
+  <fieldset>
+    <legend>Registration example</legend>
+    <p>
+      First name: <input type="text" name="firstname" /><br />
+      Last name: <input type="text" name="lastname" />
+    </p>
+    <p>
+      <input type="submit" value="Submit" />
+    </p>
+  </fieldset>
+</form>
+
+<h2>Using the POST method</h2>
+<h3>Enctype: application/x-www-form-urlencoded (default)</h3>
+
+<form action="register.php" method="post" onsubmit="AJAXSubmit(this); return false;">
+  <fieldset>
+    <legend>Registration example</legend>
+    <p>
+      First name: <input type="text" name="firstname" /><br />
+      Last name: <input type="text" name="lastname" />
+    </p>
+    <p>
+      <input type="submit" value="Submit" />
+    </p>
+  </fieldset>
+</form>
+
+<h3>Enctype: text/plain</h3>
+
+<p>The text/plain encoding is not supported by the FormData API.</p>
+
+<h3>Enctype: multipart/form-data</h3>
+
+<form action="register.php" method="post" enctype="multipart/form-data" onsubmit="AJAXSubmit(this); return false;">
+  <fieldset>
+    <legend>Upload example</legend>
+    <p>
+      First name: <input type="text" name="firstname" /><br />
+      Last name: <input type="text" name="lastname" /><br />
+      Sex:
+      <input id="sex_male" type="radio" name="sex" value="male" /> <label for="sex_male">Male</label>
+      <input id="sex_female" type="radio" name="sex" value="female" /> <label for="sex_female">Female</label><br />
+      Password: <input type="password" name="secret" /><br />
+      What do you prefer:
+      <select name="image_type">
+        <option>Books</option>
+        <option>Cinema</option>
+        <option>TV</option>
+      </select>
+    </p>
+    <p>
+      Post your photos:
+      <input type="file" multiple name="photos[]">
+    </p>
+    <p>
+      <input id="vehicle_bike" type="checkbox" name="vehicle[]" value="Bike" /> <label for="vehicle_bike">I have a bike</label><br />
+      <input id="vehicle_car" type="checkbox" name="vehicle[]" value="Car" /> <label for="vehicle_car">I have a car</label>
+    </p>
+    <p>
+      Describe yourself:<br />
+      <textarea name="description" cols="50" rows="8"></textarea>
+    </p>
+    <p>
+      <input type="submit" value="Submit" />
+    </p>
+  </fieldset>
+</form>
+
+</body>
+</html>
+
+ +
Note: As we said, FormData objects are not stringifiable objects. If you want to stringify a submitted data, use the previous pure-AJAX example. Note also that, although in this example there are some file {{ HTMLElement("input") }} fields, when you submit a form through the FormData API you do not need to use the FileReader API also: files are automatically loaded and uploaded.
+ +

Cross-site XMLHttpRequest

+ +

Modern browsers support cross-site requests by implementing the web applications working group's Access Control for Cross-Site Requests standard.  As long as the server is configured to allow requests from your web application's origin, XMLHttpRequest will work.  Otherwise, an INVALID_ACCESS_ERR exception is thrown.

+ +

Bypassing the cache

+ +

A, cross-browser compatible approach to bypassing the cache is to append a timestamp to the URL, being sure to include a "?" or "&" as appropriate.  For example:

+ +
http://foo.com/bar.html -> http://foo.com/bar.html?12345
+http://foo.com/bar.html?foobar=baz -> http://foo.com/bar.html?foobar=baz&12345
+
+ +

Since the local cache is indexed by URL, this causes every request to be unique, thereby bypassing the cache.

+ +

You can automatically adjust URLs using the following code:

+ +
var oReq = new XMLHttpRequest();
+
+oReq.open("GET", url + ((/\?/).test(url) ? "&" : "?") + (new Date()).getTime(), true);
+oReq.send(null);
+ +

Security

+ +

{{fx_minversion_note(3, "Versions of Firefox prior to Firefox 3 allowed you to set the preference capability.policy..XMLHttpRequest.open to allAccess to give specific sites cross-site access.  This is no longer supported.")}}

+ +

{{fx_minversion_note(5, "Versions of Firefox prior to Firefox 5 could use netscape.security.PrivilegeManager.enablePrivilege(\"UniversalBrowserRead\"); to request cross-site access. This is no longer supported, even though it produces no warning and permission dialog is still presented.")}}

+ +

The recommended way to enable cross-site scripting is to use the Access-Control-Allow-Origin HTTP header in the response to the XMLHttpRequest.

+ +

XMLHttpRequests being stopped

+ +

If you end up with an XMLHttpRequest having status=0 and statusText=null, it means that the request was not allowed to be performed. It was UNSENT. A likely cause for this is when the XMLHttpRequest origin (at the creation of the XMLHttpRequest) has changed when the XMLHttpRequest is then open(). This case can happen for example when one has an XMLHttpRequest that gets fired on an onunload event for a window: the XMLHttpRequest gets in fact created when the window to be closed is still there, and then the request is sent (ie open()) when this window has lost its focus and potentially different window has gained focus. The way to avoid this problem is to set a listener on the new window "activate" event that gets set when the old window has its "unload" event fired.

+ +

Using XMLHttpRequest from JavaScript modules / XPCOM components

+ +

Instantiating XMLHttpRequest from a JavaScript module or an XPCOM component works a little differently; it can't be instantiated using the XMLHttpRequest() constructor. The constructor is not defined inside components and the code results in an error. The best way to work around this is to use the XPCOM component constructor.

+ +
const XMLHttpRequest = Components.Constructor("@mozilla.org/xmlextras/xmlhttprequest;1");
+var oReq = XMLHttpRequest();
+ +

Unfortunately in versions of Gecko prior to Gecko 16 there is a bug which can cause requests created this way to be cancelled for no reason.  If you need your code to work on Gecko 15 or earlier, you can get the XMLHttpRequest constructor from the hidden DOM window like so.

+ +
const { XMLHttpRequest } = Components.classes["@mozilla.org/appshell/appShellService;1"]
+                                     .getService(Components.interfaces.nsIAppShellService)
+                                     .hiddenDOMWindow;
+var oReq = XMLHttpRequest();
+
+ +

See also

+ +
    +
  1. MDC AJAX introduction
  2. +
  3. HTTP access control
  4. +
  5. How to check the security state of an XMLHTTPRequest over SSL
  6. +
  7. XMLHttpRequest - REST and the Rich User Experience
  8. +
  9. Microsoft documentation
  10. +
  11. Apple developers' reference
  12. +
  13. "Using the XMLHttpRequest Object" (jibbering.com)
  14. +
  15. The XMLHttpRequest Object: W3C Specification
  16. +
  17. Web Progress Events specification
  18. +
diff --git a/files/pt-br/web/css/--_star_/index.html b/files/pt-br/web/css/--_star_/index.html new file mode 100644 index 0000000000..19d4078aaf --- /dev/null +++ b/files/pt-br/web/css/--_star_/index.html @@ -0,0 +1,149 @@ +--- +title: Propriedades personalizadas (--*) +slug: Web/CSS/--* +translation_of: Web/CSS/--* +--- +
{{CSSRef}}{{SeeCompatTable}}
+ +

Nomes de propriedades com o prefixo --, como --example-name, representam Propriedade personalizadas que contém um valor que pode ser reutilizado por todo o documento usando a função ({{cssxref("var")}}).

+ +

Propriedades personalizadas participam na cascata: cada uma delas pode aparecer várias vezes e o valor da variável corresponderá ao valor definido na propriedade personalizada, decidido pelo algoritmo de cascata.

+ +

{{cssinfo}}

+ +

Sintaxe

+ +
--somekeyword: left;
+--somecolor: #0000ff;
+--somecomplexvalue: 3px 6px rgb(20, 32, 54);
+
+ +
+
<declaration-value>
+
Este valor corresponde a qualquer sequência de um ou mais tokens, desde que a sequência não contenha tokens não permitidos. Representa a totalidade do que uma declaração válida pode ter como valor.
+
+ +

Sintaxe formal

+ +
{{csssyntax}}
+ +

Exemplo

+ +

HTML

+ +
<p id="firstParagraph">Este parágrafo deve ter um fundo azul e um texto amarelo.</p>
+<p id="secondParagraph">Este parágrafo deve ter um fundo amarelo e um texto azul.</p>
+<div id="container">
+  <p id="thirdParagraph">Este parágrafo deve ter um fundo verde e um texto amarelo.</p>
+</div>
+ +

CSS

+ +
:root {
+  --first-color: #488cff;
+  --second-color: #ffff8c;
+}
+
+#firstParagraph {
+  background-color: var(--first-color);
+  color: var(--second-color);
+}
+
+#secondParagraph {
+  background-color: var(--second-color);
+  color: var(--first-color);
+}
+
+#container {
+  --first-color: #48ff32;
+}
+
+#thirdParagraph {
+  background-color: var(--first-color);
+  color: var(--second-color);
+}
+
+
+ +

Resultado

+ +

{{EmbedLiveSample('Example', 500, 130)}}

+ +

Especificações

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("CSS3 Variables", "#defining-variables", "--*")}}{{Spec2("CSS3 Variables")}}Initial definition
+ +

Compatibilidade entre navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
RecursoChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
suporte básico49.015{{CompatGeckoDesktop("42.0")}}{{CompatNo}}36.09.3[3]
+
+ +
+ + + + + + + + + + + + + + + + + + + +
RecursoAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
suporte básico50.0{{CompatGeckoDesktop("29.0")}}{{CompatNo}}37.09.3[3]
+
+ +

[3] See {{WebKitBug(19660)}}.

+ +

Veja também

+ + diff --git a/files/pt-br/web/css/-moz-binding/index.html b/files/pt-br/web/css/-moz-binding/index.html new file mode 100644 index 0000000000..136ccb9b33 --- /dev/null +++ b/files/pt-br/web/css/-moz-binding/index.html @@ -0,0 +1,57 @@ +--- +title: '-moz-binding' +slug: Web/CSS/-moz-binding +translation_of: Archive/Web/CSS/-moz-binding +--- +
{{CSSRef}}{{Non-standard_Header}}{{Deprecated_Header(57)}}
+ +

A propriedade CSS -moz-binding é usada por aplicações baseadas em Mozilla para fixar um XBL binding a um elemento DOM.

+ +

{{CSSInfo}}

+ +

Sintaxe

+ +
/* valor da <url> */
+-moz-binding: url(http://www.example.org/xbl/htmlBindings.xml#checkbox);
+
+/* Valores globais */
+-moz-binding: inherited;
+-moz-binding: initial;
+-moz-binding: unset;
+
+ +

Valores

+ +
+
{{CSSxRef("<url>")}}
+
A URL para o XBL binding (incluindo o identificador de fragmento).
+
none
+
Nenhum XBL binding é aplicado ao elemento.
+
+ +

Sintaxe formal

+ +
{{CSSSyntax}}
+ +

Exemplo

+ +
.exampleone {
+  -moz-binding: url(http://www.example.org/xbl/htmlBindings.xml#radiobutton);
+}
+ +

Especificações

+ +

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

+ +

Compatibilidade do navegador

+ + + +

{{Compat("css.properties.-moz-binding")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/css/-moz-border-bottom-colors/index.html b/files/pt-br/web/css/-moz-border-bottom-colors/index.html new file mode 100644 index 0000000000..855b7f79ba --- /dev/null +++ b/files/pt-br/web/css/-moz-border-bottom-colors/index.html @@ -0,0 +1,85 @@ +--- +title: '-moz-border-bottom-colors' +slug: Web/CSS/-moz-border-bottom-colors +translation_of: Archive/Web/CSS/-moz-border-bottom-colors +--- +
{{CSSRef}}{{Non-standard_Header}}{{Obsolete_Header(59)}}
+ +

Em aplicações Mozilla como o Firefox, a propriedade CSS -moz-border-bottom-colors define uma lista de cores para a borda inferior.

+ +
/* Valor unico <color>  */
+-moz-border-bottom-colors: #00E676;
+
+/* Multiplos valores <color> */
+-moz-border-bottom-colors: #f0f0f0 #a0a0a0 #505050 #000000;
+
+/* Valores globais */
+-moz-border-bottom-colors: inherit;
+-moz-border-bottom-colors: initial;
+-moz-border-bottom-colors: unset;
+
+ +

Quando um elemento tem a borda maior do que um único pixel do CSS, cada linha de pixel usa a próxima cor especificada em sua propriedade, de fora para dentro. Isso elimina a necessidade de caixas aninhadas. Se a borda for mais larga que o número de cores especificadas, a parte restante da borda é a cor especificada mais próxima.

+ +

{{cssinfo}}

+ +

Não se aplica

+ +
    +
  1. se {{Cssxref("border-style")}} é dashed ou dotted.
  2. +
  3. a tabelas com border-collapse: collapse.
  4. +
+ +

Sintaxe

+ +

Valores

+ +

Aceita uma lista de valores de cores separados por espaços em branco.

+ +
+
<color>
+
Especifica a cor de uma linha de pixels da borda inferior. transparent é válido. Veja os valores de {{cssxref("<color>")}} para possíveis unidades.
+
none
+
Padrão, nenhuma cor é desenhada ou o {{cssxref("border-color")}} é usado, se for especificado.
+
+ +

Sintaxe formal

+ +
{{csssyntax}}
+ +

Exemplo

+ +
<div id="exemplo">Exemplo</div>
+
+ +
#exemplo {
+  padding: 20px;
+  background-color: pink;
+  border: 10px solid black;
+  -moz-border-top-colors: #e00 #c30 #c50 #c60 #c70 #c80 #c90 #ca0 #cb0 #cc0;
+  -moz-border-right-colors: red #f60 #f80 #f90 #fa0 #fb0 #fc0 #fd0 #fe0 #ff0;
+  -moz-border-bottom-colors: red #f60 #f80 #f90 #fa0 #fb0 #fc0 #fd0 #fe0 #ff0;
+  -moz-border-left-colors: #e00 #c30 #c50 #c60 #c70 #c80 #c90 #ca0 #cb0 #cc0;
+}
+
+ +

{{EmbedLiveSample("Exemplo", 120, 90)}}

+ +

Especificações

+ +

Essa propriedade não é parte de nenhuma especificação.

+ +

Compatibilidade de navegador

+ + + +

{{Compat("css.properties.-moz-border-bottom-colors")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/css/-moz-border-left-colors/index.html b/files/pt-br/web/css/-moz-border-left-colors/index.html new file mode 100644 index 0000000000..950f8205a1 --- /dev/null +++ b/files/pt-br/web/css/-moz-border-left-colors/index.html @@ -0,0 +1,85 @@ +--- +title: '-moz-border-left-colors' +slug: Web/CSS/-moz-border-left-colors +translation_of: Archive/Web/CSS/-moz-border-left-colors +--- +
{{CSSRef}}{{Non-standard_Header}}{{Obsolete_Header(59)}}
+ +

Em aplicações Mozilla como o Firefox, a propriedade CSS -moz-border-left-colors define uma lista de cores para a borda esquerda.

+ +
/* Valor unico <color> */
+-moz-border-left-colors: #f0f0f0;
+
+/* Multiplo valor <color> */
+-moz-border-left-colors: #f0f0f0 #a0a0a0 #505050 #000000;
+
+/* Valores globais */
+-moz-border-left-colors: inherit;
+-moz-border-left-colors: initial;
+-moz-border-left-colors: unset;
+
+ +

Quando um elemento tem a borda mais larga que um único pixel CSS, cada linha do pixel usa a próxima cor especificada na sua propriedade, de fora para dentro. Isso elimina a necessidade de caixas aninhadas. Se a borda é mais larga do que o número de cores especificadas, a parte restante da borda é a cor especificada mais próxima.

+ +

{{cssinfo}}

+ +

Não se aplica

+ +
    +
  1. se {{Cssxref("border-style")}} é dashed ou dotted.
  2. +
  3. a tabelas com border-collapse: collapse.
  4. +
+ +

Sintaxe

+ +

Valores

+ +

Aceita uma lista de valores de cores separados por um espaço em branco.

+ +
+
<color>
+
Especifica a cor de uma linha de pixels da borda esquerda. transparent é válido. Veja valores de {{cssxref("<color>")}} para possíveis unidades.
+
none
+
Padrão, nenhuma cor é desenhada ou a {{cssxref("border-color")}} é usada, se especificada.
+
+ +

Sintaxe formal

+ +
{{csssyntax}}
+ +

Exemplo

+ +
<div id="exemplo">Exemplo</div>
+
+ +
#exemplo {
+  padding: 15px;
+  background-color: #4DD0E1;
+  border: 5px solid black;
+  -moz-border-top-colors: #e00 #c30 #c50 #c60 #c70 #c80 #c90 #ca0 #cb0 #cc0;
+  -moz-border-right-colors: red #f60 #f80 #f90 #fa0 #fb0 #fc0 #fd0 #fe0 #ff0;
+  -moz-border-bottom-colors: red #f60 #f80 #f90 #fa0 #fb0 #fc0 #fd0 #fe0 #ff0;
+  -moz-border-left-colors: #e00 #c30 #c50 #c60 #c70 #c80 #c90 #ca0 #cb0 #cc0;
+}
+
+ +

{{EmbedLiveSample("Exemplo", 120, 90)}}

+ +

Especificações

+ +

Essa propriedade não é parte de nenhuma especificação.

+ +

Browser compatibility

+ + + +

{{Compat("css.properties.-moz-border-left-colors")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/css/-moz-border-right-colors/index.html b/files/pt-br/web/css/-moz-border-right-colors/index.html new file mode 100644 index 0000000000..905a2f4576 --- /dev/null +++ b/files/pt-br/web/css/-moz-border-right-colors/index.html @@ -0,0 +1,85 @@ +--- +title: '-moz-border-right-colors' +slug: Web/CSS/-moz-border-right-colors +translation_of: Archive/Web/CSS/-moz-border-right-colors +--- +
{{CSSRef}}{{Non-standard_Header}}{{Obsolete_Header(59)}}
+ +

Em aplicações Mozilla como o Firefox, a propriedade CSS -moz-border-right-colors define uma lista de cores para a borda direita.

+ +
/* Valor unico <color> */
+-moz-border-right-colors: #f0f0f0;
+
+/* Multiplos valores <color> */
+-moz-border-right-colors: #f0f0f0 #a0a0a0 #505050 #000000;
+
+/* Valores globais */
+-moz-border-right-colors: inherit;
+-moz-border-right-colors: initial;
+-moz-border-right-colors: unset;
+
+ +

Quando um elemento tem a borda mais larga que um único pixel CSS, cada linha do pixel usa a próxima cor especificada em sua propriedade, de fora para dentro. Isso elimina a necessidade de caixas aninhadas. Se a borda é mais larga que o número espeficado de cores, a parte restante da borda é a cor especificada mais próxima.

+ +

{{cssinfo}}

+ +

Não se aplica

+ +
    +
  1. se {{Cssxref("border-style")}} é dashed ou dotted.
  2. +
  3. a tabelas com border-collapse: collapse.
  4. +
+ +

Sintaxe

+ +

Valores

+ +

Aceita uma lista de valores de cores separados por espaços em branco.

+ +
+
<color>
+
Especifica a cor de uma linha de pixel da borda direita. transparent é válido. Veja os valores de {{cssxref("<color>")}} para possíveis unidades.
+
none
+
Padrão, nenhuma cor é desenhada ou {{cssxref("border-color")}} é usada, se especificada.
+
+ +

Sintaxe formal

+ +
{{csssyntax}}
+ +

Exemplo

+ +
<div id="exemplo">Exemplo</div>
+
+ +
#exemplo {
+  padding: 20px;
+  background-color: gray;
+  border: 10px solid black;
+  -moz-border-top-colors: #e00 #c30 #c50 #c60 #c70 #c80 #c90 #ca0 #cb0 #cc0;
+  -moz-border-right-colors: red #f60 #f80 #f90 #fa0 #fb0 #fc0 #fd0 #fe0 #ff0;
+  -moz-border-bottom-colors: red #f60 #f80 #f90 #fa0 #fb0 #fc0 #fd0 #fe0 #ff0;
+  -moz-border-left-colors: #e00 #c30 #c50 #c60 #c70 #c80 #c90 #ca0 #cb0 #cc0;
+}
+
+ +

{{EmbedLiveSample("Exemplo", 120, 90)}}

+ +

Especificações

+ +

Essa propriedade não é parte de nenhuma especificação.

+ +

Compatibilidade do navegador

+ + + +

{{Compat("css.properties.-moz-border-right-colors")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/css/-moz-border-top-colors/index.html b/files/pt-br/web/css/-moz-border-top-colors/index.html new file mode 100644 index 0000000000..0e9aac64a2 --- /dev/null +++ b/files/pt-br/web/css/-moz-border-top-colors/index.html @@ -0,0 +1,85 @@ +--- +title: '-moz-border-top-colors' +slug: Web/CSS/-moz-border-top-colors +translation_of: Archive/Web/CSS/-moz-border-top-colors +--- +
{{CSSRef}}{{Non-standard_Header}}{{Obsolete_Header(59)}}
+ +

In Mozilla applications like Firefox, the -moz-border-top-colors CSS property sets a list of colors for the top border.

+ +
/* Single <color> value */
+-moz-border-top-colors: #f0f0f0;
+
+/* Multiple <color> values */
+-moz-border-top-colors: #f0f0f0 #a0a0a0 #505050 #000000;
+
+/* Global values */
+-moz-border-top-colors: inherit;
+-moz-border-top-colors: initial;
+-moz-border-top-colors: unset;
+
+ +

Quando um elemento tem a borda mais larga que um único pixel CSS, cada linha do pixel usa a próxima cor especificada em sua propriedade, de fora para dentro. Isso elimina a necessidade de caixas aninhadas. Se a borda é mais larga que o número espeficado de cores, a parte restante da borda é a cor especificada mais próxima.

+ +

{{cssinfo}}

+ +

It does not apply

+ +
    +
  1. se {{Cssxref("border-style")}} é dashed ou dotted.
  2. +
  3. a tabela com border-collapse: collapse.
  4. +
+ +

Sintaxe

+ +

Valores

+ +

Aceita uma lista de valores de cores separados por espaços em branco.

+ +
+
<color>
+
Especifica a cor de uma linha de pixel da borda superior. transparent é válido. Veja os valores de {{cssxref("<color>")}} para possíveis unidades.
+
none
+
Padrão, nenhuma cor é desenhada ou {{cssxref("border-color")}} é usada, se especificada .
+
+ +

Sintaxe formal

+ +
{{csssyntax}}
+ +

Exemplo

+ +
<div id="exemplo">Exemplo</div>
+
+ +
#exemplo {
+  padding: 20px;
+  background-color: gray;
+  border: 10px solid black;
+  -moz-border-top-colors: #e00 #c30 #c50 #c60 #c70 #c80 #c90 #ca0 #cb0 #cc0;
+  -moz-border-right-colors: red #f60 #f80 #f90 #fa0 #fb0 #fc0 #fd0 #fe0 #ff0;
+  -moz-border-bottom-colors: red #f60 #f80 #f90 #fa0 #fb0 #fc0 #fd0 #fe0 #ff0;
+  -moz-border-left-colors: #e00 #c30 #c50 #c60 #c70 #c80 #c90 #ca0 #cb0 #cc0;
+}
+
+ +

{{EmbedLiveSample("Exemplo", 120, 90)}}

+ +

Especificações

+ +

Essa propriedade não é parte de nenhuma especificação.

+ +

Compatibilidade do navegador

+ + + +

{{Compat("css.properties.-moz-border-top-colors")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/css/-moz-box-ordinal-group/index.html b/files/pt-br/web/css/-moz-box-ordinal-group/index.html new file mode 100644 index 0000000000..6895245bfa --- /dev/null +++ b/files/pt-br/web/css/-moz-box-ordinal-group/index.html @@ -0,0 +1,59 @@ +--- +title: '-moz-box-ordinal-group' +slug: Web/CSS/-moz-box-ordinal-group +translation_of: Web/CSS/box-ordinal-group +--- +

{{CSSRef}}{{Warning("Essa propriedade é parte do projeto do módulo original do CSS Flexible Box Layout, e foi substituído em projetos recentes.")}}

+ +

Veja Flexbox para mais informações do que você deveria usar ao invés dessa propriedade.

+ +

Sumário

+ +

Indica o grupo ordinal ao qual o elemento percente. Elementos com um grupo ordinal menor são mostrados antes daqueles com grupo ordinal maior.

+ +

Valores

+ +

Os valores devem ser inteiros maiores que zero. O valor padrão para essa propriedade é 1.

+ +

Exemplos

+ +
<style type="text/css">
+  #Flexbox {
+    display: -ms-box;
+    display: -moz-box;
+    display: -webkit-box;
+  }
+
+  #text1 {
+    background: red;
+    -ms-box-ordinal-group: 4;
+    -moz-box-ordinal-group: 4;
+    -webkit-box-ordinal-group: 4;
+  }
+
+  #text2 {
+    background: green;
+    -ms-box-ordinal-group: 3;
+    -moz-box-ordinal-group: 3;
+    -webkit-box-ordinal-group: 3;
+  }
+
+  #text3 {
+    background: blue;
+    -ms-box-ordinal-group: 2;
+    -moz-box-ordinal-group: 2;
+    -webkit-box-ordinal-group: 2;
+  }
+
+  #text4 {
+    background: orange;
+  }
+</style>
+
+<div id="Flexbox">
+  <div id="text1">text 1</div>
+  <div id="text2">text 2</div>
+  <div id="text3">text 3</div>
+  <div id="text4">text 4</div>
+</div>
+
diff --git a/files/pt-br/web/css/-moz-cell/index.html b/files/pt-br/web/css/-moz-cell/index.html new file mode 100644 index 0000000000..89fe31fd66 --- /dev/null +++ b/files/pt-br/web/css/-moz-cell/index.html @@ -0,0 +1,8 @@ +--- +title: '-moz-cell' +slug: Web/CSS/-moz-cell +translation_of: Web/CSS/cursor +--- +
{{CSSRef}} {{deprecated_header}}
+ +

Não use esse valor! Use o valor cursor {{cssxref("cursor#cell","cell")}} em seu lugar.

diff --git a/files/pt-br/web/css/-moz-context-properties/index.html b/files/pt-br/web/css/-moz-context-properties/index.html new file mode 100644 index 0000000000..21f99210e6 --- /dev/null +++ b/files/pt-br/web/css/-moz-context-properties/index.html @@ -0,0 +1,79 @@ +--- +title: '-moz-context-properties' +slug: Web/CSS/-moz-context-properties +translation_of: Web/CSS/-moz-context-properties +--- +
{{CSSRef}}{{Non-standard_header}} +
+

Nota: Essa característica está disponível desde o Fireforx 55, mas só é suportada atualmente com imagens SVG carregadas via URLs chrome:// ou resource://. Para experimentar o recurso em SVG na web é necessário definir svg.context-properties.content.enabled para true.

+
+
+ +

Se você referenciar uma imagem SVG em uma página web (como com o elemento {{htmlelement("img")}} ou como imagem de fundo), a imagem SVG pode coordenar com o elemento de incorporação (seu contexto) para que a imagem adote os valores da propriedade definidos no elemento de incorporação. Para fazer isso o elemento de incorporação pecisa listar as propriedades que precisarão ficar disponíveis para a imagem listando-os como valores da propriedade de -moz-context-properties, e a imagem precisa optar em usar essas propriedades usando valores como o context-fill.

+ +

{{cssinfo}}

+ +

Sintaxe

+ +
/* Valores-chave */
+-moz-context-properties: fill;
+-moz-context-properties: fill, stroke;
+
+/* Valores globais */
+-moz-context-properties: inherit;
+-moz-context-properties: initial;
+-moz-context-properties: unset;
+
+ +

Valores

+ +
+
fill
+
Expõe o valor fill definido na imagem para o SVG incorporado.
+
stroke
+
Expõe o valor stroke definido na imagem para o SVG incorporado.
+
fill-opacity
+
Expõe o valor fill-opacity definido na imagem para o SVG incorporado.
+
stroke-opacity
+
Expõe o valor stoke-opacity definido na imagem para o SVG incorporado.
+
+ +

Sintaxe formal

+ +
{{csssyntax}}
+ +

Exemplo

+ +

Nesse exemplo temos um simples SVG incorporado usando o elemento <img>.

+ +

Você precisa primeiro especificar no elemento de incorporação as propriedades cujos valores deseja expor ao SVG incorporado, usando a propriedade -moz-context-properties. Por exemplo:

+ +
.img1 {
+  width: 100px;
+  height: 100px;
+  -moz-context-properties: fill, stroke;
+  fill: lime;
+  stroke: purple;
+}
+ +

Agora que você o fez, a imagem SVG pode usar os valores das propriedades {{cssxref("fill")}} e {{cssxref("stroke")}}, por exemplo:

+ +
<img class="img1" src="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg'>
+                       <rect width='100%' height='100%' stroke-width='30px'
+                       fill='context-fill red' stroke='context-stroke' fill-opacity='0.5'/></svg>">
+ +

Aqui nós definimos a imagem src para uma URI de dado contendo uma simples imagem SVG; o <rect> foi feito para receber os valores de fill e stroke de {{cssxref("fill")}} e {{cssxref("stroke")}} definidos no elemento <img> dando a eles a palavras-chave context-fill/context-stroke em seus valores, juntamente com a cor de fallback para o preenchimento (vermelho) que será usada caso o SVG seja carregado sozinho em uma janela top-level (onde não terá elemento de contexto para prover valores de contexto). Note que se uma cor é definida diretamente no SVG, e a cor de contexto é também especificada, a cor de contexto sobrescreve a cor direta.

+ +
+

Note: Você pode encontrar um exemplo funcinal no Github.

+
+ +

Especificações

+ +

Essa propriedade não está definida em nenhum padrão CSS.

+ +

Compatibilidade de navegador

+ + + +

{{Compat("css.properties.-moz-context-properties")}}

diff --git a/files/pt-br/web/css/-webkit-overflow-scrolling/index.html b/files/pt-br/web/css/-webkit-overflow-scrolling/index.html new file mode 100644 index 0000000000..72f2aac139 --- /dev/null +++ b/files/pt-br/web/css/-webkit-overflow-scrolling/index.html @@ -0,0 +1,105 @@ +--- +title: '-webkit-overflow-scrolling' +slug: Web/CSS/-webkit-overflow-scrolling +tags: + - CSS + - CSS Property + - CSS Reference + - NeedsBrowserCompatibility + - NeedsLiveSample + - NeedsMobileBrowserCompatibility + - Non-standard + - Não-padrão + - Propriedade CSS + - Reference + - Referência CSS(3) +translation_of: Web/CSS/-webkit-overflow-scrolling +--- +
{{CSSRef}}{{Non-standard_header}}
+ +

Resumo

+ +

A propriedade CSS -webkit-overflow-scrolling controla quando dispositivos com a funcionalidade de toque na tela usam uma rolagem baseada no "momentum" de um dado elemento.

+ +

{{cssinfo}}

+ +

Valores

+ +
+
auto
+
Usa a rolagem "regular", onde o conteúdo imediatamente cessa a rolagem quando você remove o dedo da tela que reconhece os toques.
+
touch
+
Usa a rolagem baseada em "momentos", onde o conteúdo continua a rolar por um momento depois do gesto de rolagem ter sido finalizado quando o usuário deixar de tocar com o dedo na tela. A velocidade e duração da rolagem contínua é proporcional ao quão vigoroso a rolagem. Também cria um novo contexto estagnado.
+
+ +

Sintaxe formal

+ +
{{csssyntax}}
+ +

Exemplos

+ +
-webkit-overflow-scrolling: touch; /* deixa a rolagem suave */
+
+-webkit-overflow-scrolling: auto; /* pare de rolar imediatamente */
+ +

Especificações

+ +

Não faz parte de nenhuma especificação. A Apple tem uma descrição na referência de CSS do Safari.

+ +

 

+ +

Compatibilidade do navegador

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
RecursoChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte Básico{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
RecursoAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Suporte Básico{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}5.0
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/css/-webkit-text-security/index.html b/files/pt-br/web/css/-webkit-text-security/index.html new file mode 100644 index 0000000000..81ceff0405 --- /dev/null +++ b/files/pt-br/web/css/-webkit-text-security/index.html @@ -0,0 +1,49 @@ +--- +title: '-webkit-text-security' +slug: Web/CSS/-webkit-text-security +translation_of: Web/CSS/-webkit-text-security +--- +
{{ CSSRef() }} {{ Non-standard_header() }}
+ +

-webkit-text-security é uma propriedade CSS não padronizada que ofusca caracteres em um campo {{HtmlElement ("form")}} (como {{HtmlElement ("input")}}} ou {{HtmlElement ("textarea")}}) substituindo eles com uma forma. Afeta apenas campos que não são type=password.

+ +

Sintaxe

+ +
-webkit-text-security: circle;
+-webkit-text-security: disc;
+-webkit-text-security: square;
+-webkit-text-security: none;
+
+ +

Exemplo

+ +

Tente digitar no campo abaixo. Se o seu navegador suportar essa propriedade, os caracteres deverão ser visualmente substituídos por quadrados.

+ +

HTML

+ +
<label for="name">Name:</label>
+<input type="text" name="name" id="name" />
+ +

CSS

+ +
input {
+  -webkit-text-security: square;
+}
+ +

Result

+ +

{{EmbedLiveSample("Example")}}

+ +

Especificação

+ +

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

+ +

Compatibilidade do navegador

+ +

Suportado em navegadores baseados no WebKit e Blink.

+ +

Veja também

+ + diff --git a/files/pt-br/web/css/@charset/index.html b/files/pt-br/web/css/@charset/index.html new file mode 100644 index 0000000000..21ea7edbbd --- /dev/null +++ b/files/pt-br/web/css/@charset/index.html @@ -0,0 +1,114 @@ +--- +title: '@charset' +slug: Web/CSS/@charset +translation_of: Web/CSS/@charset +--- +
{{cssxref("<string>")}}{{ CSSRef() }}
+ +

Resumo

+ +

A regra @charset especifica a codificação de caracteres utilizada na folha de estilo. Deve ser o primeiro elemento na folha de estilo e não ser precedida de qualquer caráter; uma vez que não é uma declaração aninhada, ele não pode ser usado dentro de um grupo condicional de regras. Se vários @charset são definidos, apenas o primeiro é usado, e não pode ser usado dentro de um atributo de estilo em um elemento HTML ou dentro do elemento {{ HTMLElement("style") }}, onde o conjunto de caracteres da página HTML é relevante.

+ +

Esta regra at (at-rule) é útil quando se usa caracteres não ASCII em algumas propriedades CSS, como conteúdo.

+ +

Como existem várias maneiras de definir a codificação de caracteres em uma folha de estilo, o navegador vai tentar os seguintes métodos na seguinte ordem (e parar assim que um produzir um resultado):

+ +
    +
  1. O valor do carácter de ordem de byte Unicode colocado no início do arquivo.
  2. +
  3. O valor dado pelo atributo charset do Content-Type: cabeçalho HTTP ou o equivalente no protocolo usado para servir a folha de estilo.
  4. +
  5. O @charset CSS.
  6. +
  7. Use a codificação de caracteres definidos pelo documento referente: o atributo charset do elemento {{ HTMLElement("link") }}. Este método é obsoleto em HTML5 e não deve ser utilizado.
  8. +
  9. Assume que o documento é UTF-8.
  10. +
+ +

Sintaxe

+ +
  @charset charset;
+
+ +

onde :

+ +
+
charset
+
É uma {{cssxref("<string>")}} denotando a codificação de caracteres a ser usado. Ele deve ser o nome de uma codificação de caracteres segura para a Web definido no registro IANA. Se vários nomes estão associados com uma codificação, apenas um é marcado como preferido e assim ser utilizado.
+
+ +

Exemplos

+ +
@charset "UTF-8";       /* Define a codificação da folha de estilo para Unicode UTF-8 */
+@charset 'iso-8859-15'; /* Define a codificação da folha de estilo para Latin-9 (línguas da Europa Ocidental, com sinal de euro) */
+ @charset "UTF-8";      /* Inválido, há um caracter (espaço) antes da regra */
+@charset UTF-8;         /*  Inválido, sem ‘ ou ", o conjunto de caracteres não é uma {{cssxref("<string>")}} CSS */
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{ SpecName('CSS2.1', 'syndata.html#x57', '@charset') }}{{ Spec2('CSS2.1') }} 
+ +

Compatibilidade de navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico2.0{{ CompatGeckoDesktop("1.8") }}[*]5.5 [**]94
+
+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico2.1{{ CompatGeckoMobile("1.8") }}5.5 [**]10.04
+
+ +

[*] Firefox 1.0 suportado apenas uma sintaxe inválida onde a codificação de caracteres não está definido entre aspas simples ou duplas.
+ [**] A partir IE 5.5 para o IE 7 incluído, IE também apoiou a sintaxe inválida onde a codificação de caracteres não está definido entre aspas simples ou duplas.

diff --git a/files/pt-br/web/css/@font-face/index.html b/files/pt-br/web/css/@font-face/index.html new file mode 100644 index 0000000000..9f60002ff0 --- /dev/null +++ b/files/pt-br/web/css/@font-face/index.html @@ -0,0 +1,189 @@ +--- +title: '@font-face' +slug: Web/CSS/@font-face +translation_of: Web/CSS/@font-face +--- +
{{CSSRef}}
+ +

O @font-face CSS at-rule especifica uma fonte customizada com a qual exibe o texto; a fonte pode ser carregada de um servidor remoto ou de uma fonte instalada localmente no computador do usuário. Se a função local() for fornecida, a especificação do nome da fonte a ser procurada no computador do usuário, e a {{Glossary("user agent")}} encontrar uma correspondência, essa fonte local será usada. Caso contrário, o recurso de fonte especificado usando a função url() é baixado e usado.

+ +

Ao permitir que os autores forneçam suas próprias fontes, @font-face torna possível projetar conteúdo sem se limitar às chamadas fontes "seguras para a web" (ou seja, as fontes que são tão comuns que são consideradas como universalmente disponível). A capacidade de especificar o nome de uma fonte instalada localmente a ser procurada e usada permite personalizar a fonte além do básico, ao mesmo tempo em que é possível fazê-lo sem depender de uma conexão com a Internet.

+ +

É comum usar url() e local() juntos, para que a cópia instalada da fonte do usuário seja usada, se disponível, voltando ao download de uma cópia da fonte, caso ela não seja encontrada no dispositivo do usuário.

+ +

A regra de CSS @font-face pode ser usada não apenas no nível superior de um CSS, mas também dentro de qualquer CSS conditional-group at-rule.

+ +
@font-face {
+  font-family: "Open Sans";
+  src: url("/fonts/OpenSans-Regular-webfont.woff2") format("woff2"),
+       url("/fonts/OpenSans-Regular-webfont.woff") format("woff");
+}
+ +

Sintaxe

+ +

Descritores

+ +
+
{{cssxref("@font-face/font-display", "font-display")}}
+
Determina como uma fonte é exibida, com base em se e quando é baixada e pronta para uso.
+
{{cssxref("@font-face/font-family", "font-family")}}
+
Especifica um nome que será usado como o valor nominal da fonte para as propriedades da fonte.
+
{{cssxref("@font-face/font-stretch", "font-stretch")}}
+
Um valor {{cssxref ("font-stretch")}}. Desde o Firefox 61 (e em outros navegadores modernos), isso também aceita dois valores para especificar um intervalo suportado por uma fonte, por exemplo, extensão de fonte: font-stretch: 50% 200%;
+
{{cssxref("@font-face/font-style", "font-style")}}
+
Um valor {{cssxref ("font-style")}}. Desde o Firefox 61 (e em outros navegadores modernos), isso também aceita dois valores para especificar um intervalo suportado por uma fonte, por exemplo font-style: oblique 20deg 50deg;
+
{{cssxref("@font-face/font-weight", "font-weight")}}
+
Um valor de {{cssxref ("font-weight")}}. Desde o Firefox 61 (e em outros navegadores modernos), isso também aceita dois valores para especificar um intervalo suportado por uma fonte, por exemplo font-weight: 100 400;
+
{{cssxref("@font-face/font-variant", "font-variant")}}
+
Um valor {{cssxref("font-variant")}}.
+
{{cssxref("font-feature-settings", "font-feature-settings")}}
+
Permite o controle sobre recursos tipográficos avançados em fontes OpenType.
+
{{cssxref("@font-face/font-variation-settings", "font-variation-settings")}}
+
Permite o controle de baixo nível sobre as variações de fonte OpenType ou TrueType, especificando os nomes dos quatro eixos das letras dos recursos para variar, juntamente com seus valores de variação.
+
{{cssxref("@font-face/src", "src")}}
+
+

Especifica o recurso que contém os dados da fonte. Pode ser um URL para um local de arquivo de fonte remota ou o nome de uma fonte no computador do usuário.

+ +

Para fornecer ao navegador uma dica sobre o formato de um recurso de fonte - para que ele possa selecionar um adequado - é possível incluir um tipo de formato dentro de uma função format():

+ +
src: url(ideal-sans-serif.woff) format("woff"),
+     url(basic-sans-serif.ttf) format("truetype");
+ +

Os tipos disponíveis são: "woff", "woff2", "truetype", "opentype", "embedded-opentype", e "svg".

+
+
{{cssxref("@font-face/unicode-range", "unicode-range")}}
+
O intervalo de pontos de código Unicode a serem usados na fonte.
+
+ +

Sintaxe formal

+ +
{{csssyntax}}
+ +

Exemplos

+ +

Este exemplo simplesmente especifica uma fonte para download a ser usada, aplicando-a a todo o corpo do documento:

+ +

Veja este exemplo

+ +
<html>
+<head>
+  <title>Web Font Sample</title>
+  <style type="text/css" media="screen, print">
+    @font-face {
+      font-family: "Bitstream Vera Serif Bold";
+      src: url("https://mdn.mozillademos.org/files/2468/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 "Helvetica Neue Bold" é usada; se o usuário não tiver essa fonte instalada (dois nomes diferentes são tentados), a fonte para download denominada "MgOpenModernaBold.ttf" será usada:

+ +
@font-face {
+  font-family: MyHelvetica;
+  src: local("Helvetica Neue Bold"),
+       local("HelveticaNeue-Bold"),
+       url(MgOpenModernaBold.ttf);
+  font-weight: bold;
+}
+
+ +

Font MIME Types

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
FormatoMIME type
TrueTypefont/ttf
OpenTypefont/otf
Web Open File Formatfont/woff
Web Open File Format 2font/woff2
+ +

Notes

+ + + +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('WOFF2.0', '', 'WOFF2 font format')}}{{Spec2('WOFF2.0')}}Especificação de formato de fonte com novo algoritmo de compactação.
{{SpecName('WOFF1.0', '', 'WOFF font format')}}{{Spec2('WOFF1.0')}}Especificação de formato
{{SpecName('CSS3 Fonts', '#font-face-rule', '@font-face')}}{{Spec2('CSS3 Fonts')}}Definição Inicial
+ +

Compatibilidade do navegador

+ + + +

{{Compat("css.at-rules.font-face")}}

+ +

Veja Também

+ + diff --git a/files/pt-br/web/css/@import/index.html b/files/pt-br/web/css/@import/index.html new file mode 100644 index 0000000000..9081439ecb --- /dev/null +++ b/files/pt-br/web/css/@import/index.html @@ -0,0 +1,121 @@ +--- +title: '@import' +slug: Web/CSS/@import +translation_of: Web/CSS/@import +--- +
{{CSSRef}}
+ +

Sumário

+ +

A Regra Atribuída (at-rule) CSS @import é usado para importar regras de estilo de outras folhas de estilo. Estas regras devem preceder todos os outros tipos de regras, exceto as  regrasde @charset ; uma vez que não é um Declaração aninhada, @import não pode ser usado dentro do grupo condicional de regras atribuídas (at-rules).

+ +

Assim como os agentes do usuário podem evitar a recuperação de recursos para os tipos de mídia incompatíveis, os autores podem especificar regras @import dependentes de mídia. Estas importações condicionais devem ter media queries separadas por vírgulas após a URI. Na ausência de qualquer consulta de mídia (media queries), a importação é incondicional. Especificando todos para o médio tem o mesmo efeito.

+ +

Sintaxe

+ +
@import url;
+@import url list-of-media-queries;
+
+ +

where:

+ +
+
url
+
É algo como {{cssxref("<string>")}} ou como {{cssxref("<uri>")}} representaando o local de onde o recurso será importado. A URL pode ser absoluta ou relativa. Perceba que a URL não precisa, necessariamente, ser um arquivo específico; ela pode especificar o nome do pacotee parcialmente, e o arquivo apropriado será escolhido automaticamente (exemplo: chrome://communicator/skin/). Veja aqui para mais informações.
+
list-of-media-queries
+
É uma lista separada por vírgulas de consultas de mídia (media queries) conidicionando a aplicação das regras de CSS definidas na URL relacionada. Se o navegador não suportar quaisquer consultas de mídia, ele não carregará o recurso relacionado.
+
+ +

Sintaxe formal

+ +
{{csssyntax}}
+ +

Exemplos

+ +
@import url("fineprint.css") print;
+@import url("bluish.css") projection, tv;
+@import 'custom.css';
+@import url("chrome://communicator/skin/");
+@import "common.css" screen, projection;
+@import url('landscape.css') screen and (orientation:landscape);
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoSituaçãoComentário
{{SpecName('CSS3 Media Queries', '#media0', '@import')}}{{Spec2('CSS3 Media Queries')}}Estendeu a sintaxe para apoiar qualquer consulta de mídia e não apenas simples tipos de mídia (media types).
{{SpecName('CSS2.1', 'cascade.html#at-import', '@import')}}{{Spec2('CSS2.1')}}Adicionado suporte para {{cssxref("<string>")}} para denotar a URL de uma folha de  estilo,
+ e obrigatoriedade da regra @import no início do documento CSS.
{{SpecName('CSS1', '#the-cascade', '@import')}}{{Spec2('CSS1')}}Definição inicial
+ +

Browser compatibilidade

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}5.5{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suorte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}5.5{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
diff --git a/files/pt-br/web/css/@keyframes/index.html b/files/pt-br/web/css/@keyframes/index.html new file mode 100644 index 0000000000..c11df0eee6 --- /dev/null +++ b/files/pt-br/web/css/@keyframes/index.html @@ -0,0 +1,222 @@ +--- +title: '@keyframes' +slug: Web/CSS/@keyframes +translation_of: Web/CSS/@keyframes +--- +

{{CSSRef}}

+ +

The @keyframes CSS at-rule controls the intermediate steps in a CSS animation sequence by defining styles for keyframes (or waypoints) along the animation sequence. This gives more control over the intermediate steps of the animation sequence than transitions.

+ +
@keyframes slidein {
+  from {
+    margin-left: 100%;
+    width: 300%;
+  }
+
+  to {
+    margin-left: 0%;
+    width: 100%;
+  }
+}
+ +

JavaScript can access the @keyframes at-rule with the CSS object model interface {{domxref("CSSKeyframesRule")}}.

+ +

To use keyframes, create a @keyframes rule with a name that is then used by the {{ cssxref("animation-name") }} property to match an animation to its keyframe declaration. Each @keyframes rule contains a style list of keyframe selectors, which specify percentages along the animation when the keyframe occurs, and a block containing the styles for that keyframe.

+ +

You can list the keyframe percentages in any order; they will be handled in the order they should occur.

+ +

Valid keyframe lists

+ +

If a keyframe rule doesn't specify the start or end states of the animation (that is, 0%/from and 100%/to, browsers will use the element's existing styles for the start/end states. This can be used to animate an element from its initial state and back.

+ +

Properties that can't be animated in keyframe rules are ignored, but supported properties will still be animated.

+ +

Resolving duplicates

+ +

If multiple keyframe sets exist for a given name, the last one encountered by the parser is used. @keyframes rules don't cascade, so animations never derive keyframes from more than one rule set.

+ +

If a given animation time offset is duplicated, the last keyframe in the @keyframes rule for that percentage is used for that frame. There's no cascading within a @keyframes rule if multiple keyframes specify the same percentage values.

+ +

When properties are left out of some keyframes

+ +

Properties that aren't specified in every keyframe are interpolated if possible — properties that can't be interpolated are dropped from the animation. For example:

+ +
@keyframes identifier {
+  0% { top: 0; left: 0; }
+  30% { top: 50px; }
+  68%, 72% { left: 50px; }
+  100% { top: 100px; left: 100%; }
+}
+
+ +

Here, the {{ cssxref("top") }} property animates using the 0%, 30%, and 100% keyframes, and {{ cssxref("left") }} animates using the 0%, 68%, and 100% keyframes.

+ +

When a keyframe is defined multiple times

+ +

If a keyframe is defined multiple times but not all affected properties are in each keyframe, only the values specified in the latest keyframe are considered. For example:

+ +
@keyframes identifier {
+  0% { top: 0; }
+  50% { top: 30px; left: 20px; }
+  50% { top: 10px; }
+  100% { top: 0; }
+}
+
+ +

In this example, at the 50% keyframe, the value used is top: 10px and all other values at this keyframe are ignored.

+ +

{{ non-standard_inline }} {{ fx_minversion_inline("14") }} Cascading keyframes are supported starting in Firefox 14. For the example above, it means that at the 50% keyframe, the value left: 20px will be considered. This is not defined in the specification yet, but it is being discussed.

+ +

!important in a keyframe

+ +

Declarations in a keyframe qualified with !important are ignored.

+ +
@keyframes important1 {
+  from { margin-top: 50px; }
+  50%  { margin-top: 150px !important; } /* ignored */
+  to   { margin-top: 100px; }
+}
+
+@keyframes important2 {
+  from { margin-top: 50px;
+         margin-bottom: 100px; }
+  to   { margin-top: 150px !important; /* ignored */
+         margin-bottom: 50px; }
+}
+
+ +

Syntax

+ +

Values

+ +
+
{{cssxref("custom-ident")}}
+
A name identifying the keyframe list. This must match the identifier production in CSS syntax.
+
from
+
A starting offset of 0%.
+
to
+
An ending offset of 100%.
+
{{cssxref("<percentage>")}}
+
A percentage of the time through the animation sequence at which the specified keyframe should occur.
+
+ +

Formal syntax

+ +
{{csssyntax}}
+ +

Examples

+ +

See Using CSS animations for examples.

+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSS3 Animations', '#keyframes', '@keyframes') }}{{ Spec2('CSS3 Animations') }} 
+ +

Browser compatibility

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support +

{{ CompatVersionUnknown() }}{{ property_prefix("-webkit") }}
+ 43.0

+
{{CompatVersionUnknown}}{{ CompatGeckoDesktop("5.0") }}{{ property_prefix("-moz") }}
+ {{ CompatGeckoDesktop("16.0") }}
1012 {{ property_prefix("-o") }}
+ 12.10 #
+

4.0{{ property_prefix("-webkit") }}
+ 9.0 #

+
ignore !important declarations{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop(19)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{ CompatVersionUnknown() }}{{ property_prefix("-webkit") }}{{CompatVersionUnknown}}{{ CompatGeckoMobile("5.0") }}{{ property_prefix("-moz") }}
+ {{ CompatGeckoMobile("16.0") }}
{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
ignore !important declarations{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(19)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Notes

+ +
    +
  1. @keyframes unsupported in scoped stylesheets in Firefox ({{bug(830056)}}).
  2. +
+ +

See also

+ + diff --git a/files/pt-br/web/css/@media/aspect-ratio/index.html b/files/pt-br/web/css/@media/aspect-ratio/index.html new file mode 100644 index 0000000000..73b86c6b2d --- /dev/null +++ b/files/pt-br/web/css/@media/aspect-ratio/index.html @@ -0,0 +1,128 @@ +--- +title: aspect-ratio +slug: Web/CSS/@media/aspect-ratio +tags: + - '@media' + - CSS + - Media Queries + - Taxa de aspecto + - Tradução + - características de mídia + - pt-br +translation_of: Web/CSS/@media/aspect-ratio +--- +
{{cssref}}
+ +

característica de mídia CSS aspect-ratio pode ser utilizada para testar a taxa de aspecto de sua {{glossary("viewport")}}.

+ +

Sintaxe

+ +

A característica de aspect-ratio é especificada como um valor de {{cssxref("<ratio>")}} representando a relação de largura-para-altura em aspecto à sua viewport. É uma característica de diferencial, o que significa que você pode fazer uso de variações pré-fixadas de min-aspect-ratio e max-aspect-ratio para definir os os seus valores mínimos e máximos, respectivamente.

+ +

Exemplo

+ +

O exemplo abaixo está contido em um {{htmlElement("iframe")}}, que cria o seu próprio viewport. Redimensione o <iframe> para ver o  aspect-ratio em ação !

+ +

HTML

+ +
<div id='inner'>
+  Observe este elemento, conforme voc&ecirc; altera a largura e a altura da sua viewport.
+</div>
+
+ +

CSS

+ +
/* Taxa de aspecto mínima */
+@media (min-aspect-ratio: 8/5) {
+  div {
+    background: #9af; /* azul */
+  }
+}
+
+/* Taxa de aspecto máxima */
+@media (max-aspect-ratio: 3/2) {
+  div {
+    background: #9ff;  /* ciano */
+  }
+}
+
+/* Taxa de aspecto exata, coloque-a no final para evitar sobrescrita*/
+@media (aspect-ratio: 1/1) {
+  div {
+    background: #f9a; /* vermelho */
+  }
+}
+
+ + + +

Result

+ +
+

{{ EmbedLiveSample('_Exemplo', '300px', '400px') }}

+
+ +

Specificações

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS4 Media Queries', '#aspect-ratio', 'aspect-ratio')}}{{Spec2('CSS4 Media Queries')}}No change.
{{SpecName('CSS3 Media Queries', '#aspect-ratio', 'aspect-ratio')}}{{Spec2('CSS3 Media Queries')}}Initial definition.
+ +

Browser compatibility

+ + + +

{{Compat("css.at-rules.media.aspect-ratio")}}

diff --git a/files/pt-br/web/css/@media/display-mode/index.html b/files/pt-br/web/css/@media/display-mode/index.html new file mode 100644 index 0000000000..64fdf5f4d8 --- /dev/null +++ b/files/pt-br/web/css/@media/display-mode/index.html @@ -0,0 +1,151 @@ +--- +title: Modo de exibição (display-mode) +slug: Web/CSS/@media/display-mode +tags: + - '@media' + - CSS + - Internet + - Rede + - Referencia + - Web + - display + - display-moe + - funcionalidade de mídia + - manifesto das aplicações web +translation_of: Web/CSS/@media/display-mode +--- +
{{cssref}}
+ +

O recurso de mídia CSS {{cssxref("@media")}} do modo de exibição pode ser usado para aplicar estilos com base no modo de exibição de um aplicativo. Você pode usar para prover uma consistente experiência de usuário entre abrir um site a partir de uma URL e um ícone desktop.

+ +

Esse recurso corresponde ao membro da exibição do manifesto do aplicativo da Web. Ambos aplicam-se ao contexto de navegação de nível superior e a qualquer contexto afilhado de navegação. O recurso de consulta aplica-se independentemente de onde um manifesto de aplicativo web está presente.

+ +

Sintaxe

+ +

O recurso display-mode é especificado como um valor de uma palavra chave escolhido da lista abaixo.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Modo de exibiçãoDescriçãoModo de exibição secundário
fullscreen +

Toda a área disponível da tela será usada e nada do agente-usuário (navegador) {{glossary("chrome")}} é mostrado.

+
standalone
standalone +

A aplicação irá parecer uma aplicação independente. Isso pode incluir a aplicação ter uma janela diferente, seu próprio ícone no menu de aplicações, etc. Neste modo, o navegador não irá mostrar os controles de navegação (como barra de endereço, botão voltar, botão página inicial, etc), mas pode incluir outros elementos gráficos como a barra de status.

+
minimal-ui
minimal-ui +

A aplicação irá parecer uma aplicação independente, mas terá um conjunto mínimo de elementos gráficos (UI) para controlar a navegação. Esses elementos podem variar de acordo com o navegador.

+
browser
browser +

A aplicação abre numa aba ou nova janela convencional do navegador, dependendo do navegador e da plataforma.

+
(nenhum)
+ +

Exemplo

+ +
@media all and (display-mode: fullscreen) {
+  body {
+    margin: 0;
+    border: 5px solid black;
+  }
+}
+ +

Especificações

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Manifest', '#the-display-mode-media-feature', 'display-mode')}}{{Spec2('Manifest')}}Definição inicial.
+ +

Compatibilidade entre navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{ CompatChrome(46.0) }}[1]{{ CompatGeckoDesktop(47) }}[2]{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Suporte básico{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatGeckoDesktop(47) }}[2]{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatChrome(46.0) }}[1]
+
+ +

[1] Não suporta o valor minimal-ui. O valor @supports para display-mode só é suportado no Chrome 48.

+ +

[2] Somente os valores fullscreen e browser são suportados na versão 47. minimal-ui e standalone foram adicionados no Firefox 57.

diff --git a/files/pt-br/web/css/@media/index.html b/files/pt-br/web/css/@media/index.html new file mode 100644 index 0000000000..18c46ee615 --- /dev/null +++ b/files/pt-br/web/css/@media/index.html @@ -0,0 +1,446 @@ +--- +title: '@media' +slug: Web/CSS/@media +tags: + - '@media' + - At-rule + - CSS + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/CSS/@media +--- +
{{CSSRef}}
+ +

The @media CSS at-rule  pode ser usada para aplicar estilos com base no resultado de uma ou mais consultas de mídia, que testam o tipo, as características específicas e o ambiente de um dispositivo.

+ +

No CSS, a regra @media deve ser posta na parte superior do seu código ou aninhada dentro de algum outro conditional group at-rule.

+ +
/* Media query */
+@media screen and (min-width: 900px) {
+  article {
+    padding: 1rem 3rem;
+  }
+}
+
+/* Nested media query */
+@supports (display: flex) {
+  @media screen and (min-width: 900px) {
+    article {
+      display: flex;
+    }
+  }
+}
+
+ +

Besides its use in the @media rule, a media query may also be applied to an HTML {{HTMLElement("link")}} element to restrict an entire style sheet to certain media.

+ +
<!-- Media-dependent style sheet included in HTML -->
+<link rel="stylesheet" media="screen and (min-width: 900px)" href="widescreen-styles.css" />
+ +

In JavaScript, @media can be accessed via the {{domxref("CSSMediaRule")}} CSS object model interface.

+ +

Syntax

+ +

The @media at-rule is composed of one or more media queries, each of which consists of an optional media type and any number of media feature expressions. Multiple queries can be combined in various ways by using logical operators, and are case-insensitive.

+ +

Corresponding styles are applied only if a media query computes to true, i.e., when the specified media type matches the type of device the document is being displayed on and all media feature expressions compute as true. Queries involving unknown media types are always false.

+ +
+

Note: A style sheet with a media query attached to its {{HTMLElement("link")}} tag will still download even if the query returns false. Nevertheless, its contents will not apply unless and until the result of the query changes to true.

+
+ +

Media types

+ +

Media types describe the general category of a device. Unless you use the not or only logical operators, the media type is optional and the all type will be implied.

+ +
+
all
+
Suitable for all devices.
+
print
+
Intended for paged material and for documents viewed on screen in print preview mode. Please consult the section on paged media, and the media section of the Getting Started tutorial for information about formatting issues that are specific to paged media.
+
screen
+
Intended primarily for color computer screens.
+
speech
+
Intended for speech synthesizers.
+
+ +
Deprecated media types: CSS2.1 and Media Queries 3 defined several additional media types (tty, tv, projection, handheld, braille, embossed, and aural), but they were deprecated in Media Queries 4 and shouldn't be used. The aural type has been replaced by speech, which is similar.
+ +

Media features

+ +

Media feature expressions test for specific characteristics of the {{glossary("user agent")}}, output device, or environment. They are entirely optional. Each media feature expression must be surrounded by parentheses.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameSummaryNotes
widthWidth of the viewport
heightHeight of the viewport
aspect-ratioWidth-to-height aspect ratio of the viewport
orientationOrientation of the viewport
resolutionPixel density of the output device
scanScanning process of the output device
gridDoes the device use a grid or bitmap screen?
updateHow frequently the output device can modify the appearance of contentAdded in Media Queries Level 4.
overflow-blockHow does the output device handle content that overflows the viewport along the block axis?Added in Media Queries Level 4.
overflow-inlineCan content that overflows the viewport along the inline axis be scrolled?Added in Media Queries Level 4.
colorNumber of bits per color component of the output device, or zero if the device isn't color
color-gamutApproximate range of colors that are supported by the user agent and output deviceAdded in Media Queries Level 4.
color-indexNumber of entries in the output device's color lookup table, or zero if the device does not use such a table
display-modeThe display mode of the application, as specified in the web app manifest's display memberDefined in the Web App Manifest spec.
monochromeBits per pixel in the output device's monochrome frame buffer, or zero if the device isn't monochrome
inverted-colorsIs the user agent or underlying OS inverting colors?Deferred to Media Queries Level 5.
pointerIs the primary input mechanism a pointing device, and if so, how accurate is it?Added in Media Queries Level 4.
hoverDoes the primary input mechanism allow the user to hover over elements?Added in Media Queries Level 4.
any-pointerIs any available input mechanism a pointing device, and if so, how accurate is it?Added in Media Queries Level 4.
any-hoverDoes any available input mechanism allow the user to hover over elements?Added in Media Queries Level 4.
light-levelLight level of the environmentDeferred to Media Queries Level 5.
scriptingIs scripting (e.g., JavaScript) available?Deferred to Media Queries Level 5.
device-width {{obsolete_inline}}Width of the rendering surface of the output deviceDeprecated in Media Queries Level 4.
device-height {{obsolete_inline}}Height of the rendering surface of the output deviceDeprecated in Media Queries Level 4.
device-aspect-ratio {{obsolete_inline}}Width-to-height aspect ratio of the output deviceDeprecated in Media Queries Level 4.
-webkit-device-pixel-ratio {{non-standard_inline}}Number of physical device pixels per CSS pixelNonstandard; WebKit/Blink-specific. If possible, use the resolution media feature instead.
-webkit-transform-3d {{non-standard_inline}}Are CSS 3D {{cssxref("transform")}}s supported?Nonstandard; WebKit/Blink-specific. If possible, use {{cssxref("@supports")}} instead.
-webkit-transform-2d {{non-standard_inline}}Are CSS 2D {{cssxref("transform")}}s supported?Nonstandard; WebKit-specific. If possible, use {{cssxref("@supports")}} instead.
-webkit-transition {{non-standard_inline}}Are CSS {{cssxref("transition")}}s supported?Nonstandard; WebKit-specific. If possible, use {{cssxref("@supports")}} instead.
-webkit-animation {{non-standard_inline}}Are CSS {{cssxref("animation")}}s supported?Nonstandard; WebKit-specific. If possible, use {{cssxref("@supports")}} instead.
+ +

Logical operators

+ +

The logical operators not, and, and only can be used to compose a complex media query. You can also combine multiple media queries into a single rule using a comma-separated list.

+ +

and

+ +

The and operator is used for combining multiple media features together into a single media query, requiring each chained feature to return true in order for the query to be true. It is also used for joining media features with media types.

+ +

not

+ +

The not operator is used to negate a media query, returning true if the query would otherwise return false. If present in a comma-separated list, it will only negate the specific query to which it is applied. If you use the not operator, you must specify an explicit media type.

+ +
+

Note: The not keyword can't be used to negate an individual feature expression, only an entire media query.

+
+ +

only

+ +

The only operator is used to apply a style only if an entire query matches, and is useful for preventing older browsers from applying selected styles. If you use the only operator, you must specify an explicit media type.

+ +

comma-separated lists

+ +

Each query in a comma-separated media query list is treated separately from the others. If any of the queries in a list is true, the entire media statement returns true. In other words, lists behave like the logical operator or.

+ +

Formal syntax

+ +
{{csssyntax}}
+ +

Examples

+ +
@media print {
+  body { font-size: 10pt; }
+}
+
+@media screen {
+  body { font-size: 13px; }
+}
+
+@media screen, print {
+  body { line-height: 1.2; }
+}
+
+@media only screen
+  and (min-device-width: 320px)
+  and (max-device-width: 480px)
+  and (-webkit-min-device-pixel-ratio: 2) {
+    body { line-height: 1.4; }
+}
+
+ +

For more media feature examples, please see the reference page for each specific feature. For more logical operator examples, please see Using media queries.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Compat', '#css-media-queries', 'CSS Media Queries')}}{{Spec2('Compat')}}Standardizes the -webkit-device-pixel-ratio and -webkit-transform-3d media features.
{{SpecName('CSS3 Conditional', '#at-media', '@media')}}{{Spec2('CSS3 Conditional')}}Defines the basic syntax of the @media rule.
{{SpecName('CSS4 Media Queries', '#media', '@media')}}{{Spec2('CSS4 Media Queries')}} +

Adds scripting, pointer, hover, light-level, update-frequency, overflow-block, and overflow-inline media features.
+ Deprecates all media types except for screen, print, speech, and all.
+ Makes the syntax more flexible by adding, among other things, the or keyword.

+
{{SpecName('CSS3 Media Queries', '#media0', '@media')}}{{Spec2('CSS3 Media Queries')}}No change.
{{SpecName('CSS2.1', 'media.html#at-media-rule', '@media')}}{{Spec2('CSS2.1')}}Initial definition.
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support (all, print, screen)1.0{{CompatVersionUnknown}}{{ CompatGeckoDesktop(1.7) }}6.09.21.3
speech{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}9.2{{CompatNo}}
Media features1.0{{CompatVersionUnknown}}{{ CompatGeckoDesktop(1.7) }}9.09.21.3
display-mode media feature{{CompatUnknown}}{{CompatNo}}{{ CompatGeckoDesktop(47) }}[1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support (all, print, screen)1.0{{CompatVersionUnknown}}{{ CompatGeckoMobile(1.7) }}{{CompatVersionUnknown}}9.03.1
speech{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}9.0{{CompatNo}}
Media features1.0{{CompatVersionUnknown}}{{ CompatGeckoMobile(1.7) }}{{CompatVersionUnknown}}9.03.1
display-mode media feature{{CompatUnknown}}{{CompatNo}}{{CompatGeckoMobile(47)}}[1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Only the fullscreen and browser values of display-mode were supported in 47. minimal-ui and standalone were added in Firefox 57.

+ +

See also

+ + diff --git a/files/pt-br/web/css/@media/prefers-color-scheme/index.html b/files/pt-br/web/css/@media/prefers-color-scheme/index.html new file mode 100644 index 0000000000..dc224d8741 --- /dev/null +++ b/files/pt-br/web/css/@media/prefers-color-scheme/index.html @@ -0,0 +1,104 @@ +--- +title: prefers-color-scheme +slug: Web/CSS/@media/prefers-color-scheme +tags: + - '@media' + - CSS + - Reference + - Web + - prefers-color-scheme +translation_of: Web/CSS/@media/prefers-color-scheme +--- +
+

Se você definiu privacy.resistFingerprinting como true, prefers-color-scheme será substituída pela light.

+
+ +

O prefers-color-scheme CSS media feature é usado para detectar se o usuário solicitou que o sistema use um tema de cores claras ou escuras.

+ +

Syntax

+ +
+
no-preference
+
Indica que o usuário não fez nenhuma preferência conhecida pelo sistema. Este valor da palavra-chave é avaliado como false no contexo booleano.
+
light
+
Indica que o usuário notificou o sistema de que prefere uma interface com um tema claro.
+
dark
+
Indica que o usuário notificou o sistema de que prefere uma interface com um tema escuro.
+
+ +

Exemplos

+ +

Os elementos abaixo têm um tema de cores inicial. Eles podem ser mais temáticos de acordo com a preferência do esquema de cores do usuário.

+ +

HTML

+ +
<div class="day">Dia (inicial)</div>
+<div class="day light-scheme">Dia (modificar e utilizar um tema claro)</div>
+<div class="day dark-scheme">Dia (modificar e utilizar um tema escuro)</div> <br>
+
+<div class="night">Noite (inicial)</div>
+<div class="night light-scheme">Noite (modificar e utilizar um tema claro)</div>
+<div class="night dark-scheme">Noite (modificar e utilizar um tema escuro)</div>
+ +

CSS

+ +
.day   { background: #eee; color: black; }
+.night { background: #333; color: white; }
+
+@media (prefers-color-scheme: dark) {
+  .day.dark-scheme   { background:  #333; color: white; }
+  .night.dark-scheme { background: black; color:  #ddd; }
+}
+
+@media (prefers-color-scheme: light) {
+  .day.light-scheme   { background: white; color:  #555; }
+  .night.light-scheme { background:  #eee; color: black; }
+}
+
+.day, .night {
+  display: inline-block;
+  padding: 1em;
+  width: 7em;
+  height: 2em;
+  vertical-align: middle;
+}
+
+ +

Resultado

+ +

{{EmbedLiveSample("Exemples")}}

+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentários
{{SpecName('CSS5 Media Queries', '#descdef-media-prefers-color-scheme', 'prefers-color-scheme')}}{{Spec2('CSS5 Media Queries')}}Definição inicial.
+ +

Compatibilidade dos navegadores

+ + + +

{{Compat("css.at-rules.media.prefers-color-scheme")}}

+ +

Veja também

+ + + +
{{QuickLinksWithSubpages("/en-US/docs/Web/CSS/@media/")}}
diff --git a/files/pt-br/web/css/@page/index.html b/files/pt-br/web/css/@page/index.html new file mode 100644 index 0000000000..5303c7e2c1 --- /dev/null +++ b/files/pt-br/web/css/@page/index.html @@ -0,0 +1,109 @@ +--- +title: '@page' +slug: Web/CSS/@page +tags: + - '@page' + - CSS + - pagina +translation_of: Web/CSS/@page +--- +
{{CSSRef}}
+ +

Resumo

+ +

A regra CSS @page é utilizada para modificar algumas propriedades CSS quando o documento for impresso. Você não pode mudar todas as propriedades CSS com @page. Você poderá somente mudar as margens, orphans, widows, e page breaks do documento. Na tentativa de mudar outra propriedade CSS, elas serão ignoradas.

+ +

A regra CSS @page pode ser acessada via interface do modelo de objeto {{domxref("CSSPageRule")}}.

+ +
Nota: A W3C está analisando como lidar com unidades viewport-related {{cssxref("<length>")}}, vh, vw, vmin, and vmax. Enquanto isso, não use eles junto com a regra @page.
+ +

Sintaxe

+ +
@page :pseudo-class {
+  margin:2in;
+}
+
+ +

Exemplos

+ +

Podemos fazer referência a vários pseudo-classes de @page por exemplo.

+ + + +

Especificações

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Paged Media', '#at-page-rule', '@page')}}{{Spec2('CSS3 Paged Media')}}Sem mudanças para {{SpecName('CSS2.1')}}, though more CSS at-rules can be used inside a @page.
{{SpecName('CSS2.1', 'page.html#page-selectors', '@page')}}{{Spec2('CSS2.1')}} 
+ +

Compatibilidade dos navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support2.0{{CompatGeckoDesktop("19.0")}}8.06.05.0
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatGeckoMobile("19.0")}}{{CompatUnknown}}{{CompatUnknown}}{CompatUnknown}}
+
diff --git a/files/pt-br/web/css/_colon_active/index.html b/files/pt-br/web/css/_colon_active/index.html new file mode 100644 index 0000000000..5c929711bf --- /dev/null +++ b/files/pt-br/web/css/_colon_active/index.html @@ -0,0 +1,159 @@ +--- +title: ':active' +slug: 'Web/CSS/:active' +translation_of: 'Web/CSS/:active' +--- +
{{CSSRef}}
+ +
+ +
A pseudo-classe css <strong> :active </strong>
+ +

Esse estilo pode ser substituído por qualquer outra pseudo-classe relacionada ao link, ou seja, {{cssxref(":link")}}, {{cssxref(":hover")}} e {{cssxref(":visited")}}, aparecendo nas regras subseqüentes. Para estilizar apropriadamente os links, você precisa colocar a regra  :active depois de todas as outras regras relacionadas ao link, conforme definido pela ordem LVHA. :link:visited:hover:active.

+ +
Nota: Em sistemas com mouses com vários botões, o CSS 3 especifica que a pseudo-classe :active só deve ser aplicada ao botão principal em mouses destros, este é tipicamente o botão mais à esquerda.
+ +

Exemplo

+ +
+

HTML

+ +
<body>
+    <h1>:active CSS selector example</h1>
+    <p>The following link will turn lime during the time you click it and release the click: <a href="#">Mozilla Developer Network</a>.</p>
+</body>
+ +

CSS

+ +
body { background-color: #ffffc9 }
+a:link { color: blue } /* links não visitados */
+a:visited { color: purple } /* links visitados */
+a:hover { font-weight: bold } /* user hovers */
+a:active { color: lime } /* links ativos */
+
+ +
{{EmbedLiveSample('example',600,140)}}
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('CSS4 Selectors', '#active-pseudo', ':active')}}{{Spec2('CSS4 Selectors')}} +
+
Nenhuma mudança.
+
+
{{SpecName('CSS3 Selectors', '#useraction-pseudos', ':active')}}{{Spec2('CSS3 Selectors')}} +
+
Nenhuma mudança.
+
+
{{SpecName('CSS2.1', 'selector.html#dynamic-pseudo-classes', ':active')}}{{Spec2('CSS2.1')}} +
+
Nenhuma mudança.
+
+
{{SpecName('CSS1', '#anchor-pseudo-classes', ':active')}}{{Spec2('CSS1')}} +
+
Definição inicial.
+
+
+ +

Compatibilidade do navegador

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
RecursoChromeFirefox (Gecko)Internet ExplorerOperaSafari
Support on the <a> element1.0{{CompatGeckoDesktop("1.0")}}4.05.01.0
Support on any element1.0{{CompatGeckoDesktop("1.0")}}8.07.0{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Support on the <a> element1.0{{CompatGeckoMobile("1.0")}}6.06.01.0
Support on any element1.0{{CompatGeckoMobile("1.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}} [1]
+
+ +

[1] By default, Safari Mobile does not use the {{cssxref(":active")}} state unless there is a touchstart event handler on the relevant element or on the {{HTMLElement("body")}}.

+ +

Veja também

+ + diff --git a/files/pt-br/web/css/_colon_blank/index.html b/files/pt-br/web/css/_colon_blank/index.html new file mode 100644 index 0000000000..97395a29d1 --- /dev/null +++ b/files/pt-br/web/css/_colon_blank/index.html @@ -0,0 +1,57 @@ +--- +title: ':blank' +slug: 'Web/CSS/:blank' +tags: + - ':blank' + - CSS + - Experimental + - Necessita de Exemplos + - Pseudo-classe + - Seletores CSS +translation_of: 'Web/CSS/:blank' +--- +

{{CSSRef}}{{Draft}}{{SeeCompatTable}}

+ +
+

Note: The :blank selector is considered at risk, as the CSSWG keeps changing it.

+ +

See CSSWG issue #1967.

+
+ +

A pseudo-classe CSS :blank seleciona elementos de entrada do usuário vazios (ex. {{HTMLElement("input")}} ou {{HTMLElement("textarea")}}).

+ +

Sintaxe

+ +
{{CSSSyntax}}
+ +

Especificações

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("CSS4 Selectors", "#blank-pseudo", ":blank")}}{{Spec2("CSS4 Selectors")}}Definição inicial.
+ +

Compatibilidade com navegadores

+ + + +

{{Compat("css.selectors.blank")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/css/_colon_checked/index.html b/files/pt-br/web/css/_colon_checked/index.html new file mode 100644 index 0000000000..17954e5a20 --- /dev/null +++ b/files/pt-br/web/css/_colon_checked/index.html @@ -0,0 +1,239 @@ +--- +title: ':checked' +slug: 'Web/CSS/:checked' +tags: + - ':checked' + - CSS + - CSS Pseudo-classe + - Layout + - Referencia + - Web +translation_of: 'Web/CSS/:checked' +--- +
{{CSSRef}}
+ +

A pseudo-classe :checked de um seletor CSS representa um elemento radio (<input type="radio">), checkbox (<input type="checkbox">) ou option ({{ HTMLElement("option") }} em um {{ HTMLElement("select") }})  que está marcada ou alternado para um estado ligado. O usuário pode mudar seu estado clicando no elemento, ou selecionando um valor diferente, nesse caso a pseudo-classe :checked não se aplica a esse elemento, mas vai para um elemento relevante.

+ +

Sintaxe

+ +
input:checked {
+  margin-left: 25px;
+  border: 1px solid blue;
+}
+
+ +

Sintaxe formal

+ +
elemento:checked { estilos de propriedades }
+ +

Exemplos

+ +

Exemplo de seletores

+ +
/* qualquer elemento "checkable" */
+:checked {
+  width: 50px;
+  height: 50px;
+}
+
+/* qualquer elemento radio */
+input[type="radio"]:checked {
+  margin-left: 25px;
+}
+
+/* apenas elementos checkbox */
+input[type="checkbox"]:checked {
+  display: none;
+}
+
+/* apenas elementos option */
+option:checked {
+  color: red;
+}
+
+ +
+
input[type="radio"]:checked
+
Representa todos os botões de rádio na página que estão ativos
+
+ +
+
input[type="checkbox"]:checked
+
Representa todos os checkboxes na página que estão ativos
+
option:checked
+
Representa todos os selects na página que estão selecionados
+
+ +

Usando checkboxes escodindos para amarzenar algum valor booleano.

+ +

A pseudo-classe :checked aplicada em checkboxes escondidos, adicionado ao início de sua página pode
+ ser aplicada de forma a armazenar algum booleano dinâmico para ser usado por uma regra CSS. O exemplo a seguir mostra como exibir/esconder um elemento expansível com um simples clique em um botão (download esse demo).

+ +
<!doctype html>
+<html>
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
+<title>Elementos expansíveis</title>
+<style type="text/css">
+#expand-btn {
+    margin: 0 3px;
+    display: inline-block;
+    font: 12px / 13px "Lucida Grande", sans-serif;
+    text-shadow: rgba(255, 255, 255, 0.4) 0 1px;
+    padding: 3px 6px;
+    border: 1px solid rgba(0, 0, 0, 0.6);
+    background-color: #969696;
+    cursor: default;
+    -moz-border-radius: 3px;
+    -webkit-border-radius: 3px;
+    border-radius: 3px;
+    -moz-box-shadow: rgba(255, 255, 255, 0.4) 0 1px, inset 0 20px 20px -10px white;
+    -webkit-box-shadow: rgba(255, 255, 255, 0.4) 0 1px, inset 0 20px 20px -10px white;
+    box-shadow: rgba(255, 255, 255, 0.4) 0 1px, inset 0 20px 20px -10px white;
+}
+
+#isexpanded:checked ~ #expand-btn, #isexpanded:checked ~ * #expand-btn {
+    background: #B5B5B5;
+    -moz-box-shadow: inset rgba(0, 0, 0, 0.4) 0 -5px 12px, inset rgba(0, 0, 0, 1) 0 1px 3px, rgba(255, 255, 255, 0.4) 0 1px;
+    -webkit-box-shadow: inset rgba(0, 0, 0, 0.4) 0 -5px 12px, inset rgba(0, 0, 0, 1) 0 1px 3px, rgba(255, 255, 255, 0.4) 0 1px;
+    box-shadow: inset rgba(0, 0, 0, 0.4) 0 -5px 12px, inset rgba(0, 0, 0, 1) 0 1px 3px, rgba(255, 255, 255, 0.4) 0 1px;
+}
+
+#isexpanded, .expandable {
+    display: none;
+}
+
+#isexpanded:checked ~ * tr.expandable {
+    display: table-row;
+    background: #cccccc;
+
+}
+
+#isexpanded:checked ~ p.expandable, #isexpanded:checked ~ * p.expandable {
+    display: block;
+    background: #cccccc;
+}
+</style>
+</head>
+<body>
+
+<input type="checkbox" id="isexpanded" />
+
+<h1>Elementos expansíveis</h1>
+<table>
+    <thead>
+        <tr><th>Coluna #1</th><th>Coluna #2</th><th>Coluna #3</th></tr>
+    </thead>
+    <tbody>
+        <tr class="expandable"><td>[cell text]</td><td>[cell text]</td><td>[cell text]</td></tr>
+        <tr><td>[cell text]</td><td>[cell text]</td><td>[cell text]</td></tr>
+        <tr><td>[cell text]</td><td>[cell text]</td><td>[cell text]</td></tr>
+        <tr class="expandable"><td>[cell text]</td><td>[cell text]</td><td>[cell text]</td></tr>
+        <tr class="expandable"><td>[cell text]</td><td>[cell text]</td><td>[cell text]</td></tr>
+    </tbody>
+</table>
+
+<p>[some sample text]</p>
+<p><label for="isexpanded" id="expand-btn">Mostra ou esconder elemntos</label></p>
+<p class="expandable">[outra amostra de texto]</p>
+<p>[alguma amostra de texto]</p>
+</body>
+</html>
+
+ +

{{ EmbedLiveSample('Usando_checkboxes_escodindos_para_amarzenar_algum_valor_booleano', '', '', '', 'Web/CSS/:checked') }}

+ +

Usando radioboxes escondidos para armazenar algum valor CSS booleano

+ +

Você também pode usar a pseudo-classe :checked aplicada a um radioboxe escondido afim de construir, por exemplo, uma galeria de imagem onde as imagens apenas sejam exibidas no tamanho cheio com o clique do mouse em visualizar. Veja essa demonstração como uma dica.

+ +
Nota: Para um efeito análogo, mas baseada na pseudo-classe :hover sem radioboxes escondidos, veja essa demostração, tomadas a partir de uma página :hover.
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoEstatusComentários
{{ SpecName('HTML WHATWG', '#selector-checked', ':checked') }}{{ Spec2('HTML WHATWG') }}Sem mudanças.
{{ SpecName('HTML5 W3C', '#selector-checked', ':checked') }}{{ Spec2('HTML5 W3C') }}Define a semântica sobre o HTML.
{{ SpecName('CSS4 Selectors', '#checked', ':checked') }}{{ Spec2('CSS4 Selectors') }}Sem mudanças.
{{ SpecName('CSS3 Basic UI', '#pseudo-checked', ':checked') }}{{ Spec2('CSS3 Basic UI') }}Link para Seletores nível 3
{{ SpecName('CSS3 Selectors', '#checked', ':checked') }}{{ Spec2('CSS3 Selectors') }}Define a pseudo-classe, mas não associação semântica
+ +

Compatibilidade de navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico1.0{{ CompatGeckoDesktop(1.0) }}9.09.03.1
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico2.1{{ CompatGeckoMobile(1.0) }}9.09.53.1
+
diff --git a/files/pt-br/web/css/_colon_disabled/index.html b/files/pt-br/web/css/_colon_disabled/index.html new file mode 100644 index 0000000000..702714e76c --- /dev/null +++ b/files/pt-br/web/css/_colon_disabled/index.html @@ -0,0 +1,128 @@ +--- +title: ':disabled' +slug: 'Web/CSS/:disabled' +translation_of: 'Web/CSS/:disabled' +--- +
{{CSSRef}}
+ +

pseudo-classe CSS  :disabled representa qualquer elemento desativado. Um elemento é desativado se não puder ser ativado (selecionado, clicado, digitado etc.) ou aceitar o foco. O elemento também possui um estado habilitado, no qual ele pode ser ativado ou aceitar o foco.

+ +
/* Selects any disabled <input> */
+input:disabled {
+  background: #ccc;
+}
+ +

Sintaxe

+ +
{{csssyntax}}
+ +

Exemplo

+ +

Este exemplo mostra um formulário básico de envio. Ele usa o evento JavaScript change para permitir que o usuário ative / desative os campos de faturamento.

+ +

HTML

+ +
<form action="#">
+  <fieldset id="shipping">
+    <legend>Shipping address</legend>
+    <input type="text" placeholder="Name">
+    <input type="text" placeholder="Address">
+    <input type="text" placeholder="Zip Code">
+  </fieldset>
+  <br>
+  <fieldset id="billing">
+    <legend>Billing address</legend>
+    <label for="billing-checkbox">Same as shipping address:</label>
+    <input type="checkbox" id="billing-checkbox" checked>
+    <br>
+    <input type="text" placeholder="Name" disabled>
+    <input type="text" placeholder="Address" disabled>
+    <input type="text" placeholder="Zip Code" disabled>
+  </fieldset>
+</form>
+
+ +

CSS

+ +
input[type="text"]:disabled {
+  background: #ccc;
+}
+
+ +

JavaScript

+ +
// Wait for the page to finish loading
+document.addEventListener('DOMContentLoaded', function () {
+  // Attach `change` event listener to checkbox
+  document.getElementById('billing-checkbox').onchange = toggleBilling;
+}, false);
+
+function toggleBilling() {
+  // Select the billing text fields
+  var billingItems = document.querySelectorAll('#billing input[type="text"]');
+
+  // Toggle the billing text fields
+  for (var i = 0; i < billingItems.length; i++) {
+    billingItems[i].disabled = !billingItems[i].disabled;
+  }
+}
+
+ +

Resultado

+ +

{{EmbedLiveSample('Example', 300, 250)}}

+ +

Expecificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#selector-disabled', ':disabled')}}{{Spec2('HTML WHATWG')}}No change.
{{SpecName('HTML5 W3C', '#selector-disabled', ':disabled')}}{{Spec2('HTML5 W3C')}}Defines the semantics of HTML and forms.
{{SpecName('CSS4 Selectors', '#enableddisabled', ':disabled')}}{{Spec2('CSS4 Selectors')}}No change.
{{SpecName('CSS3 Basic UI', '#pseudo-classes', ':disabled')}}{{Spec2('CSS3 Basic UI')}}Links to Selectors Level 3.
{{SpecName('CSS3 Selectors', '#enableddisabled', ':disabled')}}{{Spec2('CSS3 Selectors')}}Defines the pseudo-class, but not the associated semantics.
+ +

Compatibilidades entre navegadores

+ +
+ + +

{{Compat("css.selectors.disabled")}}

+
+ +

Veja também

+ + diff --git a/files/pt-br/web/css/_colon_empty/index.html b/files/pt-br/web/css/_colon_empty/index.html new file mode 100644 index 0000000000..feac75ca32 --- /dev/null +++ b/files/pt-br/web/css/_colon_empty/index.html @@ -0,0 +1,96 @@ +--- +title: ':empty' +slug: 'Web/CSS/:empty' +translation_of: 'Web/CSS/:empty' +--- +
{{ CSSRef() }}
+ +

A pseudo-classe CSS :empty representa qualquer elemento que não tenha filhos. Aqui, filhos podem ser outros elementos ou blocos de texto (incluindo espaços em branco). Comentários e instruções de processamento não são considerados ao se determinar se um elemento é vazio.

+ +
/* Seleciona qualquer <div> que não tenha conteúdo */
+div:empty {
+  background: lime;
+}
+ +

Sintaxe

+ +
{{csssyntax}}
+
+ +

Exemplos

+ +

HTML

+ +
<div class="box"><!-- Eu serei verde. --></div>
+<div class="box">Eu serei rosa.</div>
+<div class="box">
+    <!-- Eu serei rosa por causa do espaço em branco em volta desse comantário -->
+</div>
+ +

CSS

+ + + +
.box {
+  background: pink;
+  height: 80px;
+  width: 80px;
+}
+
+.box:empty {
+  background: lime;
+}
+ +

Resultado

+ +

{{EmbedLiveSample('Examples', 300, 80)}}

+ +

Questões de acessibilidade

+ +

Tecnologias assistivas como leitores de tela não conseguem identificar e processar conteúdos interativos que estejam vazios. Todo conteúdo interativo deve ter um nome acessível, que é criado ao fornecer um valor de texto para o elemento pai do controle interativo (âncoras, botões, etc.). Nomes acessíveis expõem o controle interativo à árvore de acessibilidade, uma API que comunica informações importantes úteis para tecnologias assistivas.

+ +

The text that provides the interactive control's accessible name can be hidden using a combination of properties that remove it visually from the screen but keep it parseable by assistive technology. This is commonly used for buttons that rely solely on an icon to convey purpose.

+ + + +

Specifications

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSS4 Selectors', '#empty-pseudo', ':empty') }}{{ Spec2('CSS4 Selectors') }}No change
{{ SpecName('CSS3 Selectors', '#empty-pseudo', ':empty') }}{{ Spec2('CSS3 Selectors') }}Initial definition
+ +

Browser compatibility

+ +
+ + +

{{Compat("css.selectors.empty")}}

+
diff --git a/files/pt-br/web/css/_colon_enabled/index.html b/files/pt-br/web/css/_colon_enabled/index.html new file mode 100644 index 0000000000..2d51b11e61 --- /dev/null +++ b/files/pt-br/web/css/_colon_enabled/index.html @@ -0,0 +1,103 @@ +--- +title: ':enabled' +slug: 'Web/CSS/:enabled' +translation_of: 'Web/CSS/:enabled' +--- +
{{CSSRef}}
+ +

pseudo-classe CSS  :enabled representa qualquer elemento ativado. Um elemento é ativado se puder ser ativado (selecionado, clicado, digitado etc.) ou aceitar o foco. O elemento também possui um estado desativado, no qual não pode ser ativado nem aceitar foco.

+ +
/* Seleciona qualquer <input> ativado */
+input:enabled {
+  color: blue;
+}
+ +

Sintaxe

+ +
{{csssyntax}}
+ +

Exemplo

+ +

O exemplo a seguir torna a cor do texto e do botão <input> verde quando ativada e cinza quando desativada. Isso ajuda o usuário a entender quais elementos podem ser interagidos..

+ +
+

HTML

+ +
<form action="url_of_form">
+  <label for="FirstField">First field (enabled):</label>
+  <input type="text" id="FirstField" value="Lorem"><br>
+
+  <label for="SecondField">Second field (disabled):</label>
+  <input type="text" id="SecondField" value="Ipsum" disabled="disabled"><br>
+
+  <input type="button" value="Submit">
+</form>
+ +

CSS

+ +
input:enabled {
+  color: #2b2;
+}
+
+input:disabled {
+  color: #aaa;
+}
+
+ +

Result

+ +

{{EmbedLiveSample("Example", 550, 95)}}

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#selector-enabled', ':enabled')}}{{Spec2('HTML WHATWG')}}No change.
{{SpecName('HTML5 W3C', '#selector-enabled', ':enabled')}}{{Spec2('HTML5 W3C')}}Defines the semantics for HTML and forms.
{{SpecName('CSS4 Selectors', '#enableddisabled', ':enabled')}}{{Spec2('CSS4 Selectors')}}No change.
{{SpecName('CSS3 Basic UI', '#pseudo-classes', ':enabled')}}{{Spec2('CSS3 Basic UI')}}Links to Selectors Level 3.
{{SpecName('CSS3 Selectors', '#enableddisabled', ':enabled')}}{{Spec2('CSS3 Selectors')}}Defines the pseudo-class, but not the associated semantics.
+ +

Browser compatibility

+ +
+ + +

{{Compat("css.selectors.enabled")}}

+
+ +

See also

+ + +
diff --git a/files/pt-br/web/css/_colon_first-child/index.html b/files/pt-br/web/css/_colon_first-child/index.html new file mode 100644 index 0000000000..4301b602dc --- /dev/null +++ b/files/pt-br/web/css/_colon_first-child/index.html @@ -0,0 +1,139 @@ +--- +title: ':first-child' +slug: 'Web/CSS/:first-child' +tags: + - Referencia +translation_of: 'Web/CSS/:first-child' +--- +

{{ CSSRef() }}

+ +

Sumário

+ +

A pseudo-classe de CSS :first-child representa qualquer elemento que seja o primeiro filho de seus pais.

+ +

Sintaxe

+ +
elemento:first-child { estilos }
+
+ +

Exemplos

+ +

Exemplo 1

+ +

HTML

+ +
<div>
+  <span>Este span é verde limão!</span>
+  <span>Este span não é verde limão. :(</span>
+</div>
+
+ +

CSS

+ +
span:first-child {
+    background-color: lime;
+}
+
+ +

... resultado ...

+ +

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

+ +

Exemplo 2 - Usando UL

+ +

HTML

+ +
<ul>
+  <li>Elemento de Lista 1</li>
+  <li>Elemento de Lista 2</li>
+  <li>Elemento de Lista 3</li>
+</ul>
+ +

CSS

+ +
li{
+  color:red;
+}
+li:first-child{
+  color:green;
+}
+ +

... resultado ...

+ +

{{EmbedLiveSample('Example_2_-_Using_UL',300,150)}}

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{ SpecName('CSS4 Selectors', '#first-child-pseudo', ':first-child') }}{{ Spec2('CSS4 Selectors') }}Sem mudança.
{{ SpecName('CSS3 Selectors', '#first-child-pseudo', ':first-child') }}{{ Spec2('CSS3 Selectors') }}Definição inicial.
+ +

Browsers compatíveis

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico4.0{{ CompatGeckoDesktop("1.9") }}7[1]9.54
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico1.0{{ CompatGeckoMobile("1.9.1") }}7[1]10.03.1
+
+ +

[1] Internet Explorer 7 não atualiza os estilo dos elementos quando estes são adicionados dinamicamente. No Internet Explorer 8, se um elemento é inserido dinamicamente por um evento de clique, o estilo first-child não é aplicado até que este perca o foco.

diff --git a/files/pt-br/web/css/_colon_first-of-type/index.html b/files/pt-br/web/css/_colon_first-of-type/index.html new file mode 100644 index 0000000000..9cc021360c --- /dev/null +++ b/files/pt-br/web/css/_colon_first-of-type/index.html @@ -0,0 +1,156 @@ +--- +title: ':first-of-type' +slug: 'Web/CSS/:first-of-type' +tags: + - CSS Pseudo-classe +translation_of: 'Web/CSS/:first-of-type' +--- +
{{CSSRef}}
+ +

CSS pseudo-classe :first-of-type representa o primeiro elemento de seu tipo entre os filhos de seu elemento pai.

+ +
/* Seleciona qualquer <p> que seja o primeiro elemento
+   desse tipo entre seus irmãos */
+p:first-of-type {
+  color: red;
+}
+ +
+

Nota: Originalmente definido, o elemento selecionado tinha que ter um pai. Desde o Seletores Nível 4, isso não é mais necessário.

+
+ +

Sintaxe

+ +
{{csssyntax}}
+
+ +

Exemplos

+ +

Estilizando o primeiro parágrafo

+ +

HTML

+ +
<h2>Título</h2>
+<p>Parágrafo 1</p>
+<p>Parágrafo 2</p>
+ +

CSS

+ +
p:first-of-type {
+  color: red;
+  font-style: italic;
+}
+ +

Resultado

+ +

{{EmbedLiveSample('Styling_the_first_paragraph')}}

+ +

Elementos aninhados

+ +

Este exemplo mostra como os elementos aninhados também podem ser estilizados. Note que o seletor universal (*) está implícito quando nenhum seletor simples está escrito.

+ +

HTML

+ +
<article>
+  <div>Esta `div` é a primeira!</div>
+  <div>Esta <span>`span` aninhada é a primeira</span>!</div>
+  <div>Este <em>`em` aninhado é o primeiro</em>, mas este <em>`em` aninhado é o último</em>!</div>
+  <div>Este <span>`span` aninhado pegou o estilo</span>!</div>
+  <b>Este `b` qualifica!</b>
+  <div>Esta é a `div` final.</div>
+</article>
+
+ +

CSS

+ +
article :first-of-type {
+  background-color: pink;
+}
+ +

Resultado

+ +

{{EmbedLiveSample('Nested_elements', 500)}}

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS4 Selectors', '#first-of-type-pseudo', ':first-of-type')}}{{Spec2('CSS4 Selectors')}}Os elementos correspondentes não são necessários para ter um pai.
{{SpecName('CSS3 Selectors', '#first-of-type-pseudo', ':first-of-type')}}{{Spec2('CSS3 Selectors')}}Definição inicial.
+ +

Compatibilidade de navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
RecursoChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico1.0{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.1")}}9.09.53.2
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
RecursoAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico2.1{{CompatVersionUnknown}}{{CompatGeckoMobile("1.9.1")}}9.010.03.2
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/css/_colon_focus-within/index.html b/files/pt-br/web/css/_colon_focus-within/index.html new file mode 100644 index 0000000000..6b83efb630 --- /dev/null +++ b/files/pt-br/web/css/_colon_focus-within/index.html @@ -0,0 +1,88 @@ +--- +title: ':focus-within' +slug: 'Web/CSS/:focus-within' +translation_of: 'Web/CSS/:focus-within' +--- +
{{CSSRef}}
+ +

A pseudo-classe CSS :focus-within representa um elemento que recebeu o foco ou contém um elemento que recebeu o foco. Em outras palavras, isto representa um elemento que é correspondido por si só pela pseudo-classe {{cssxref(":focus")}} ou tem um descendente que é correspondido por :focus. (Isto inclui descendentes em shadow trees.)

+ +
/* Seleciona uma <div> quando um de seus descendentes é focado */
+div:focus-within {
+  background: cyan;
+}
+ +

Este seletor é útil, pegando um exemplo comum, para destacar um todo {{htmlElement("form")}} container quando o usuário focar em um de seus campos {{htmlElement("input")}}.

+ +

Sintaxe

+ +
{{csssyntax}}
+ +

Exemplo

+ +

Neste exemplo, o formulário receberá estilos de coloração especiais quando o input de texto recebe o foco

+ +

HTML

+ +
<p>Tente digitar neste formulário.</p>
+
+<form>
+  <label for="given_name">Given Name:</label>
+  <input id="given_name" type="text">
+  <br>
+  <label for="family_name">Family Name:</label>
+  <input id="family_name" type="text">
+</form>
+ +

CSS

+ +
form {
+  border: 1px solid;
+  color: gray;
+  padding: 4px;
+}
+
+form:focus-within {
+  background: #ff8;
+  color: black;
+}
+
+input {
+  margin: 4px;
+}
+
+ +

Resultado

+ +

{{EmbedLiveSample("Exemplo", 500, 150)}}

+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName("CSS4 Selectors", "#the-focus-within-pseudo", ":focus-within")}}{{Spec2("CSS4 Selectors")}}Initial definition.
+ +

Compatibilidade entre navegadores

+ + + +

{{Compat("css.selectors.focus-within")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/css/_colon_focus/index.html b/files/pt-br/web/css/_colon_focus/index.html new file mode 100644 index 0000000000..733c8e214a --- /dev/null +++ b/files/pt-br/web/css/_colon_focus/index.html @@ -0,0 +1,124 @@ +--- +title: ':focus' +slug: 'Web/CSS/:focus' +tags: + - Acessibilidade + - CSS + - Foco + - Focus + - Pseudo classe + - Pseudo classe CSS + - Referencia + - Web +translation_of: 'Web/CSS/:focus' +--- +

{{CSSRef}}

+ +

Resumo

+ +

A pseudo-classe :focus do CSS é aplicada quando um elemento recebe foco, o que pode ocorrer quando o usuário seleciona o elemento utilizando o teclado ou ativando o mesmo com o mouse (ex: um campo de um formulário).

+ +

A pseudo classe é aplicada apenas ao elemento focado, e não aos seus elementos ascendentes, como ocorre com {{ Cssxref(":checked") }} e {{ Cssxref(":enabled") }} e diferentemente de {{ Cssxref(":active") }} ou {{ Cssxref(":hover") }}.

+ +

Sintaxe

+ +
elemento:focus { ... }
+ +

Exemplos

+ +
.nome:focus {
+  color: red;
+}
+
+.sobrenome:focus {
+  color: lime;
+}
+ +
<input class="nome" value="Esse elemento ficará vermelho quando focado">
+<input class="sobrenome" value="Esse elemento ficará verde-limão quando focado">
+ +

{{ EmbedLiveSample('Exemplos', '', '', '', 'Web/CSS/:focus') }}

+ +

Especificação

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('HTML WHATWG', 'scripting.html#selector-focus', ':focus')}}{{Spec2('HTML WHATWG')}}Define a semântica no HTML.
{{SpecName('CSS4 Selectors', '#focus-pseudo', ':focus')}}{{Spec2('CSS4 Selectors')}}Nenhuma modificação.
{{SpecName('CSS3 Selectors', '#the-user-action-pseudo-classes-hover-act', ':focus')}}{{Spec2('CSS3 Selectors')}}Nenhuma modificação.
{{SpecName('CSS2.1', 'selector.html#dynamic-pseudo-classes', ':focus')}}{{Spec2('CSS2.1')}}Definição inicial.
+ +

Compatibilidade com navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico1.0{{CompatGeckoDesktop("1")}}8.07.01.0
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FuncionalidadeAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico1.0{{CompatGeckoMobile("1")}}8.06.01.0
+
diff --git a/files/pt-br/web/css/_colon_fullscreen/index.html b/files/pt-br/web/css/_colon_fullscreen/index.html new file mode 100644 index 0000000000..7d721684ab --- /dev/null +++ b/files/pt-br/web/css/_colon_fullscreen/index.html @@ -0,0 +1,87 @@ +--- +title: ':fullscreen' +slug: 'Web/CSS/:fullscreen' +translation_of: 'Web/CSS/:fullscreen' +--- +
{{CSSRef}}
+ +

A pseudo-classe :fullscreen do CSS representa os elementos que estão atualmente no modo tela-cheia. Se vários elementos estiverem em tela-cheia, isto seleciona todos.

+ +

Sintaxe

+ +
{{csssyntax}}
+ +

Usage notes

+ +

The :fullscreen pseudo-class lets you configure your stylesheets to automatically adjust the size, style, or layout of content when elements switch back and forth between full-screen and traditional presentations.

+ +

Examples

+ +

In this example, the color of a button is changed depending on whether or not the document is in full-screen mode. This is done without needing to specifically apply style changes using JavaScript.

+ +

HTML

+ +

The page's HTML looks like this:

+ +
<h1>MDN Web Docs Demo: :fullscreen pseudo-class</h1>
+
+<p>This demo uses the <code>:fullscreen</code> pseudo-class to automatically
+  change the style of a button used to toggle full-screen mode on and off,
+  entirely using CSS.</p>
+
+<button id="fs-toggle">Toggle Fullscreen</button>
+ +

The {{HTMLElement("button")}} with the ID "fs-toggle" will change between pale red and pale green depending on whether or not the document is in full-screen mode.

+ +

CSS

+ +

The magic happens in the CSS. There are two rules here. The first establishes the background color of the "Toggle Full-screen Mode" button when the element is not in a full-screen state. The key is the use of the :not(:fullscreen), which looks for the element to not have the :fullscreen pseudo-class applied to it.

+ +
#fs-toggle:not(:fullscreen) {
+  background-color: #afa;
+}
+
+ +

When the document is in full-screen mode, the following CSS applies instead, setting the background color to a pale shade of red.

+ +
#fs-toggle:fullscreen {
+  background-color: #faa;
+}
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fullscreen', '#:fullscreen-pseudo-class', ':fullscreen')}}{{Spec2('Fullscreen')}}Initial definition.
+ +

Browser compatibility

+ +
+ + +

{{Compat("css.selectors.fullscreen")}}

+
+ +

See also

+ + diff --git a/files/pt-br/web/css/_colon_hover/index.html b/files/pt-br/web/css/_colon_hover/index.html new file mode 100644 index 0000000000..9e5dfb2b29 --- /dev/null +++ b/files/pt-br/web/css/_colon_hover/index.html @@ -0,0 +1,185 @@ +--- +title: ':hover' +slug: 'Web/CSS/:hover' +translation_of: 'Web/CSS/:hover' +--- +

{{ CSSRef() }}

+ +

Resumo

+ +

A pseudo-classe :hover corresponde quando o usuário designa um elemento com um dispositivo apontador, mas não necessariamente o ativa. Este estilo pode ser substituído por qualquer outra pseudo-classe de  link-relacionados, isto é  {{ cssxref(":link") }}, {{ cssxref(":visited") }}, e {{ cssxref(":active") }}, aparecendo em regras subsequentes. Na ordem para estilizar apropriadamente links, você precisa colocar a regra :hover depois das regras :link e :visited mas antes da regra :active, como definido pela ordem LVHA :link — :visited — :hover — :active.

+ +

A pseudo-class :hover pode ser aplicada a qualquer pseudo-elemento. {{experimental_inline}}.

+ +

User agents visuais como Firefox, Internet Explorer, Safari, Opera ou Chrome, aplicam o estilo associado quando o cursor(mouse pointer) passa sobre um elemento.

+ +
Nota de uso: em telas de toque (touch screens) :hover é impossível ou problemático. Dependendo do navegador a pseudo-classe :hover pode nunca funcionar, ou funcionar apenas por um curto momento depois de “tocar” um elemento, ou podem continuar a funcionar mesmo depois que o usuário pare de “tocar” o elemento até que o usuário toque outro elemento. Como dispositivos touchscreen são comuns, é importante para desenvolvedores web não terem conteúdos acessíveis apenas quando passamos sobre ele, uma vez que esse conteúdo é mais complicado ou impossível de acessar para usuários desses dispositivos.
+ +

Exemplos

+ +
:link:hover { outline: dotted red; }
+
+.foo:hover { background: gold; }
+
+ + + +

Com a pseudo-classe :hover você pode criar algoritmos complexos de cascata. Esta é uma técnica comumente usada, por exemplo, para criar menus dropdown com CSS puro (apenas utilizando CSS, sem usar JavaScript). A essência desta técnica é criação de uma regra como a seguinte:

+ +
div.menu-bar ul ul {
+  display: none;
+}
+
+div.menu-bar li:hover > ul {
+  display: block;
+}
+
+ +

para ser aplicada a uma estrutura HTML como a seguinte:

+ +
<div class="menu-bar">
+  <ul>
+    <li>
+      <a href="example.html">Menu</a>
+      <ul>
+        <li>
+          <a href="example.html">Link</a>
+        </li>
+        <li>
+          <a class="menu-nav" href="example.html">Submenu</a>
+          <ul>
+            <li>
+              <a class="menu-nav" href="example.html">Submenu</a>
+              <ul>
+                <li><a href="example.html">Link</a></li>
+                <li><a href="example.html">Link</a></li>
+                <li><a href="example.html">Link</a></li>
+                <li><a href="example.html">Link</a></li>
+              </ul>
+            </li>
+            <li><a href="example.html">Link</a></li>
+          </ul>
+        </li>
+      </ul>
+    </li>
+  </ul>
+</div>
+
+ +

Veja nosso exemplo de menu dropdown baseado em CSS para entender melhor.

+ +

Galeria com imagens full-size e previews

+ +

Você pode usar a pseudo-classe :hover para construir uma galeria de imagem, exibindo imagens full-size apenas quando o mouse passa sobre as imagens. Veja esse exemplo para uma possível dica.

+ +
Note: Para efeitos análogos, mas baseado na pseudo-classe :checked (aplicada para esconder radioboxes), veja esse demo, tirado desta página En/CSS/:checked.
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{ SpecName('CSS4 Selectors', '#hover', ':hover') }}{{ Spec2('CSS4 Selectors') }}Pode ser aplicado a qualquer pseudo-elemento.
{{ SpecName('CSS3 Selectors', '#the-user-action-pseudo-classes-hover-act', ':hover') }}{{ Spec2('CSS3 Selectors') }}Sem mudança significativa.
{{ SpecName('CSS2.1', 'selector.html#dynamic-pseudo-classes', ':hover') }}{{ Spec2('CSS2.1') }}definição inicial.
+ +

Compatibilidade dos navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari
para elementos <a>0.2{{ CompatGeckoDesktop(1.0) }}4.04.02.0.4 (419)
+ various bugs before
para qualquer elemento0.2{{ CompatGeckoDesktop(1.0) }}7.07.02.0.4 (419)
+ various bugs before
para pseudo-elementos{{CompatUnknown}}{{ CompatGeckoDesktop(28) }}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FuncionalidadeAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

Nos IE8-11, passar sobre um elemento e depois rolar a tela para cima/baixo sem mover o cursor deixará o elemento no estado :hover até que o cursor seja movido. Veja IE bug 926665.

+ +

No IE9 (e possivelmente versões mais antigas), se uma {{HTMLElement("table")}}  tem um pai com uma {{cssxref("width")}} não-auto e {{cssxref("overflow-x")}}: auto;, e a {{HTMLElement("table")}} tiver conteúdo suficiente para transbordar horizontalmente seu pai e existirem estilos {{cssxref(":hover")}} definidos dentro de elementos da tabela, então passar o mouse sobre esses elementos fará com que a altura da {{HTMLElement("table")}} aumente. Aqui está um exemplo do bug ao vivo. Uma solução alternativa para o bug é definir min-heigth: 0%; nos elemento pai da tabela (e a unidade em % deve ser especificada, 0 e 0px não funcionam). Para mais detalhes, veja jQuery ticket #10854.

+ +

A partir do Safari Mobile para o iOS 7.1.2, “bater levemente” em um elemento clicável faz com que o elemento entre no estado :hover, e o elemento permanecerá nesse estado até que um elemento diferente entre no estado :hover.

+ +

Veja também:

+ + diff --git a/files/pt-br/web/css/_colon_invalid/index.html b/files/pt-br/web/css/_colon_invalid/index.html new file mode 100644 index 0000000000..c14654b595 --- /dev/null +++ b/files/pt-br/web/css/_colon_invalid/index.html @@ -0,0 +1,139 @@ +--- +title: ':invalid' +slug: 'Web/CSS/:invalid' +tags: + - CSS + - Formulário + - Pseudo-class + - Validações +translation_of: 'Web/CSS/:invalid' +--- +
{{CSSRef}}
+ +

A pseudo-classe CSS :invalid representa qualquer elemento {{HTMLElement("input")}} ou {{HTMLElement("form")}} cujo conteúdo não esteja válido.

+ +
/* Seleciona todos os inputs inválidos */
+input:invalid {
+  background-color: pink;
+}
+ +

Essa pseudo-classe é útil para usuário identificar quais campos foram preenchidos incorretamente.

+ +

Sintaxe

+ +
{{csssyntax}}
+ +

Exemplo

+ +

Esse exemplo apresenta um simples formulário onde a cor verde realça um input válido e a cor vermelha realça um input inválido.

+ +

HTML

+ +
<form>
+  <label for="url_input">Adicione uma URL:</label>
+  <input type="url" id="url_input" />
+  <br />
+  <br />
+  <label for="email_input">Adicione um endereço de email:</label>
+  <input type="email" id="email_input" required/>
+</form>
+ +

CSS

+ +
input:invalid {
+  background-color: #ffdddd;
+}
+
+form:invalid {
+  border: 5px solid #ffdddd;
+}
+
+input:valid {
+  background-color: #ddffdd;
+}
+
+form:valid {
+  border: 5px solid #ddffdd;
+}
+
+input:required {
+  border-color: #800000;
+  border-width: 3px;
+}
+
+input:required:invalid {
+  border-color: #C00000;
+}
+ +

Resultado

+ +

{{EmbedLiveSample('Exemplo', 600, 120)}}

+ +

Notas

+ +

Radio buttons

+ +

Se algum radio button de um grupo possuir o atributo required, a pseudo-classe :invalid é aplicada a todos se nenhum deles for selecionado. (Radio buttons agrupados compartilham o mesmo valor pelo atributo name.)

+ +

Gecko defaults

+ +

Por padrão, Gecko não aplica o estilo para a pseudo-classe :invalid. Entretanto, pode-se aplicar um estilo (um "brilho" vermelho usando a propriedade {{Cssxref("box-shadow")}}) à pseudo-classe {{cssxref(":-moz-ui-invalid")}}, que são um conjunto que se aplicam como o :invalid.

+ +

Você pode desabilitar o "brilho" usando o CSS a seguir, ou substituir completamente para alterar a aparência dos campos inválidos: 

+ +
:invalid {
+  box-shadow: none;
+}
+
+:-moz-submit-invalid {
+  box-shadow: none;
+}
+
+:-moz-ui-invalid {
+  box-shadow: none;
+}
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('HTML WHATWG', '#selector-invalid', ':invalid')}}{{Spec2('HTML WHATWG')}}Nenhuma alteração.
{{SpecName('HTML5 W3C', '#selector-invalid', ':invalid')}}{{Spec2('HTML5 W3C')}}Define a semântica do HTML e validação de restrições.
{{SpecName('CSS4 Selectors', '#validity-pseudos', ':invalid')}}{{Spec2('CSS4 Selectors')}}Definição inicial.
+ +

Compatibilidade entre Browsers

+ +
+ + +

{{Compat("css.selectors.invalid")}}

+
+ +

Veja também

+ + diff --git a/files/pt-br/web/css/_colon_last-child/index.html b/files/pt-br/web/css/_colon_last-child/index.html new file mode 100644 index 0000000000..486e3ffb54 --- /dev/null +++ b/files/pt-br/web/css/_colon_last-child/index.html @@ -0,0 +1,121 @@ +--- +title: ':last-child' +slug: 'Web/CSS/:last-child' +tags: + - CSS + - CSS Pseudo-classe + - Layout + - Reference + - Referencia + - Web +translation_of: 'Web/CSS/:last-child' +--- +
{{ CSSRef() }}
+ +

Resumo

+ +

A CSS pseudo-classe :last-child representa qualquer elemento que é o último filho de seu elemento pai.

+ +

Sintaxe

+ +
elemento:last-child { propriedades de estilo }
+ +

Exemplo

+ +

Conteúdo HTML

+ +
<ul>
+  <li>Esse item não é afetado pelo estilo.</li>
+  <li>Esse também não.</li>
+  <li>Esse item é! :)</li>
+</ul>
+ +

Conteúdo CSS

+ +
li:last-child {
+    background-color: lime;
+}
+ +

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

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{ SpecName('CSS4 Selectors', '#last-child', ':last-child') }}{{ Spec2('CSS4 Selectors') }}Sem mudança.
{{ SpecName('CSS3 Selectors', '#last-child', ':last-child') }}{{ Spec2('CSS3 Selectors') }}Definição inicial.
+ +

Compatibilidade de navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico1.0{{ CompatGeckoDesktop("1") }}9.09.53.2
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico2.1{{ CompatGeckoMobile("1") }}9.010.03.2
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/css/_colon_last-of-type/index.html b/files/pt-br/web/css/_colon_last-of-type/index.html new file mode 100644 index 0000000000..63c35d2978 --- /dev/null +++ b/files/pt-br/web/css/_colon_last-of-type/index.html @@ -0,0 +1,126 @@ +--- +title: ':last-of-type' +slug: 'Web/CSS/:last-of-type' +translation_of: 'Web/CSS/:last-of-type' +--- +
{{CSSRef}}
+ +

Sumário

+ +

CSS pseudo-class :last-of-type representa o último irmão com o nome de elemento dado na lista de filhos de seu elemento pai.

+ +

Syntax

+ +
element:last-of-type { style properties }
+
+ +

Exemplo

+ +

Para selecionar o último elemento em dentro de um elemento {{HTMLElement("p")}}, você pode usar o seguinte:

+ +
p em:last-of-type {
+  color: lime;
+}
+
+ +
<p>
+  <em>I'm not lime :(</em>
+  <strong>I'm not lime :(</strong>
+  <em>I'm lime :D</em>
+  <strong>I'm also not lime :(</strong>
+</p>
+
+<p>
+  <em>I'm not lime :(</em>
+  <span><em>I am lime!</em></span>
+  <strong>I'm not lime :(</strong>
+  <em>I'm lime :D</em>
+  <span><em>I am also lime!</em> <strike> I'm not lime </strike></span>
+  <strong>I'm also not lime :(</strong>
+</p>
+ +

...irá resultar em:

+ +
{{EmbedLiveSample('Example','100%', '120')}}
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS4 Selectors', '#last-of-type-pseudo', ':last-of-type')}}{{Spec2('CSS4 Selectors')}}No change
{{SpecName('CSS3 Selectors', '#last-of-type-pseudo', ':last-of-type')}}{{Spec2('CSS3 Selectors')}}Initial definition
+ +

Compatibilidade de Browser

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1.0{{CompatGeckoDesktop("1.9.1")}}9.09.53.2
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support2.1{{CompatGeckoMobile("1.9.1")}}9.010.03.2
+
+ +

See also

+ + diff --git a/files/pt-br/web/css/_colon_link/index.html b/files/pt-br/web/css/_colon_link/index.html new file mode 100644 index 0000000000..19f883e908 --- /dev/null +++ b/files/pt-br/web/css/_colon_link/index.html @@ -0,0 +1,105 @@ +--- +title: ':link' +slug: 'Web/CSS/:link' +translation_of: 'Web/CSS/:link' +--- +

{{ CSSRef() }}

+ +

Resumo

+ +

pseudo-class CSS :link permite que você selecione os links dentro de um elemento. Ela seleciona todos os links, até mesmo os que não foram visitados, incluindo os links ja estilizados em outras classes ou ids com o {{ cssxref(":hover") }}, {{ cssxref(":active") }} ou {{ cssxref(":visited") }}. Para um funcionamento adequado é essencial que ela venha antes das regras: :visited:hover:active. O {{ cssxref(":focus") }} é uma pseudo-class geralmente usada antes de a:hover ou depois, dependendo do resultado esperado.

+ +

Exemplos

+ +
a:link {color: slategray;}
+.external:link {background-color: lightblue;}
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{ SpecName('CSS4 Selectors', '#link', ':link') }}{{ Spec2('CSS4 Selectors') }}Nenhuma mudança.
{{ SpecName('CSS3 Selectors', '#link', ':link') }}{{ Spec2('CSS3 Selectors') }}Nenhuma mudança.
{{ SpecName('CSS2.1', 'selector.html#link-pseudo-classes', ':link') }}{{ Spec2('CSS2.1') }}Uso estrito ao elemento {{ HTMLElement("a") }} .
{{ SpecName('CSS1', '#anchor-pseudo-classes', ':link') }}{{ Spec2('CSS1') }}Definição Inicial.
+ +

Compatibilidade do navegador

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
RecursoChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1{{ CompatGeckoDesktop("1") }}3.03.51.0
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte Basico1.5{{ CompatGeckoMobile("1.9.2") }}{{ CompatUnknown() }}{{ CompatUnknown() }}3.2
+
+ +

Veja também:

+ + diff --git a/files/pt-br/web/css/_colon_not/index.html b/files/pt-br/web/css/_colon_not/index.html new file mode 100644 index 0000000000..1cd6b3061e --- /dev/null +++ b/files/pt-br/web/css/_colon_not/index.html @@ -0,0 +1,75 @@ +--- +title: ':not()' +slug: 'Web/CSS/:not' +tags: + - CSS + - Composição + - Layout + - Pseudo-classe CSS + - Referencia + - Web +translation_of: 'Web/CSS/:not' +--- +
{{ CSSRef() }}
+ +

Resumo

+ +

A pseudo-classe CSS de negação, :not(X), é uma notação funcional que recebe um seletor simples X como argumento. Ela seleciona um elemento que não é representado por seu argumento. X não pode conter outro seletor de negação.

+ +
Observações: + + +
+ +

Sintaxe

+ +
:not(selector) { style properties }
+ +

Exemplos

+ +
p:not(.classico) { color: red; }
+body *:not(p) { color: green; }
+ +

Dado o CSS acima e o HTML abaixo...

+ +
<p>Um pouco de texto.</p>
+<p class="classico">Um pouco mais de texto.</p>
+<span>Mais um texto<span>
+
+ +

Se obtém resultados como este:

+ +

{{ EmbedLiveSample('Exemplos', '', '', '', 'Web/CSS/:not') }}

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{ SpecName('CSS4 Selectors', '#negation', ':not()') }}{{ Spec2('CSS4 Selectors') }}Extende seus argumentos para permitir seletores não-simples.
{{ SpecName('CSS3 Selectors', '#negation', ':not()') }}{{ Spec2('CSS3 Selectors') }}Definição inicial.
+ +

Compatibilidade em Navegadores

+ +

{{Compat("css.selectors.not")}}

diff --git a/files/pt-br/web/css/_colon_nth-child/index.html b/files/pt-br/web/css/_colon_nth-child/index.html new file mode 100644 index 0000000000..07c929d4c8 --- /dev/null +++ b/files/pt-br/web/css/_colon_nth-child/index.html @@ -0,0 +1,192 @@ +--- +title: ':nth-child()' +slug: 'Web/CSS/:nth-child' +tags: + - Pseudo-classe + - Referencia +translation_of: 'Web/CSS/:nth-child' +--- +
{{CSSRef}}
+ +

pseudo-classe CSS :nth-child() seleciona elementos com base em suas posições em um grupo de elementos irmãos.

+ +
/* Seleciona um a cada quatro elementos
+   de qualquer grupo de elementos irmãos,
+   começando do quarto elemento (4, 8 12, etc.). */
+:nth-child(4n) {
+  color: lime;
+}
+
+ +

Sintaxe

+ +

A pseudo-classe nth-child é usada com apenas um argumento, que representa o padrão usado para selecionar os elementos.

+ +

Valores

+ +
+
odd
+
Representa elementos cuja posição numérica em uma série de irmãos seja ímpar: 1, 3, 5, etc.
+
even
+
Representa elementos cuja posição numérica em uma série de irmãos seja par: 2, 4, 6, etc.
+
+ +

Notação funcional

+ +
+
<An+B>
+
Representa elementos cuja posição numérica em uma série de irmãos corresponda ao padrão An+B, o qual será aplicado a todo número maior ou igual a zero (ou seja, começando do zero). O índice do primeiro elemento é 1. Ambos os valores A e B devem ser {{cssxref("<integer>")}} (inteiros).
+
+ +

Sintaxe formal

+ +
{{csssyntax}}
+
+ +

Exemplos

+ +

Exemplos de seletores

+ +
+
tr:nth-child(odd) or tr:nth-child(2n+1)
+
Representa as linhas ímpares de uma tabela HTML: 1, 3, 5, etc.
+
tr:nth-child(even) or tr:nth-child(2n)
+
Representa as linhas pares de uma tabela HTML: 2, 4, 6, etc.
+
:nth-child(7)
+
Representa o sétimo elemento.
+
:nth-child(5n)
+
Representa os elementos de número 5 [=5×1], 10 [=5×2], 15 [=5×3], etc.
+
:nth-child(3n+4)
+
Representa os elementos de número 4 [=(3×0)+4], 7 [=(3×1)+4], 10 [=(3×2)+4], 13 [=(3×3)+4], etc.
+
:nth-child(-n+3)
+
Representa os primeiros três elementos. [=-0+3, -1+3, -2+3]
+
p:nth-child(n)
+
Representa todos os elementos <p> em um grupo de irmãos. Isso seleciona os mesmos elementos que um simples seletor p faria (só que com um nível maior de especificidade).
+
p:nth-child(1) or p:nth-child(0n+1)
+
Representa todo <p> que seja o primeiro de seu grupo de irmãos. Ele é idêntico ao seletor {{cssxref(":first-child")}} (e tem o mesmo nível de especificidade).
+
+ +
+
p:nth-child(n+8):nth-child(-n+15)
+
Representa do 8º até o 15º elementos <p> de um grupo de irmãos.
+
+ +

Exemplo detalhado

+ +

HTML

+ +
   <h3><code>span:nth-child(2n+1)</code>, SEM um
+<code>&lt;em&gt;</code> entre os elementos filhos.</h3>
+<p>Os filhos 1, 3, 5 e 7 são selecionados.</p>
+<div class="primeiro">
+  <span>Span 1!</span>
+  <span>Span 2</span>
+  <span>Span 3!</span>
+  <span>Span 4</span>
+  <span>Span 5!</span>
+  <span>Span 6</span>
+  <span>Span 7!</span>
+</div>
+
+<br>
+
+<h3><code>span:nth-child(2n+1)</code>, COM um
+   <code>&lt;em&gt;</code> entre os elementos filhos.</h3>
+<p>Os filhos 1, 5 e 7 são selecionados.<br>
+   O 3 está incluído na contagem por ser um filho, mas não é
+   selecionado porque ele não é um <code>&lt;span&gt;</code>.</p>
+<div class="segundo">
+  <span>Span!</span>
+  <span>Span</span>
+  <em>Este é um `em`.</em>
+  <span>Span</span>
+  <span>Span!</span>
+  <span>Span</span>
+  <span>Span!</span>
+  <span>Span</span>
+</div>
+
+<br>
+
+<h3><code>span:nth-of-type(2n+1)</code>, COM um
+   <code>&lt;em&gt;</code> entre os elementos filhos.</h3>
+<p>Os filhos 1, 4, 6 e 8 são selecionados.<br>
+   O 3 não está incluso na contagem nem é selecionado porque ele é um <code>&lt;em&gt;</code>,
+   não um <code>&lt;span&gt;</code>, e <code>nth-of-type</code> seleciona apenas os
+   filhos desse último tipo. O <code>&lt;em&gt;</code> é completamente
+   pulado e ignorado.</p>
+<div class="terceiro">
+  <span>Span!</span>
+  <span>Span</span>
+  <em>Este é um `em`.</em>
+  <span>Span!</span>
+  <span>Span</span>
+  <span>Span!</span>
+  <span>Span</span>
+  <span>Span!</span>
+</div>
+
+ +

CSS

+ +
html {
+  font-family: sans-serif;
+}
+
+span,
+div em {
+  padding: 5px;
+  border: 1px solid green;
+  display: inline-block;
+  margin-bottom: 3px;
+}
+
+.primeiro span:nth-child(2n+1),
+.segundo span:nth-child(2n+1),
+.terceiro span:nth-of-type(2n+1) {
+  background-color: lime;
+}
+ +

Resultado

+ +

{{ EmbedLiveSample('Exemplo_detalhado', '', 550, '', 'Web/CSS/:nth-child') }}

+ +

 

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('CSS4 Selectors', '#nth-child-pseudo', ':nth-child')}}{{Spec2('CSS4 Selectors')}}Adiciona a sintaxe of <selector> e especifica que os elementos correspondentes ao seletor não precisam ter um elemento pai.
{{SpecName('CSS3 Selectors', '#nth-child-pseudo', ':nth-child')}}{{Spec2('CSS3 Selectors')}}Definição inicial.
+ +

Compatibilidade de navegadores

+ +
+ + +

{{Compat("css.selectors.nth-child")}}

+
+ +

Veja também

+ + diff --git a/files/pt-br/web/css/_colon_nth-last-child/index.html b/files/pt-br/web/css/_colon_nth-last-child/index.html new file mode 100644 index 0000000000..7e2a3148ff --- /dev/null +++ b/files/pt-br/web/css/_colon_nth-last-child/index.html @@ -0,0 +1,218 @@ +--- +title: ':nth-last-child()' +slug: 'Web/CSS/:nth-last-child' +tags: + - Pseudo-classe + - Referencia +translation_of: 'Web/CSS/:nth-last-child' +--- +
{{CSSRef}}
+ +

pseudo-classe CSS :nth-last-child() seleciona um ou mais elementos com base em sua posição entre um grupo de elementos-irmãos, contando a partir do último.

+ +
/* Seleciona todo quarto elemento
+   em qualquer grupo de irmãos,
+   contando do último para o primeiro */
+:nth-last-child(4n) {
+  color: lime;
+}
+ +
+

Nota: Essa pseudo-classe é essencialmente o mesmo que usar {{Cssxref(":nth-child")}}, porém conta os itens de trás para a frente, e não do início para o final.

+
+ +

Sintaxe

+ +

A pseudo-classe nth-last-child é especificada com um único argumento, que representa o padrão para elementos correspondentes, contando do final.

+ +

Valores chave

+ +
+
odd
+
Representa elementos cuja posição numérica em uma série de irmãos é ímpar: 1, 3, 5, etc., contando do final. 
+
even
+
Representa elementos cuja posição numérica em uma série de irmãos é par: 2, 4, 6, etc., contando do final.
+
+ +

Notação funcional

+ +
+
<An+B>
+
Representa elementos cuja posição numérica em uma série de irmãos corresponde ao padrão An+B, para cada valor de n que seja um número inteiro positivo ou zero. O índice do primeiro elemento, contando do final, é 1.  Os valores A e B devem ambos ser {{cssxref("<integer>")}}s (inteiros).
+
+ +

Sintaxe formal

+ +
{{csssyntax}}
+
+ +

Exemplos

+ +

Seletores de exemplo

+ +
+
tr:nth-last-child(odd) ou tr:nth-last-child(2n+1)
+
Representa as linhas ímpares de uma tabela HTML: 1, 3, 5, etc., contando do final.
+
tr:nth-last-child(even) ou tr:nth-last-child(2n)
+
Representa as linhas pares de uma tabela HTML: 2, 4, 6, etc., contando do final.
+
:nth-last-child(7)
+
Representa o sétimo elemento, contando do final.
+
:nth-last-child(5n)
+
Representa elementos 5, 10, 15, etc., contando do final.
+
:nth-last-child(3n+4)
+
Representa elementos 4, 7, 10, 13, etc., contando do final.
+
:nth-last-child(-n+3)
+
Representa os últimos três elementos em um grupo de irmãos.
+
p:nth-last-child(n)
+
Representa cada elemento <p> em um grupo de irmãos. Isso é o mesmo que um simples seletor p.
+
p:nth-last-child(1) ou p:nth-last-child(0n+1)
+
Representa cada <p> que seja o primeiro elemento em um grupo de irmãos, contando do final. Isso é o mesmo que o seletor {{cssxref(":last-child")}}.
+
+ +

Exemplo de tabela

+ +

HTML

+ +
<table>
+  <tbody>
+    <tr>
+      <td>Primeira linha</td>
+    </tr>
+    <tr>
+      <td>Segunda linha</td>
+    </tr>
+    <tr>
+      <td>Terceira linha</td>
+    </tr>
+    <tr>
+      <td>Quarta linha</td>
+    </tr>
+    <tr>
+      <td>Quinta linha</td>
+    </tr>
+  </tbody>
+</table>
+
+ +

CSS

+ +
table {
+  border: 1px solid blue;
+}
+
+/* Seleciona os últimos três elementos */
+tr:nth-last-child(-n+3) {
+  background-color: pink;
+}
+
+ +

Resultado

+ +

{{EmbedLiveSample('Table_example', 300, 150)}}

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('CSS4 Selectors', '#nth-last-child-pseudo', ':nth-last-child')}}{{Spec2('CSS4 Selectors')}}Elementos correspondentes não precisam ter um elemento-pai.
{{SpecName('CSS3 Selectors', '#nth-last-child-pseudo', ':nth-last-child')}}{{Spec2('CSS3 Selectors')}}Definição inicial.
+ +

Compatibilidade de browser

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatChrome(4)}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.1")}}9.0{{CompatOpera(9.5)}}3.2
Não precisa de pai{{CompatChrome(57)}}{{CompatUnknown}}{{CompatGeckoDesktop("51")}}[1]{{CompatUnknown}}{{CompatOpera(44)}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeAndroid WebviewChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.9.1")}}9.0{{CompatOperaMobile(10)}}3.2
Não precisa de pai{{CompatChrome(57)}}{{CompatChrome(57)}}{{CompatUnknown}}{{CompatGeckoMobile("51")}}[1]{{CompatUnknown}}{{CompatOperaMobile(44)}}{{CompatUnknown}}
+ +

[1] Ver {{bug(1300374)}}.

+
+ +

Ver também

+ + diff --git a/files/pt-br/web/css/_colon_nth-of-type/index.html b/files/pt-br/web/css/_colon_nth-of-type/index.html new file mode 100644 index 0000000000..6471f5f33a --- /dev/null +++ b/files/pt-br/web/css/_colon_nth-of-type/index.html @@ -0,0 +1,146 @@ +--- +title: ':nth-of-type()' +slug: 'Web/CSS/:nth-of-type' +translation_of: 'Web/CSS/:nth-of-type' +--- +
{{CSSRef}}
+ +

A pseudo-classe CSS :nth-of-type() corresponde a um ou mais elementos de um dado tipo, baseado em sua posição entre um grupo de irmãos.

+ +
/* Seleciona cada quarto elemento <p>
+   entre qualquer grupo de irmãos */
+p:nth-of-type(4n) {
+  color: lime;
+}
+ +

Sintaxe

+ +

A pseudo-classe nth-of-type é especificada com um único argumento, o qual representa o padrão para a correspondência dos elementos. 

+ +

Veja {{Cssxref(":nth-child")}} para uma explicação mais detalhada de sua sintaxe.

+ +

Sintaxe formal

+ +
{{csssyntax}}
+
+ +

Exemplos

+ +

Exemplo básico

+ +

HTML

+ +
<div>
+  <div>Este elemento não é contado.</div>
+  <p>1º parágrafo.</p>
+  <p>2º parágrafo.</p>
+  <div>Este elemento não é contado.</div>
+  <p>3º parágrafo.</p>
+  <p>4º parágrafo.</p>
+</div>
+ +

CSS

+ +
/* Parágrafos ímpares */
+p:nth-of-type(2n+1) {
+  color: red;
+}
+
+/* Parágrafos pares */
+p:nth-of-type(2n) {
+  color: blue;
+}
+
+/* Primeiro parágrafo */
+p:nth-of-type(1) {
+  font-weight: bold;
+}
+
+ +

Resultado

+ +

{{EmbedLiveSample('Basic_example', 250, 200)}}

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoSitaçãoComentário
{{SpecName('CSS4 Selectors', '#nth-of-type-pseudo', ':nth-of-type')}}{{Spec2('CSS4 Selectors')}}Não é necessário que os elementos correspondentes tenham um pai.
{{SpecName('CSS3 Selectors', '#nth-of-type-pseudo', ':nth-of-type')}}{{Spec2('CSS3 Selectors')}}Definição inicial.
+ +

Compatibilidade de Browser

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1.0{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.1")}}9.09.53.1
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support2.1{{CompatVersionUnknown}}{{CompatGeckoMobile("1.9.1")}}9.09.53.1
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/css/_colon_only-child/index.html b/files/pt-br/web/css/_colon_only-child/index.html new file mode 100644 index 0000000000..827a539455 --- /dev/null +++ b/files/pt-br/web/css/_colon_only-child/index.html @@ -0,0 +1,197 @@ +--- +title: ':only-child' +slug: 'Web/CSS/:only-child' +tags: + - Pseudo-classe + - Referencia +translation_of: 'Web/CSS/:only-child' +--- +
{{CSSRef}}
+ +

pseudo-classe de CSS :only-child representa um elemento sem nenhum elemento-irmão. É o mesmo que :first-child:last-child ou :nth-child(1):nth-last-child(1), mas com uma especificidade mais baixa.

+ +
/* Seleciona cada <p>, mas apenas se for o */
+/* único filho de seu elemento-pai */
+p:only-child {
+  background-color: lime;
+}
+ +
+

Nota: Originalmente, foi definido que o elemento selecionado deveria ter um elemento-pai. A partir de Selectors Level 4, isso não é mais necessário.

+
+ +

Sintaxe

+ +
{{csssyntax}}
+
+ +

Exemplos

+ +

Exemplo básico

+ +

HTML

+ +
<main>
+  <div>
+    <i>Eu sou um filho único solitário.</i>
+  </div>
+
+  <div>
+    <i>Eu tenho irmãos.</i><br>
+    <b>Eu também!</b><br>
+    <span>Eu também tenho irmãos, <span>mas este é um filho único.</span></span>
+  </div>
+</main>
+ +

CSS

+ +
main :only-child {
+  color: red;
+}
+
+ +

Resultado

+ +

{{EmbedLiveSample('Basic_example','100%',180)}}

+ +

Exemplo de lista

+ +

HTML

+ +
<ol>
+  <li>Primeiro
+    <ul>
+      <li>Essa lista tem apenas um elemento.
+    </ul>
+  </li>
+  <li>Segundo
+    <ul>
+      <li>Essa lista tem três elementos.
+      <li>Essa lista tem três elementos.
+      <li>Essa lista tem três elementos.
+    </ul>
+  </li>
+<ol>
+
+ +

CSS

+ +
li li {
+  list-style-type: disc;
+}
+li:only-child {
+  color: red;
+  list-style-type: square;
+}
+ +

Resultado

+ +

{{EmbedLiveSample('A_list_example', '100%', 210)}}

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('CSS4 Selectors', '#only-child-pseudo', ':only-child')}}{{Spec2('CSS4 Selectors')}}Não é necessário que os elementos selecionados tenham um elemento-pai.
{{SpecName('CSS3 Selectors', '#only-child-pseudo', ':only-child')}}{{Spec2('CSS3 Selectors')}}Definição inicial.
+ +

Compatibilidade de browser

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico2{{CompatVersionUnknown}}{{CompatGeckoDesktop(1.8)}}9{{CompatOpera(9.5)}}3.1
Elemento-pai não é necessário{{CompatChrome(57)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOpera(44)}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeAndroid WebviewChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile(1.8)}}9{{CompatOperaMobile(10)}}3.1
Elemento-pai não é necessário{{CompatChrome(57)}}{{CompatChrome(57)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOperaMobile(44)}}{{CompatUnknown}}
+
+ +

Ver também

+ + diff --git a/files/pt-br/web/css/_colon_only-of-type/index.html b/files/pt-br/web/css/_colon_only-of-type/index.html new file mode 100644 index 0000000000..5a8b751f14 --- /dev/null +++ b/files/pt-br/web/css/_colon_only-of-type/index.html @@ -0,0 +1,95 @@ +--- +title: ':only-of-type' +slug: 'Web/CSS/:only-of-type' +translation_of: 'Web/CSS/:only-of-type' +--- +
{{CSSRef}}
+ +

Descrição

+ +

pseudo-classe CSS :only-of-type  representa qualquer elemento que não possui irmãos de um determinado tipo.

+ +

Sintaxe

+ +
:only-of-type { propriedades}
+
+ +

Especifcações

+ + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('CSS4 Selectors', '#only-of-type-pseudo', ':only-of-type')}}{{Spec2('CSS4 Selectors')}}Sem mudanças.
{{SpecName('CSS3 Selectors', '#only-of-type-pseudo', ':only-of-type')}}{{Spec2('CSS3 Selectors')}}Definição inicial.
+ + + +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte1.0{{CompatGeckoDesktop("1.9.1")}}9.09.53.2
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FuncionalidadeAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico2.1{{CompatGeckoMobile("1.9.1")}}9.010.03.2
+
+ +

Ver também

+ + diff --git a/files/pt-br/web/css/_colon_optional/index.html b/files/pt-br/web/css/_colon_optional/index.html new file mode 100644 index 0000000000..71f0b12968 --- /dev/null +++ b/files/pt-br/web/css/_colon_optional/index.html @@ -0,0 +1,85 @@ +--- +title: ':optional' +slug: 'Web/CSS/:optional' +translation_of: 'Web/CSS/:optional' +--- +
{{ CSSRef }}
+ +

A pseudo-classe CSS :optional representa qualquer elemento {{HTMLElement("input")}}, {{HTMLElement("select")}}, ou {{HTMLElement("textarea")}} que não contenha o atributo {{ htmlattrxref("required", "input") }}.

+ +
/* Selects qualquer <input> opcional */
+input:optional {
+  border: 1px dashed black;
+}
+ +

Esta pseudo-classe é utilizada para estilizar campos do formulário que não são requeridos para sumissão.

+ +
+

Nota: A pseudo-classe {{cssxref(":required")}} seleciona campos do fumulário requeridos.

+
+ +

Sintaxe

+ +
{{csssyntax}}
+ +

Exemplos

+ +

Veja {{cssxref(":invalid")}} como exemplo.

+ +

Referências de acessibilidade

+ +

Se um formulário contém {{htmlelement("input")}} opcionais, inputs requeridos devem ser indicados utilizando o atriuto {{ htmlattrxref("required", "input") }}. Isto garantirá que usuários que navegam com tecnologia de acessibilidade, como um leitor de tela, possam entender  quais entradas devem ter o conteúdo validado para submeter o formulário com êxito.

+ +

Entradas requeridas devem ser indicadas visualmente, utilizando um tratamento que não seja apenas a cor para passar o significado. Usualmente, textos descritivos e/ou um ícone são utilizados.

+ + + +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('HTML WHATWG', '#selector-optional', ':optional') }}{{ Spec2('HTML WHATWG') }}Sem mudança.
{{ SpecName('HTML5 W3C', '#selector-optional', ':optional') }}{{ Spec2('HTML5 W3C') }}Define a semântica da validação e da restrição do HTML.
{{ SpecName('CSS4 Selectors', '#opt-pseudos', ':optional') }}{{ Spec2('CSS4 Selectors') }}Sem mudança.
{{ SpecName('CSS3 Basic UI', '#pseudo-required-value', ':optional') }}{{ Spec2('CSS3 Basic UI') }}Define a pseudo-classe, mas não a semântica associada.
+ +

Compatibilidade de navegadores

+ + + +

{{Compat("css.selectors.optional")}}

+ +

Ver também

+ + diff --git a/files/pt-br/web/css/_colon_out-of-range/index.html b/files/pt-br/web/css/_colon_out-of-range/index.html new file mode 100644 index 0000000000..56ab889b6e --- /dev/null +++ b/files/pt-br/web/css/_colon_out-of-range/index.html @@ -0,0 +1,111 @@ +--- +title: ':out-of-range' +slug: 'Web/CSS/:out-of-range' +translation_of: 'Web/CSS/:out-of-range' +--- +
{{CSSRef}}
+ +

A pseudo classe de CSS :out-of-range representa um elemento de {{htmlelement("entrada")}} cujo valor atual esta fora dos limites especificados pelo {{htmlattrxref("min", "entrada")}} e {{htmlattrxref("max","entrada")}} atributos

+ +
/* Selecione qualquer <entrada>, mas somente quando estiver dentros dos
+ limites especificados, e quando este valor estiver fora deste limite */
+input:out-of-range {
+  background-color: rgba(255, 0, 0, 0.25);
+}
+ +

Essa pseudo classe é muito útil por dar ao usuario uma indicacão visual de que o valor atual esta fora dos limites permitidos

+ +
Nota: Esta pseudo classe se aplica somente a elementos que tem (ou podem ter) uma limitacao. Na falta dessa de algo como essa limitacao, o elemento nao tera como ficar "in-range"(dentro dos limites) ou "out-of-range" (fora dos limites).
+ +

Sintaxe

+ +
{{csssyntax}}
+ +

Exemplo

+ +
+

HTML

+ +
<form action="" id="form1">
+ <p>Valores entre 1 e 10 são validos.</p>
+  <ul>
+    <li>
+      <input id="value1" name="value1" type="number" placeholder="1 to 10" min="1" max="10" value="12">
+      <label for="value1">Seu valor está </label>
+    </li>
+  </ul>
+</form>
+ +

CSS

+ +
li {
+  list-style: none;
+  margin-bottom: 1em;
+}
+
+input {
+  border: 1px solid black;
+}
+
+input:in-range {
+  background-color: rgba(0, 255, 0, 0.25);
+}
+
+input:out-of-range {
+  background-color: rgba(255, 0, 0, 0.25);
+  border: 2px solid red;
+}
+
+input:in-range + label::after {
+  content: 'dentro dos limites.';
+}
+
+input:out-of-range + label::after {
+  content: 'Fora dos limites!';
+}
+ +

Resultado

+
+ +
{{EmbedLiveSample('Example', 600, 140)}}
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'scripting.html#selector-out-of-range', ':out-of-range')}}{{Spec2('HTML WHATWG')}}Define quando :out-of-range se iguala aos elementos em HTML.
{{SpecName('CSS4 Selectors', '#out-of-range-pseudo', ':out-of-range')}}{{Spec2('CSS4 Selectors')}}Definicao inicial.
+ +

Browser compatibility

+ +
+
+ + +

{{Compat("css.selectors.out-of-range")}}

+
+
+ +

See also

+ + diff --git a/files/pt-br/web/css/_colon_read-write/index.html b/files/pt-br/web/css/_colon_read-write/index.html new file mode 100644 index 0000000000..8757d4adfc --- /dev/null +++ b/files/pt-br/web/css/_colon_read-write/index.html @@ -0,0 +1,113 @@ +--- +title: ':read-write' +slug: 'Web/CSS/:read-write' +translation_of: 'Web/CSS/:read-write' +--- +
{{CSSRef}}
+ +

pseudo-classe CSS :read-write representa um elemento (como o input ou textarea) que é editável pelo usuário.

+ +
input:read-write, textarea:read-write {
+  background-color: #bbf;
+}
+
+p:read-write {
+  background-color: #bbf;
+}
+
+ +

Sintaxe

+ +
{{csssyntax}}
+ +

Examplos

+ +

Confirmando informações do formulário em controles read-only/read-write.

+ +

Ao utilizar os controles de formulário readonly permite que o usuário verifique e verifique as informações que eles podem ter inserido em um formulário anterior (por exemplo: Detalhes de envio), enquanto ainda pode enviar as informações junto com o resto do formulário. Nós fazemos exatamente isso no exemplo abaixo.

+ +

A pseudo-classe :read-only (:somente-leitura) é usada para remover todo o estilo que faz com que as entradas pareçam campos clicáveis, fazendo com que pareçam outro parágrafo somente-leitura. A pseudo-classe :read-write (:leitura-escrita) por outro lado, é usado para fornecer um estilo mais agradável para a <textarea>.

+ +
input:-moz-read-only, textarea:-moz-read-only,
+input:read-only, textarea:read-only {
+  border: 0;
+  box-shadow: none;
+  background-color: white;
+}
+
+textarea:-moz-read-write,
+textarea:read-write {
+  box-shadow: inset 1px 1px 3px #ccc;
+  border-radius: 5px;
+}
+ +

Você pode encontrar o código fonte completo em readonly-confirmation.html (disponível em inglês); isso torna assim:

+ +

{{EmbedGHLiveSample("learning-area/html/forms/pseudo-classes/readonly-confirmation.html", '100%', 660)}}

+ +

Estilizar controle não formal de read-write.

+ +

Este seletor não seleciona apenas {{htmlElement("input")}}/{{htmlElement("textarea")}}  elementos - ele selecionará qualquer elemento que possa ser editado pelo usuário, como um {{htmlelement("p")}} elemento com {{htmlattrxref("contenteditable")}} definido sobre ele.

+ +
<p contenteditable>Este parágrafo é editável; é read-write.</p>
+
+<p>Este parágrafo não é editável; é read-only.</p>
+ +
p {
+  font-size: 150%;
+  padding: 5px;
+  border-radius: 5px;
+}
+
+p:read-only {
+  background-color: red;
+  color: white;
+}
+
+p:read-write {
+  background-color: lime;
+}
+ +

{{EmbedLiveSample('Estilizar_controle_não_formal_de_read-write.', '100%', 400)}}

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{ SpecName('HTML WHATWG', '#selector-read-write', ':read-write') }}{{ Spec2('HTML WHATWG') }}Nenhuma mudança.
{{ SpecName('HTML5 W3C', '#selector-read-write', ':read-write') }}{{ Spec2('HTML5 W3C') }}Define a semântica em relação à validação de HTML e restrição.
{{ SpecName('CSS4 Selectors', '#rw-pseudos', ':read-write') }}{{ Spec2('CSS4 Selectors') }}Define a pseudo-classe, mas não a semântica associada.
+ +

Compatibilidade do navegador

+ + + +

{{Compat("css.selectors.read-write")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/css/_colon_required/index.html b/files/pt-br/web/css/_colon_required/index.html new file mode 100644 index 0000000000..edfed65e81 --- /dev/null +++ b/files/pt-br/web/css/_colon_required/index.html @@ -0,0 +1,85 @@ +--- +title: ':required' +slug: 'Web/CSS/:required' +translation_of: 'Web/CSS/:required' +--- +
{{ CSSRef }}
+ +

A pseudo-classe CSS :required representa qualquer {{HTMLElement("input")}}, {{HTMLElement("select")}}, ou {{HTMLElement("textarea")}} contendo o atributo {{ htmlattrxref("required", "input") }}.

+ +
/* Seleciona qualquer <input> requerido */
+input:required {
+  border: 1px dashed red;
+}
+ +

Esta pseudo-classe é utilizada para destacar campos que devem ter dados válidos antes do formulário ser submetido.

+ +
+

Nota: A pseudo-classe {{cssxref(":optional")}} seleciona campos do formulário que são opcionais.

+
+ +

Sintaxe

+ +
{{csssyntax}}
+ +

Exemplos

+ +

Veja {{cssxref(":invalid")}} como exemplo.

+ +

Preocupações com acessibilidade

+ +

Elementos {{htmlelement("input")}} obrigatórios devem ter o  atributo {{ htmlattrxref("required", "input") }} atribuídos. Isso garante que pessoas que navegam com auxílio de recursos de acessibilidade, como o leitor de tela, possam entender quais campos precisam ter conteúdos válidos para garantir a submissão dos dados .

+ +

Se o formulário também possui campos opcionais, entradas requeridas devem ser indicadas visualmente usando um tratamento que não seja apenas a cor para passar o significado. Usualmente, textos descritivos e/ou um ícone são utilizados.

+ + + +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{ SpecName('HTML WHATWG', '#selector-required', ':required') }}{{ Spec2('HTML WHATWG') }}Sem mudança.
{{ SpecName('HTML5 W3C', '#selector-required', ':required') }}{{ Spec2('HTML5 W3C') }}Define a semântica de validação e de restrição HTML.
{{ SpecName('CSS4 Selectors', '#opt-pseudos', ':required') }}{{ Spec2('CSS4 Selectors') }}Sem mudança.
{{ SpecName('CSS3 Basic UI', '#pseudo-required-value', ':required') }}{{ Spec2('CSS3 Basic UI') }}Define a pseudo-classe, mas não a semântica associada.
+ +

Compatibilidade de navegadores

+ + + +

{{Compat("css.selectors.required")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/css/_colon_root/index.html b/files/pt-br/web/css/_colon_root/index.html new file mode 100644 index 0000000000..066e54a1f9 --- /dev/null +++ b/files/pt-br/web/css/_colon_root/index.html @@ -0,0 +1,98 @@ +--- +title: ':root' +slug: 'Web/CSS/:root' +translation_of: 'Web/CSS/:root' +--- +
{{CSSRef}}
+ +

Sumário

+ +

A pseudo-classe CSS  :root se equipara à raíz de uma árvore, que por sua vez representa o documento. Aplicado ao HTML, :root representa o elemento {{HTMLElement("html")}}  e é identico ao seletor html, exceto que sua especificidade é mais alta.

+ +

Sintaxe

+ +
{{csssyntax}}
+ +

Exemplo

+ +

Usar :root pode ser útil para declarar uma variável CSS global:

+ +
:root {
+  --main-color: hotpink;
+  --pane-padding: 5px 42px;
+}
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('CSS4 Selectors', '#root-pseudo', ':root')}}{{Spec2('CSS4 Selectors')}}Sem mudança
{{SpecName('CSS3 Selectors', '#root-pseudo', ':root')}}{{Spec2('CSS3 Selectors')}}Definição inicial
+ +

Compatibilidade dos Navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1{{CompatGeckoDesktop("1.7")}}99.51.0
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
diff --git a/files/pt-br/web/css/_colon_target/index.html b/files/pt-br/web/css/_colon_target/index.html new file mode 100644 index 0000000000..d96be5ed63 --- /dev/null +++ b/files/pt-br/web/css/_colon_target/index.html @@ -0,0 +1,208 @@ +--- +title: ':target' +slug: 'Web/CSS/:target' +translation_of: 'Web/CSS/:target' +--- +
{{CSSRef}}
+ +

A pseudo-classe CSS :target representa um único elemento (o elemento alvo) com uma {{htmlattrxref("id")}} correspondente ao fragmento da URL.

+ +
/* Seleciona um elemento com a ID correspondente ao fragmento da URL */
+:target {
+  border: 2px solid black;
+}
+ +

Por exemplo, a seguinte URL tem um fragmento (denotado pelo sinal de #) que aponta para o elemento chamado section2:

+ +
http://www.example.com/index.html#section2
+ +

O seguinte elemento será selecionado pelo seletor :target quando a URL for igual acima:

+ +
<section id="section2">Exemplo</section>
+ +

Sintaxe

+ +
{{csssyntax}}
+ +

Exemplos

+ +

Índice

+ +

A pseudo-classe :target pode ser usada para destacar uma parte da página que foi vinculada a partir de um índice.

+ +

HTML

+ +
<h3>Índice</h3>
+<ol>
+ <li><a href="#p1">Ir para o primeiro parágrafo!</a></li>
+ <li><a href="#p2">Ir para o segundo parágrafo!</a></li>
+ <li><a href="#vazio">Esse link não vai pra lugar nenhum,
+   pois, o alvo não existe</a></li>
+</ol>
+
+<h3>Meu artigo divertido</h3>
+<p id="p1">Você pode definir <i>este parágrafo</i> como alvo
+   usando um fragmento de URL. Clique no link acima para experimentar!</p>
+<p id="p2">Esse é <i>outro parágrafo</i>, também acessável
+   pelos links acima. Não é incrível?</p>
+
+ +

CSS

+ +
p:target {
+  background-color: gold;
+}
+
+/* Adicione o pseudo-elemento dentro do elemento alvo */
+p:target::before {
+  font: 70% sans-serif;
+  content: "►";
+  color: limegreen;
+  margin-right: .25em;
+}
+
+/* Estilize nos elementos em itálico dentro do elemento alvo  */
+p:target i {
+  color: red;
+}
+ +

Resultado

+ +
{{EmbedLiveSample('A_table_of_contents', 500, 300)}}
+ + + +

Você pode usar a pseudo-classe :target para criar uma lightbox sem usar JavaScript. Essa técnica requer que os links apontem para os elementos que inicialmente estavam escondidas na página. Uma vez designado, o CSS muda o display então, assim o conteúdo pode ser mostrado.

+ +
Nota: Uma lightbox com CSS puro mais completo usando a pseudo-classe :target está disponível no GitHub (demo).
+ +

HTML

+ +
<ul>
+  <li><a href="#example1">Abrir exemplo #1</a></li>
+  <li><a href="#example2">Abrir exemplo #2</a></li>
+</ul>
+
+<div class="lightbox" id="example1">
+  <figure>
+    <a href="#" class="close"></a>
+    <figcaption>Lorem ipsum dolor sit amet, consectetur adipiscing elit.
+      Donec felis enim, placerat id eleifend eu, semper vel sem.</figcaption>
+  </figure>
+</div>
+
+<div class="lightbox" id="example2">
+  <figure>
+    <a href="#" class="close"></a>
+    <figcaption>Cras risus odio, pharetra nec ultricies et,
+      mollis ac augue. Nunc et diam quis sapien dignissim auctor.
+      Quisque quis neque arcu, nec gravida magna.</figcaption>
+  </figure>
+</div>
+ +

CSS

+ +
/* Lightbox fechado */
+.lightbox {
+  display: none;
+}
+
+/* Lightbox aberto */
+.lightbox:target {
+  position: absolute;
+  left: 0;
+  top: 0;
+  width: 100%;
+  height: 100%;
+  display: flex;
+  align-items: center;
+  justify-content: center;
+}
+
+/* Conteúdo da lightbox */
+.lightbox figcaption {
+  width: 25rem;
+  position: relative;
+  padding: 1.5em;
+  background-color: lightpink;
+}
+
+/* Botão fechar */
+.lightbox .close {
+  position: relative;
+  display: block;
+}
+
+.lightbox .close::after {
+  right: -1rem;
+  top: -1rem;
+  width: 2rem;
+  height: 2rem;
+  position: absolute;
+  display: flex;
+  z-index: 1;
+  align-items: center;
+  justify-content: center;
+  background-color: black;
+  border-radius: 50%;
+  color: white;
+  content: "×";
+  cursor: pointer;
+}
+
+/* Lightbox overlay */
+.lightbox .close::before {
+  left: 0;
+  top: 0;
+  width: 100%;
+  height: 100%;
+  position: fixed;
+  background-color: rgba(0,0,0,.7);
+  content: "";
+  cursor: default;
+}
+ +

Resultado

+ +
{{EmbedLiveSample('Pure-CSS_lightbox', 500, 220)}}
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçõesStatusComentário
{{SpecName("HTML WHATWG", "browsers.html#selector-target", ":target")}}{{Spec2("HTML WHATWG")}}Define semântica específica do HTML.
{{SpecName("CSS4 Selectors", "#the-target-pseudo", ":target")}}{{Spec2("CSS4 Selectors")}}Não há mudanças.
{{SpecName("CSS3 Selectors", "#target-pseudo", ":target")}}{{Spec2("CSS3 Selectors")}}Definição inicial.
+ + + + + +
{{Compat("css.selectors.target")}}
+ +

Veja também

+ + diff --git a/files/pt-br/web/css/_colon_valid/index.html b/files/pt-br/web/css/_colon_valid/index.html new file mode 100644 index 0000000000..7512829170 --- /dev/null +++ b/files/pt-br/web/css/_colon_valid/index.html @@ -0,0 +1,74 @@ +--- +title: ':valid' +slug: 'Web/CSS/:valid' +tags: + - CSS + - Layout + - Pseudo-classes + - Referencia + - Validação + - Web +translation_of: 'Web/CSS/:valid' +--- +
{{CSSRef}}
+ +

A pseudo-classe CSS :valid representa qualquer {{HTMLElement("input")}} ou outro elemento do {{HTMLElement("form")}} cujo conteúdo foi validado com sucesso. Isso permite, facilmente, adicionar uma aparência que ajude o usuário a identificar os campos validados.

+ +
/* Seleciona qualquer input válido */
+input:valid {
+  background-color: powderblue;
+}
+ +

Essa pseudo-classe é útil para realçar os campos válidos para o usuário.

+ +

Sintaxe

+ +
{{csssyntax}}
+ +

Exemplos

+ +

Veja {{cssxref(":invalid")}} para um exemplo.

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#selector-valid', ':valid')}}{{Spec2('HTML WHATWG')}}Sem alterações.
{{SpecName('HTML5 W3C', '#selector-valid', ':valid')}}{{Spec2('HTML5 W3C')}}Define a semântica do HTML e a validação de restrições.
{{SpecName('CSS4 Selectors', '#validity-pseudos', ':valid')}}{{Spec2('CSS4 Selectors')}}Definição inicial
+ +

Compatibilidade entre Browsers

+ +
+ + +

{{Compat("css.selectors.valid")}}

+
+ +

Veja também

+ + diff --git a/files/pt-br/web/css/_colon_visited/index.html b/files/pt-br/web/css/_colon_visited/index.html new file mode 100644 index 0000000000..501db9fcf6 --- /dev/null +++ b/files/pt-br/web/css/_colon_visited/index.html @@ -0,0 +1,154 @@ +--- +title: ':visited' +slug: 'Web/CSS/:visited' +tags: + - CSS + - Layout + - Pseudo-classes + - Web +translation_of: 'Web/CSS/:visited' +--- +
{{ CSSRef }}
+ +

:visited é uma Pseudo-classe do CSS para indicar se o link em questão já foi visitado pelo usuário. Por questões de privacidade, os styles que podem ser modificados usando este seletor são muito limitados.

+ +
/* Seleciona qualquer <a> que poderá ser visitado */
+a:visited {
+  color: green;
+}
+ +

Styles definidos pela pseudo-classe :visited vão ser substituidos por qualquer pseudo-classe relacionada ao link subsequente ({{cssxref(":link")}}, {{cssxref(":hover")}}, ou {{cssxref(":active")}}) que tenha ao menos uma especificação igual. Para estilizar links apropriadamente, garantindo assim seu funcionamento adequado, ponha a regra :visited depois da regra :link mas antes das regras :hover e :active , Pode-se definir pela ordem LVHA: :link:visited:hover:active.

+ +

Restrições de Estilo

+ +

Por razões de privacidade, navegadores limitam estritamente quais estilos você pode aplicar usando esta pseudo-class, como elas podem ser usadas:

+ + + +
+

Nota: Para mais informações quanto a essas limitações e as razões por trás delas, veja Privacy and the :visited selector. Obs: No momento estará apenas disponível em inglês.

+
+ +

Syntaxe

+ +
<!DOCTYPE html>
+<html>
+<head>
+    <title>Exemplo de uso do seletor :visited</title>
+    <style type="text/css">
+        a {
+            background-color: white;
+            border: 1px solid white; }
+        a:visited {
+            background-color: lightblue;
+            border-color: cyan;
+            color: darkblue; }
+    </style>
+</head>
+<body>
+    <a href="">Você já visitou este link?</a><br>
+    <a href="">Você já visitou este link.</a>
+</body>
+</html>
+ +

Exemplo

+ +

Propriedades que de alguma forma não tenha cor ("color") definida, ou seja transparente, não podem ser modificadas como o :visited. Das  propriedades que podem ser definidas por essa pseudo-classe, seu navegador provavelmente terá por padão valores para color e column-rule-color somente. Portanto, se você quiser modificar outras propriedades, você necessitará pré-definir os valores fora do seletor :visited.

+ +

HTML

+ +
<a href="#">Você já visitou este link?</a>
+<br>
+<a href="">Você já visitou este link.</a>
+ +

CSS

+ +
a {
+  /* Specifica non-transparent por padrão para algumas
+     propriedades, permitindo-os a serem estilizados pelo
+     estado :visited */
+  background-color: white;
+  border: 1px solid white;
+}
+
+a:visited {
+  background-color: yellow;
+  border-color: hotpink;
+  color: hotpink;
+}
+
+ +

Resultado

+ +
{{EmbedLiveSample("Exemplo")}}
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçõesStatusComentário
{{ SpecName('HTML WHATWG', 'scripting.html#selector-visited', ':visited') }}{{ Spec2('HTML WHATWG') }} 
{{ SpecName('CSS4 Selectors', '#link', ':visited') }}{{ Spec2('CSS4 Selectors') }}Sem mudança.
{{ SpecName('CSS3 Selectors', '#link', ':visited') }}{{ Spec2('CSS3 Selectors') }}Sem mudança.
{{ SpecName('CSS2.1', 'selector.html#link-pseudo-classes', ':visited') }}{{ Spec2('CSS2.1') }}Eleva a restrição para aplicar apenas :visited ao elemento {{HTMLElement ("a")}}. Permite que os navegadores restrinjam seu comportamento por motivos de privacidade.
{{ SpecName('CSS1', '#anchor-pseudo-classes', ':visited') }}{{ Spec2('CSS1') }}Definição inicial.
+ +

Compatibilidade com Navegadores

+ + + + + +

{{Compat("css.selectors.visited")}}

+ +

Veja também (inglês)

+ + diff --git a/files/pt-br/web/css/_doublecolon_-ms-tooltip/index.html b/files/pt-br/web/css/_doublecolon_-ms-tooltip/index.html new file mode 100644 index 0000000000..e9e3496a20 --- /dev/null +++ b/files/pt-br/web/css/_doublecolon_-ms-tooltip/index.html @@ -0,0 +1,23 @@ +--- +title: '::-ms-tooltip' +slug: 'Web/CSS/::-ms-tooltip' +translation_of: 'Archive/Web/CSS/::-ms-tooltip' +--- +
{{CSSRef}}{{Non-standard_header}}
+ +

The ::-ms-tooltip CSS pseudo-element is a Microsoft extension that applies one or more styles to the tooltip of a slider <input type="range">.

+ +

Syntax

+ +
::-ms-tooltip {...}
+
+ +

Propriedades

+ +

The only CSS properties that can be used on ::-ms-tooltip are display and visibility, for hiding the pseudo-element.

+ +

Veja também

+ + diff --git a/files/pt-br/web/css/_doublecolon_after/index.html b/files/pt-br/web/css/_doublecolon_after/index.html new file mode 100644 index 0000000000..3281ed4793 --- /dev/null +++ b/files/pt-br/web/css/_doublecolon_after/index.html @@ -0,0 +1,241 @@ +--- +title: '::after (:after)' +slug: 'Web/CSS/::after' +translation_of: 'Web/CSS/::after' +--- +
{{CSSRef}}
+ +

Em CSS, ::after cria um pseudo-elemento que é o último filho do elemento selecionado. Muitas vezes é usado para adicionar e melhorar o conteúdo de um elemento como a propriedade {{cssxref("content")}}. É inline por padrão.

+ +
/* Adiciona uma seta após os links */
+a::after {
+  content: "";
+}
+ +

Sintaxe

+ +
{{csssyntax}}
+ +
+

O CSS3 introduziu a notação ::after (com dois sinais de dois pontos) para distinguir pseudo-classes dos pseudo-elementos. Os navegadores também aceitam :after, introduzido no CSS2.

+
+ +

Exemplos

+ +

Uso simples

+ +

Vamos criar duas classes: uma para parágrafos tediosos e uma para parágrafos excitantes. Podemos então marcar cada parágrafo adicionando um pseudo-elemento ao final dele.

+ +
<p class="boring-text">Here is some plain old boring text.</p>
+<p>Here is some normal text that is neither boring nor exciting.</p>
+<p class="exciting-text">Contributing to MDN is easy and fun.
+Just hit the edit button to add new live samples, or improve existing samples.</p>
+ +
.exciting-text::after {
+  content: "<- now this *is* exciting!";
+  color: green;
+}
+
+.boring-text::after {
+   content: "<- BORING!";
+   color: red;
+}
+ +

Visualização

+ +

{{EmbedLiveSample('Uso_simples', 500, 150)}}

+ +

Exemplos decorativos

+ +

Podemos estilizar textos ou imagens na propriedade {{cssxref("content")}} praticamente de qualquer forma que quisermos.

+ +
<span class="ribbon">Observe onde a caixa de laranja está.</span>
+ +
.ribbon {
+  background-color: #5BC8F7;
+}
+
+.ribbon::after {
+  content: "Observe esta caixa laranja";
+  background-color: #FFBA10;
+  border-color: black;
+  border-style: dotted;
+}
+ +

Visualização

+ +

{{EmbedLiveSample('Exemplos_decorativos', 450, 20)}}

+ +

Dicas

+ +

O exemplo a seguir mostra o uso do ::after pseudo-elemento em conjunto com a expressão CSS attr() e um tributo data personalizado data-descr para criar uma dica em forma de glossário feito em CSS puro. Verifique a visualização abaixo, ou veja este exemplo em página separada.

+ +
<p>Aqui está o exemplo ao vivo do código acima.<br />
+  Temos um pouco de <span data-descr="collection of words and punctuation">texto</span> aqui com algumas
+  <span data-descr="small popups which also hide again">dicas</span>.<br />
+  Não seja tímido, passe o mouse por cima para dar uma <span data-descr="not to be taken literally">olhada</span>.
+</p>
+
+ +
span[data-descr] {
+  position: relative;
+  text-decoration: underline;
+  color: #00F;
+  cursor: help;
+}
+
+span[data-descr]:hover::after {
+  content: attr(data-descr);
+  position: absolute;
+  left: 0;
+  top: 24px;
+  min-width: 200px;
+  border: 1px #aaaaaa solid;
+  border-radius: 10px;
+  background-color: #ffffcc;
+  padding: 12px;
+  color: #000000;
+  font-size: 14px;
+  z-index: 1;
+}
+ +

Visualização

+ +

{{EmbedLiveSample('Dicas', 450, 120)}}

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('CSS4 Pseudo-Elements', '#selectordef-after', '::after')}}{{Spec2('CSS4 Pseudo-Elements')}}Sem mudanças significativas em relação à especificação anterior.
{{Specname("CSS3 Transitions", "#animatable-properties", "transitions on pseudo-element properties")}}{{Spec2("CSS3 Transitions")}}Permite transições em propriedades definidas em pseudo-elementos.
{{Specname("CSS3 Animations", "", "animations on pseudo-element properties")}}{{Spec2("CSS3 Animations")}}Permite animações em propriedades definidas em pseudo-elementos.
{{SpecName('CSS3 Selectors', '#gen-content', '::after')}}{{Spec2('CSS3 Selectors')}}Introduz a sintaxe de dois sinais de dois pontos.
{{SpecName('CSS2.1', 'generate.html#before-after-content', '::after')}}{{Spec2('CSS2.1')}}Definição inicial, usando a sintaxe de um sinal de dois pontos.
+ +

Compatibilidade entre navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
RecursoChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte ao :after{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.0")}}[1]8.0{{CompatOpera("4")}}4.0
Suporte ao ::after{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.8")}}[1]9.0{{CompatOpera("7")}}4.0
Suporte à animações e transições26{{CompatVersionUnknown}}{{CompatGeckoDesktop("2.0")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
RecursoAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte ao :after{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Suporte ao ::after{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Suporte à animações e transições{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("4.0")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] O Firefox anterior à versão 3.5 implementou apenas a versão CSS 2.0 de :after. Não foram permitidos {{cssxref("position")}}, {{cssxref("float")}}, list-style-* e algumas propriedades exibição. O Firefox 3.5 removeu estas restrições.

+ +

Veja também

+ + diff --git a/files/pt-br/web/css/_doublecolon_backdrop/index.html b/files/pt-br/web/css/_doublecolon_backdrop/index.html new file mode 100644 index 0000000000..f08d879c46 --- /dev/null +++ b/files/pt-br/web/css/_doublecolon_backdrop/index.html @@ -0,0 +1,131 @@ +--- +title: '::backdrop' +slug: 'Web/CSS/::backdrop' +tags: + - CSS + - Layout + - Pano de fundo + - Pseudo-elemento + - Referencia + - Web +translation_of: 'Web/CSS/::backdrop' +--- +
{{CSSRef}} {{SeeCompatTable}}
+ +

Cada elemento na camada superior de uma pilha de elementos possui um {{Cssxref("pseudo-elementos", "pseudo-elemento")}} ::backdrop. Esse pseudo-elemento é uma caixa renderizada imediatamente abaixo do elemento superior (e acima do elemento logo abaixo desse elemento, caso exista algum), dentro da camada superior.

+ +

O pseudo-elemento ::backdrop pode ser utilizado para criar um pano de fundo que esconde o conteúdo por trás de um elemento posicionado no topo de uma pilha de elementos. Por exemplo, para o elemento que é mostrado em tela cheia conforme descrito nessa especificação.

+ +

Ele não herda de nenhum elemento e também não é herdado. Não há restrição de propriedades que podem ser aplicadas a esse pseudo-elemento. 

+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('Fullscreen', '#::backdrop-pseudo-element', '::backdrop')}}{{Spec2('Fullscreen')}}Definição inicial
+ +

Copatibilidade com navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico32.0 {{property_prefix("webkit")}}
+ 37.0
{{CompatGeckoDesktop("47")}} [1]11 {{property_prefix("ms")}}{{CompatNo}}{{CompatNo}}
em um <dialog>32.0 {{property_prefix("webkit")}}
+ 37.0
{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
em tela cheia{{CompatNo}}{{CompatGeckoDesktop("47")}} [1]11 {{property_prefix("ms")}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatNo}}{{CompatGeckoMobile("47")}} [1]{{CompatNo}}{{CompatNo}}{{CompatNo}}
em um <dialog>{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
em tela cheia{{CompatNo}}{{CompatGeckoMobile("47")}} [1]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] Ver {{bug(1064843)}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/css/_doublecolon_before/index.html b/files/pt-br/web/css/_doublecolon_before/index.html new file mode 100644 index 0000000000..431c59a80e --- /dev/null +++ b/files/pt-br/web/css/_doublecolon_before/index.html @@ -0,0 +1,299 @@ +--- +title: '::before (:before)' +slug: 'Web/CSS/::before' +translation_of: 'Web/CSS/::before' +--- +
{{CSSRef}}
+ +

Sumário

+ +

::before cria um pseudo-elemento que é o primeiro filho do elemento atingido. É frequentemente utilizado para adicionar conteúdo decorativo à um element utilizando a propriedade {{cssxref("content")}}. Este elemento é inline por padrão.

+ +

Sintaxe

+ +
{{csssyntax}}
+ +

A notação ::before (com dois dois-pontos) foi introduzida no CSS3 afim de diferenciar pseudo-classes de pseudo-elementos. Navegadores também aceitam a notação :before introduzida no CSS 2.

+ +

Exemplos

+ +

Adicionando aspas

+ +

Um exemplo simples do uso de pseudo-elementos ::before pseudo-elementos é a exibição de aspas. Aqui usamos ::before e {{Cssxref("::after")}} para inserir caracteres de aspas.

+ +

Conteúdo HTML

+ +
<q>Algumas citações</q>, ele disse, <q>são melhor do que nenhuma.</q>
+ +

Conteúdo CSS

+ +
q::before {
+  content: "«";
+  color: blue;
+}
+q::after {
+  content: "»";
+  color: red;
+}
+ +

Saída

+ +

{{EmbedLiveSample('Adding_quotation_marks', '500', '50', '')}}

+ +

Exemplo decorativo

+ +

Podemos estilizar textos e imagens na propriedade {{cssxref("content")}} praticamente da forma que desejarmos.

+ +

Conteúdo HTML

+ +
<span class="ribbon">Observe onde a caixa laranja está.</span>
+ +

Conteúdo CSS

+ +
.ribbon {
+  background-color: #5BC8F7;
+}
+
+.ribbon::before {
+  content: "Olhe para esta caixa laranja.";
+  background-color: #FFBA10;
+  border-color: black;
+  border-style: dotted;
+}
+ +

Saída

+ +

{{EmbedLiveSample('Decorative_example', 450, 60)}}

+ +

Lista To-do

+ +

Neste exemplo vamos criar uma simples lista de tarefas, usando pseudo-elementos. Este método pode frequentemente ser utilizado para dar pequenos toques à UI (User Interface) e melhorar a experiência do usuário.

+ +

Conteúdo HTML

+ +
<ul>
+  <li>Comprar Leite</li>
+  <li>Levar o cachorro para passear</li>
+  <li>Exercitar-se</li>
+  <li>Escrever codigo</li>
+  <li>Tocar musica</li>
+  <li>Relaxar</li>
+</ul>
+
+ +

Conteúdo CSS

+ +
li {
+  list-style-type: none;
+  position: relative;
+  margin: 2px;
+  padding: 0.5em 0.5em 0.5em 2em;
+  background: lightgrey;
+  font-family: sans-serif;
+}
+
+li.done {
+  background: #CCFF99;
+}
+
+li.done::before {
+  content: '';
+  position: absolute;
+  border-color: #009933;
+  border-style: solid;
+  border-width: 0 0.3em 0.25em 0;
+  height: 1em;
+  top: 1.3em;
+  left: 0.6em;
+  margin-top: -1em;
+  transform: rotate(45deg);
+  width: 0.5em;
+}
+ +

Conteúdo JavaScript

+ +
var list = document.querySelector('ul');
+list.addEventListener('click', function(ev) {
+  if( ev.target.tagName === 'LI') {
+     ev.target.classList.toggle('done');
+  }
+}, false);
+
+ +

Aqui está rodando o código acima. Perceba que nenhum ícone é utilizado e o check-mark é o ::before que foi estilizado no CSS.

+ +

Saída

+ +

{{EmbedLiveSample('To-do_list', 400, 300)}}

+ +

Notas

+ +

Embora as correções posicionadas e fixadas no Firefox 3.5 não permitam que o conteúdo seja gerado como um irmão anterior ao elemento (conforme a especificação para o CSS indicam "Os Pseudo-elementos :before e :after interagem com outros elementos como se fosse elementos reais inseridos dentro do elemento associado."), eles podem ser usados para proporcionar uma ligeira melhora em layouts sem tables (por exemplo, para alcançar a centralização), a medida que o conteúdo a ser centrado está envolvido com um elemento filho adicional, uma coluna antes e depois do conteúdo pode ser introduzida sem adicionar elementos filhos reais (isto é, talvez mais semanticamente correto para adicionar uma pequena distância, do que seria adicionar um div vazio antes e / ou depois). (E sempre lembre-se de adicionar uma largura a um flutuador, pois, de outra forma, não flutuará!)

+ +

HTML content

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

CSS content

+ +
#floatme { float: left; width: 50%; }
+
+/* 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) */
+.example::before {
+  content: "Floated Before";
+  float: left;
+  width: 25%
+}
+.example::after {
+  content: "Floated After";
+  float: right;
+  width:25%
+}
+
+/* For styling */
+.example::before, .example::after, .first {
+  background: yellow;
+  color: red;
+}
+ +

Output

+ +

{{EmbedLiveSample("Notes")}}

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS4 Pseudo-Elements', '#selectordef-before', '::before')}}{{Spec2('CSS4 Pseudo-Elements')}}No significant changes to the previous specification.
{{Specname("CSS3 Transitions", "#animatable-properties", "")}}{{Spec2("CSS3 Transitions")}}Allows transitions on properties defined on pseudo-elements.
{{Specname("CSS3 Animations", "", "")}}{{Spec2("CSS3 Animations")}}Allows animations on properties defined on pseudo-elements.
{{SpecName('CSS3 Selectors', '#gen-content', '::before')}}{{Spec2('CSS3 Selectors')}}Introduces the two-colon syntax.
{{SpecName('CSS2.1', 'generate.html#before-after-content', '::before')}}{{Spec2('CSS2.1')}}Initial definition, using the one-colon syntax
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
:before support{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.0")}}[1]8.0{{CompatOpera("4")}}4.0
::before support{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.8")}}[1]9.0{{CompatOpera("7")}}4.0
Support of animations and transitions26{{CompatGeckoDesktop("2.0")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChromeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
:before support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
::before support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}7.1{{CompatUnknown}}5.1
Support of animations and transitions26{{CompatVersionUnknown}}{{CompatGeckoMobile("4.0")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] Firefox prior to version 3.5 only implemented the CSS 2.0 version of :before. Not allowed were {{cssxref("position")}}, {{cssxref("float")}}, list-style-* and some display properties. Firefox 3.5 removed those restrictions.

+ +

See also

+ + diff --git a/files/pt-br/web/css/_doublecolon_first-letter/index.html b/files/pt-br/web/css/_doublecolon_first-letter/index.html new file mode 100644 index 0000000000..990a51a3ff --- /dev/null +++ b/files/pt-br/web/css/_doublecolon_first-letter/index.html @@ -0,0 +1,190 @@ +--- +title: '::first-letter (:first-letter)' +slug: 'Web/CSS/::first-letter' +translation_of: 'Web/CSS/::first-letter' +--- +

{{ CSSRef() }}

+ +

Sumário

+ +

O ::first-letter CSS pseudo-elemento que seleciona a primeira letra da primeira linha de um bloco, se nçao for procedido por qual outro conteúdo (como imagens ou tableas embutidas/inline table) na mesma linha.

+ +

A primeira letra de um elemento não é necessariamente uma identificação trivial:

+ + + +

Uma primeira linha tem apenas significado em uma caixa de contêiner de bloco; portanto, o pseudo-elemento ::first-letter apenas afeta os elementos com um valor de {{cssxref ("display")}} de block, inline-block, table-cell, list-item ou table-caption. Em todos os outros casos, ::first-letter não tem efeito.

+ +

Somente um pequeno subconjunto de todas as propriedades CSS pode ser usado dentro de um bloco de declaração de um conjunto de regras CSS que contém um seletor usando o pseudoelemento ::first-letter:

+ + + +

Como toda essa lista será estendida no futuro, é recomendado que você não use qualquer propriedade dentro da declaração do bloco, afim de manter o CSS a qualquer prova.

+ +
+

No CSS 2, os pseudoelementos eram prefixados com um caractere de dois pontos (:). Como as pseudo-classes também estavam seguindo a mesma convenção, elas eram indistinguíveis. Para resolver isso, o CSS 2.1 mudou a convenção para pseudoelementos. Agora, um pseudoelemento é prefixado com dois caracteres de dois pontos (::) e uma pseudo-classe ainda é prefixado com um único dois pontos (:).

+ +

Exemplo de pseudoclasse:
+ .classedoelemento:hover { ... }

+ +

Exemplo de pesudoelemento:
+ .classedoelemento::first-letter { ... }

+ +

Como vários navegadores já implementaram a versão CSS 2 em uma versão de lançamento, todos os navegadores que suportam a sintaxe de dois pontos também suportam a antiga sintaxe de dois pontos.

+ +
+

Mas isso pode mudar, portanto use SEMPRE :: para pseudolementos

+ +

...a não se que você precise muito que seu código seja compatível com Internet Explore 8, então use um carectere de dois pontos.

+
+
+ +

Exemplo

+ +
/* Fazendo odas as letras dos paragrados maior e vermelha */
+
+p::first-letter {  /* Use :first-letter if você precise muito de compatibilidade com IE 8 */
+  color: red;
+  font-size: 130%;
+}
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçõesStatusComentários
{{ SpecName('CSS4 Pseudo-Elements', '#first-letter-pseudo', '::first-letter')}}{{ Spec2('CSS4 Pseudo-Elements')}}Propriedades permitidas generalizadas para tipografia, decoração de texto e propriedades de layout embutido, {{ cssxref("opacity") }} e {{ cssxref("box-shadow") }}.
{{ SpecName('CSS3 Text Decoration', '#text-shadow', 'text-shadow with ::first-letter')}}{{ Spec2('CSS3 Text Decoration')}}Permitido uso de {{cssxref("text-shadow")}} com ::first-letter.
{{ SpecName('CSS3 Selectors', '#first-letter', '::first-letter') }}{{ Spec2('CSS3 Selectors') }}Comportamento definido entre maiúsculas e minúsculas, como nos itens da lista, ou com comportamento específico do idioma (como o dígrafo holandês IJ). A sintaxe de dois dois-pontos para pseudo-elementos foi introduzida.
{{ SpecName('CSS2.1', 'selector.html#first-letter', '::first-letter') }}{{ Spec2('CSS2.1') }}Sem mudanças significativas, apesar que CSS nível 2 continuar aceitando apenas um dois-pontos.
{{ SpecName('CSS1', '#the-first-letter-pseudo-element', '::first-letter') }}{{ Spec2('CSS1') }}Definição inicial de um dois-pontos.
+ +

Compatibilidade de Navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracteristicasChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte Básico1.0{{ CompatGeckoDesktop("1") }}9.07.01.0 (85)
Velha sintaxe de um dois-pontos (:first-line)1.0{{ CompatGeckoDesktop("1") }}5.53.51.0 (85)
Suporte ao dígrafo Holandês IJ{{ CompatNo() }}{{ CompatNo() }} {{ bug("92176") }} {{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CaracteristicasAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Suporte Básico{{ CompatUnknown() }}{{ CompatGeckoMobile("1") }}{{ CompatNo() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
Velha sintaxe um dois-pontos (:first-line){{ CompatUnknown() }}{{ CompatGeckoMobile("1") }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
Suporte ao dígrafo holandês IJ{{ CompatUnknown() }}{{ CompatNo() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/css/_doublecolon_first-line/index.html b/files/pt-br/web/css/_doublecolon_first-line/index.html new file mode 100644 index 0000000000..e1fc0246ff --- /dev/null +++ b/files/pt-br/web/css/_doublecolon_first-line/index.html @@ -0,0 +1,115 @@ +--- +title: '::first-line (:first-line)' +slug: 'Web/CSS/::first-line' +translation_of: 'Web/CSS/::first-line' +--- +
{{CSSRef}}
+ +

O pseudoelemento ::first-line aplica estilos à primeira linha de um elemento no nível do bloco. Observe que o comprimento da primeira linha depende de muitos fatores, incluindo a largura do elemento, a largura do documento e o tamanho da fonte do texto.

+ +
/* Seleciona a primeira linha dentro da tag <p> */
+p::first-line {
+  color: red;
+}
+ +
+

O CSS3 introduziu a notação ::first-line(com dois pontos) para distinguir pseudo-classes de pseudo-elementos. Os navegadores também aceitam  :first-line introduzida no CSS2.

+
+ +

Propriedades permitidas

+ +

Somente um pequeno subconjunto de propriedades CSS pode ser usado com o::first-line pseudo-elemento:

+ + + +

Sintaxe

+ +
{{csssyntax}}
+ +

Exemplos

+ +

HTML

+ +
<p>Os estilos serão aplicados apenas à primeira linha deste parágrafo.
+Depois disso, todo o texto será estilizado normalmente. Entendeu o que eu quis dizer?</p>
+
+<span>A primeira linha deste texto não receberá um estilo especial
+porque não é um elemento no nível do bloco.</span>
+ +

CSS

+ +
::first-line {
+  color: blue;
+  text-transform: uppercase;
+
+
+  /* AVISO: NÃO UTILIZE: */
+  /* Muitas propriedades são inválidas em pseudo-elementos ::first-line */
+  margin-left: 20px;
+  text-indent: 20px;
+}
+ +

Resultado

+ +

{{EmbedLiveSample('Examples', 350, 160)}}

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('CSS4 Pseudo-Elements', '#first-line-pseudo', '::first-line')}}{{Spec2('CSS4 Pseudo-Elements')}}Define mais estritamente onde ::first-letter pode ocorrer.
+ Generaliza propriedades permitidas para tipografia, decoração de texto e propriedades de layout embutido e {{cssxref("opacity")}}.
+ Define a herança de::first-letter.
{{SpecName('CSS3 Text Decoration', '#text-shadow-property', 'text-shadow with ::first-line')}}{{Spec2('CSS3 Text Decoration')}}Permite o uso de {{cssxref("text-shadow")}} com ::first-letter.
{{SpecName('CSS3 Selectors', '#first-line', '::first-line')}}{{Spec2('CSS3 Selectors')}}Introdução da sintaxe de dois-pontos.
{{SpecName('CSS2.1', 'selector.html#first-line-pseudo', '::first-line')}}{{Spec2('CSS2.1')}}Nenhuma mudança.
{{SpecName('CSS1', '#the-first-line-pseudo-element', '::first-line')}}{{Spec2('CSS1')}}Definição inicial, usando a sintaxe de dois pontos.
+ +

Compatibilidade do navegador

+ +
+ + +

{{Compat("css.selectors.first-line")}}

+
+ +

Veja também

+ + diff --git a/files/pt-br/web/css/_doublecolon_selection/index.html b/files/pt-br/web/css/_doublecolon_selection/index.html new file mode 100644 index 0000000000..16ad827a2a --- /dev/null +++ b/files/pt-br/web/css/_doublecolon_selection/index.html @@ -0,0 +1,129 @@ +--- +title: '::selection' +slug: 'Web/CSS/::selection' +translation_of: 'Web/CSS/::selection' +--- +
{{CSSRef}}
+ +

pseudo-elemento CSS ::selection aplica estilos para partes do documento que foram selecionadas pelo usuário (tal como clicar e arrastar o ponteiro do mouse através de um texto.

+ +
::selection {
+  background-color: cyan;
+}
+ +

Propriedades permitidas

+ +

Apenas certas propriedades podem ser usadas com o ::selection:

+ + + +
+

Em particular, {{CSSxRef("background-image")}} é ignorada.

+
+ +

Sintaxe

+ +
/* Sintaxe legado do Firefox (até a versão 61) */
+::-moz-selection
+
+{{CSSSyntax}}
+
+ +

Exemplo

+ +

HTML

+ +
Esse texto tem estilos especiais quando selecionado.
+<p>Tente selecionando também o texto nesse parágrafo.</p>
+ +

CSS

+ + + +
/* Texto selecionado dourado com o fundo vermelho */
+::selection {
+  color: gold;
+  background-color: red;
+}
+
+/* Texto selecionado branco com o fundo azul */
+p::selection {
+  color: white;
+  background-color: blue;
+}
+ +

Resultado

+ +

{{EmbedLiveSample('Exemplo')}}

+ +

Preocupações com acessibilidade

+ +

Não substitua os estilos de texto selecionados por razões puramente estéticas — os usuários podem personalizá-los para atender às suas necessidades. Para pessoas com problemas cognitivos ou com menos conhecimento tecnológico, alterações inesperadas nos estilos de seleção podem prejudicar sua compreensão da funcionalidade.

+ +

Se substituído, é importante garantir que a taxa de contraste entre o texto e as cores de plano de fundo da seleção seja alta o suficiente para que pessoas com condições de baixa visão possam lê-lo.

+ +

A taxa de contraste da cor é encontrada comparando a luminosidade do texto selecionado e as cores de fundo do texto selecionado. Para atender às atuais Diretrizes de acessibilidade de conteúdo da Web (WCAG), o conteúdo de texto deve ter uma taxa de contraste de 4.5:1 ou 3:1 para texto maior, como títulos. (WCAG define texto grande entre 18,66 px e 24 px e negrito, ou 24 px ou maior.)

+ +

Facilite para os usuários ver e ouvir o conteúdo, incluindo a separação do primeiro plano do segundo plano

+ + + +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçõesStatusComentário
{{SpecName('CSS4 Pseudo-Elements', '#selectordef-selection', '::selection')}}{{Spec2('CSS4 Pseudo-Elements')}}Definição inicial.
+ +
+

Nota: ::selection estava nos rascunhos do Nível 3 dos Seletores de CSS, mas foi removido na fase Recomendação do Candidato porque estava subespecificado (especialmente com elementos aninhados) e a interoperabilidade não foi alcançada (com base na lista de discussão de estilos W3C). Ele retornou no Nível 4 dos Pseudo-Elementos.

+
+ +

Compatibilidade

+ + + +

{{Compat("css.selectors.selection")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/css/align-content/index.html b/files/pt-br/web/css/align-content/index.html new file mode 100644 index 0000000000..349bc34b26 --- /dev/null +++ b/files/pt-br/web/css/align-content/index.html @@ -0,0 +1,294 @@ +--- +title: align-content +slug: Web/CSS/align-content +translation_of: Web/CSS/align-content +--- +

A propriedade CSS align-content define a distribuição entre e ao redor dos items do conteúdo do eixo transversal de uma flexbox ou do eixo de bloco de uma grid.

+ +

O exemplo interativo abaixo use Grid Layout para demonstrar alguns dos valores dessa propriedade.

+ +
{{EmbedInteractiveExample("pages/css/align-content.html")}}
+ + + +

This property has no effect on single line flex containers (i.e. ones with flex-wrap: nowrap).

+ +

Syntax

+ +
/* Basic positional alignment */
+/* align-content does not take left and right values */
+align-content: center;     /* Pack items around the center */
+align-content: start;      /* Pack items from the start */
+align-content: end;        /* Pack items from the end */
+align-content: flex-start; /* Pack flex items from the start */
+align-content: flex-end;   /* Pack flex items from the end */
+
+/* Normal alignment */
+align-content: normal;
+
+/* Baseline alignment */
+align-content: baseline;
+align-content: first baseline;
+align-content: last baseline;
+
+/* Distributed alignment */
+align-content: space-between; /* Distribute items evenly
+                                 The first item is flush with the start,
+                                 the last is flush with the end */
+align-content: space-around;  /* Distribute items evenly
+                                 Items have a half-size space
+                                 on either end */
+align-content: space-evenly;  /* Distribute items evenly
+                                 Items have equal space around them */
+align-content: stretch;       /* Distribute items evenly
+                                 Stretch 'auto'-sized items to fit
+                                 the container */
+
+/* Overflow alignment */
+align-content: safe center;
+align-content: unsafe center;
+
+/* Global values */
+align-content: inherit;
+align-content: initial;
+align-content: unset;
+
+ +

Values

+ +
+
start
+
The items are packed flush to each other against the start edge of the alignment container in the cross axis.
+
end
+
The items are packed flush to each other against the end edge of the alignment container in the cross axis.
+
flex-start
+
The items are packed flush to each other against the edge of the alignment container depending on the flex container's cross-start side.
+ This only applies to flex layout items. For items that are not children of a flex container, this value is treated like start.
+
flex-end
+
The items are packed flush to each other against the edge of the alignment container depending on the flex container's cross-end side.
+ This only applies to flex layout items. For items that are not children of a flex container, this value is treated like end.
+
center
+
The items are packed flush to each other in the center of the alignment container along the cross axis.
+
normal
+
The items are packed in their default position as if no align-content value was set.
+
baseline
+ first baseline

+ last baseline
+
the baseline is the line upon which most letters "sit" and below which descenders extend.
+
Specifies participation in first- or last-baseline alignment: aligns the alignment baseline of the box’s first or last baseline set with the corresponding baseline in the shared first or last baseline set of all the boxes in its baseline-sharing group.
+ The fallback alignment for first baseline is start, the one for last baseline is end.
+
space-between
+
The items are evenly distributed within the alignment container along the cross axis. The spacing between each pair of adjacent items is the same. The first item is flush with the start edge of the alignment container in the cross axis, and the last item is flush with the end edge of the alignment container in the cross axis.
+
space-around
+
The items are evenly distributed within the alignment container along the cross axis. The spacing between each pair of adjacent items is the same. The empty space before the first and after the last item equals half of the space between each pair of adjacent items.
+
space-evenly
+
The items are evenly distributed within the alignment container along the cross axis. The spacing between each pair of adjacent items, the start edge and the first item, and the end edge and the last item, are all exactly the same.
+
stretch
+
If the combined size of the items along the cross axis is less than the size of the alignment container, any auto-sized items have their size increased equally (not proportionally), while still respecting the constraints imposed by {{cssxref("max-height")}}/{{cssxref("max-width")}} (or equivalent functionality), so that the combined size exactly fills the alignment container along the cross axis.
+
safe
+
Used alongside an alignment keyword. If the chosen keyword means that the item overflows the alignment container causing data loss, the item is instead aligned as if the alignment mode were start.
+
unsafe
+
Used alongside an alignment keyword. Regardless of the relative sizes of the item and alignment container and whether overflow which causes data loss might happen, the given alignment value is honored.
+
+ +

Formal definition

+ +

{{CSSInfo}}

+ +

Formal syntax

+ +
{{csssyntax}}
+ +

Examples

+ +

CSS

+ +
#container {
+  height:200px;
+  width: 240px;
+  align-content: center; /* Can be changed in the live sample */
+  background-color: #8c8c8c;
+}
+
+.flex {
+  display: flex;
+  flex-wrap: wrap;
+}
+
+.grid {
+  display: grid;
+  grid-template-columns: repeat(auto-fill, 50px);
+}
+
+div > div {
+  box-sizing: border-box;
+  border: 2px solid #8c8c8c;
+  width: 50px;
+  display: flex;
+  align-items: center;
+  justify-content: center;
+}
+
+#item1 {
+  background-color: #8cffa0;
+  min-height: 30px;
+}
+
+#item2 {
+  background-color: #a0c8ff;
+  min-height: 50px;
+}
+
+#item3 {
+  background-color: #ffa08c;
+  min-height: 40px;
+}
+
+#item4 {
+  background-color: #ffff8c;
+  min-height: 60px;
+}
+
+#item5 {
+  background-color: #ff8cff;
+  min-height: 70px;
+}
+
+#item6 {
+  background-color: #8cffff;
+  min-height: 50px;
+  font-size: 30px;
+}
+
+select {
+  font-size: 16px;
+}
+
+.row {
+  margin-top: 10px;
+}
+
+ +

HTML

+ +
<div id="container" class="flex">
+  <div id="item1">1</div>
+  <div id="item2">2</div>
+  <div id="item3">3</div>
+  <div id="item4">4</div>
+  <div id="item5">5</div>
+  <div id="item6">6</div>
+</div>
+
+<div class="row">
+  <label for="display">display: </label>
+  <select id="display">
+    <option value="flex">flex</option>
+    <option value="grid">grid</option>
+  </select>
+</div>
+
+<div class="row">
+  <label for="values">align-content: </label>
+  <select id="values">
+    <option value="normal">normal</option>
+    <option value="stretch">stretch</option>
+    <option value="flex-start">flex-start</option>
+    <option value="flex-end">flex-end</option>
+    <option value="center" selected>center</option>
+    <option value="space-between">space-between</option>
+    <option value="space-around">space-around</option>
+    <option value="space-evenly">space-evenly</option>
+
+    <option value="start">start</option>
+    <option value="end">end</option>
+    <option value="left">left</option>
+    <option value="right">right</option>
+
+    <option value="baseline">baseline</option>
+    <option value="first baseline">first baseline</option>
+    <option value="last baseline">last baseline</option>
+
+    <option value="safe center">safe center</option>
+    <option value="unsafe center">unsafe center</option>
+    <option value="safe right">safe right</option>
+    <option value="unsafe right">unsafe right</option>
+    <option value="safe end">safe end</option>
+    <option value="unsafe end">unsafe end</option>
+    <option value="safe flex-end">safe flex-end</option>
+    <option value="unsafe flex-end">unsafe flex-end</option>
+  </select>
+</div>
+
+ + + +

Result

+ +

{{EmbedLiveSample("Example", 260, 290)}}

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("CSS3 Box Alignment", "#propdef-align-content", "align-content")}}{{Spec2("CSS3 Box Alignment")}}Adds the [ first | last ]? baseline, start, end, left, right, unsafe | safe values.
{{SpecName("CSS3 Flexbox", "#align-content-property", "align-content")}}{{Spec2("CSS3 Flexbox")}}Initial definition
+ +
{{cssinfo}}
+ +

Browser compatibility

+ +
+ + +

Support in Flex layout

+ +

{{Compat("css.properties.align-content.flex_context")}}

+ +

Support in Grid layout

+ +

{{Compat("css.properties.align-content.grid_context")}}

+
+ +

See also

+ + + +
{{CSSRef}}
diff --git a/files/pt-br/web/css/align-items/index.html b/files/pt-br/web/css/align-items/index.html new file mode 100644 index 0000000000..2d74f7ec77 --- /dev/null +++ b/files/pt-br/web/css/align-items/index.html @@ -0,0 +1,286 @@ +--- +title: align-items +slug: Web/CSS/align-items +tags: + - CSS + - CSS Flexible Boxes + - CSS Propriedade + - Referencia +translation_of: Web/CSS/align-items +--- +

A propriedade CSS align-items estabelece o valor {{cssxref("align-self")}} em todos filhos diretos como um grupo. A propriedade align-self estabelece o alinhamento de um certo item dentro do bloco que o contém. Em Flexbox ele controla o alinhamento dos itens em {{glossary("Cross Axis")}}, enquanto que no Grid Layout, controla o alinhamento dos itens no Eixo de Bloco dentro de sua  grid area.

+ +

O exemplo interativo abaixo demonstra alguns dos valores para align-items usando grid layout.

+ +
{{EmbedInteractiveExample("pages/css/align-items.html")}}
+ + + +

Sintaxe

+ +
/* Palavras-chave básicas */
+align-items: normal;
+align-items: stretch;
+
+/* Posicionamento do alinhamento */
+/* align-items não recebe valores left e right */
+align-items: center; /* Itens posicionados ao redor do centro */
+align-items: start; /* Posiciona itens a partir do início */
+align-items: end; /* Posiciona itens a partir do fim */
+align-items: flex-start; /* Posiciona itens-flex a partir do início */
+align-items: flex-end; /* Posiciona itens-flex a partir do fim */
+align-items: self-start;
+align-items: self-end;
+
+/* Alinhamento da baseline */
+align-items: baseline;
+align-items: first baseline;
+align-items: last baseline; /* Overflow alinhamento (apenas para alinhamento de posição) */
+align-items: safe center;
+align-items: unsafe center;
+
+/* Valores globais */
+align-items: inherit;
+align-items: initial;
+align-items: unset;
+
+ +

Valores

+ +
+
normal
+
O efeito desta palavra-chave depende do modo de layout em que nos encontramos: +
    +
  • Em layouts absolutamente posicionados, a palavra-chave se comporta como start em replaced de caixas absolutamente posicionadas, e como stretch em all others de caixas absolutamente posicionadas.
  • +
  • Em posição estática de layouts absolutamente posicionados, a palavra-chave se comporta como stretch.
  • +
  • Para itens-flex, a palavra chave se comporto como stretch.
  • +
  • Para itens-grid, esta palavra-chave leva a um comportamento similiar ao stretch, exceto para caixas com um aspect ratio ou tamanhos intrínsecos, onde se comporta como start.
  • +
  • A propriedade não se aplica para caixas block-level, e para células de tabela.
  • +
+
+
flex-start
+
As bordas da margem superior dos itens-flex são juntados com a borda superior da linha.
+
flex-end
+
As bordas da margem inferior dos itens flex são juntados com a borda inferior da linha.
+
center
+
As caixas de margem dos itens flex são centralizados ao longo da linha do eixo. Caso o tamanho de um item seja superior ao container flex, irá transbordar de maneira igual em ambas direções.
+
start
+
Os itens são posicionados, para cada um, em direção a borda início do container de alinhamento no eixo apropriado. 
+
end
+
Os itens são posicionados, para cada um, em direção a borda fim do container de alinhamento no eixo apropriado.
+
self-start
+
Os itens são posicionados para a borda do container de alinhamento do lado inicial do item, no eixo apropriado.
+
self-end
+
Os itens são posicionados para a borda do container de alinhamento do lado final do item, no eixo apropriado.
+
+ +
+
baseline
+
first baseline
+
last baseline
+
Todos itens-flex são alinhados de tal forma que suas  baselines de container flex estejam alinhados. O item com a maior distância entre o eixo de início de sua margem e sua baseline é juntado com eixo de início da linha.
+
stretch
+
Itens-flex são esticados de tal maneira que o tamanho da caixa de margem do item seja o mesmo da linha, respeitando as restrições de comprimento e altura.
+
safe
+
Usado em conjunto com uma palavra-chave de alinhamento. Se a palavra-chave escolhida signifique que o item transborde o alinhamento do container, causando assim perda de dados, o item é alinhado como estivesse no modo start.
+
unsafe
+
Usado em conjunto com uma palavra-chave de alinhamento. Independente dos tamanhos relativos do item, do alinhamento do container e caso overflow possa causar perda de dados, o valor de alinhamento estabelecido é mantido.
+
+ +

Sintaxe formal

+ +
{{csssyntax}}
+
+ +

Exemplo

+ +

CSS

+ +
#container {
+  height:200px;
+  width: 240px;
+  align-items: center; /* Pode ser mudado na amostra ao vivo */
+  background-color: #8c8c8c;
+}
+
+.flex {
+  display: flex;
+  flex-wrap: wrap;
+}
+
+.grid {
+  display: grid;
+  grid-template-columns: repeat(auto-fill, 50px);
+}
+
+div > div {
+  box-sizing: border-box;
+  border: 2px solid #8c8c8c;
+  width: 50px;
+  display: flex;
+  align-items: center;
+  justify-content: center;
+}
+
+#item1 {
+  background-color: #8cffa0;
+  min-height: 30px;
+}
+
+#item2 {
+  background-color: #a0c8ff;
+  min-height: 50px;
+}
+
+#item3 {
+  background-color: #ffa08c;
+  min-height: 40px;
+}
+
+#item4 {
+  background-color: #ffff8c;
+  min-height: 60px;
+}
+
+#item5 {
+  background-color: #ff8cff;
+  min-height: 70px;
+}
+
+#item6 {
+  background-color: #8cffff;
+  min-height: 50px;
+  font-size: 30px;
+}
+
+select {
+  font-size: 16px;
+}
+
+.row {
+  margin-top: 10px;
+}
+ +

HTML

+ +
<div id="container" class="flex">
+  <div id="item1">1</div>
+  <div id="item2">2</div>
+  <div id="item3">3</div>
+  <div id="item4">4</div>
+  <div id="item5">5</div>
+  <div id="item6">6</div>
+</div>
+
+<div class="row">
+  <label for="display">display: </label>
+  <select id="display">
+    <option value="flex">flex</option>
+    <option value="grid">grid</option>
+  </select>
+</div>
+
+<div class="row">
+  <label for="values">align-items: </label>
+  <select id="values">
+    <option value="normal">normal</option>
+    <option value="flex-start">flex-start</option>
+    <option value="flex-end">flex-end</option>
+    <option value="center" selected>center</option>
+    <option value="baseline">baseline</option>
+    <option value="stretch">stretch</option>
+
+    <option value="start">start</option>
+    <option value="end">end</option>
+    <option value="self-start">self-start</option>
+    <option value="self-end">self-end</option>
+    <option value="left">left</option>
+    <option value="right">right</option>
+
+    <option value="first baseline">first baseline</option>
+    <option value="last baseline">last baseline</option>
+
+    <option value="safe center">safe center</option>
+    <option value="unsafe center">unsafe center</option>
+    <option value="safe right">safe right</option>
+    <option value="unsafe right">unsafe right</option>
+    <option value="safe end">safe end</option>
+    <option value="unsafe end">unsafe end</option>
+    <option value="safe self-end">safe self-end</option>
+    <option value="unsafe self-end">unsafe self-end</option>
+    <option value="safe flex-end">safe flex-end</option>
+    <option value="unsafe flex-end">unsafe flex-end</option>
+  </select>
+</div>
+
+ + + +

Resultado

+ +

{{EmbedLiveSample("Example", "260px", "290px")}}

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName("CSS3 Box Alignment", "#propdef-align-items", "align-items")}}{{Spec2("CSS3 Box Alignment")}}Atualização para últimas definições de sintaxe.
{{SpecName('CSS3 Flexbox', '#propdef-align-items', 'align-items')}}{{Spec2('CSS3 Flexbox')}}Definição inicial
+ +

{{cssinfo}}

+ +

Compatibilidade de Navegador

+ + + +

Support in Flex layout

+ +

{{Compat("css.properties.align-items.flex_context")}}

+ +

Support in Grid layout

+ +

{{Compat("css.properties.align-items.grid_context")}}

+ +

Veja também

+ + + +
{{CSSRef}}
diff --git a/files/pt-br/web/css/align-self/index.html b/files/pt-br/web/css/align-self/index.html new file mode 100644 index 0000000000..a57605a13f --- /dev/null +++ b/files/pt-br/web/css/align-self/index.html @@ -0,0 +1,175 @@ +--- +title: align-self +slug: Web/CSS/align-self +tags: + - CSS + - CSS Alinhamento Caixa + - CSS Caixas flexíveis + - CSS Propriedade + - Referencia +translation_of: Web/CSS/align-self +--- +

A propriedade CSS align-self alinha itens-flex da linha flex alvo, sobreescrevendo o valor {{cssxref("align-items")}}. Se alguma dos eixos das margens do dado item está estabelecido como auto, então align-self é ignorado.

+ +
{{EmbedInteractiveExample("pages/css/align-self.html")}}
+ + + +

A propriedade não se aplica a caixas block-level, ou células de tabela.

+ +

Sintaxe

+ +
/* valores de palavras-chave */
+align-self: auto;
+align-self: normal;
+
+/* Alinhamento de posicionamento */
+/* align-self não recebe valores left e right */
+align-self: center; /* Coloca o item em torno do centro */
+align-self: start; /* Coloca o item no início */
+align-self: end; /* Coloca o item no fim */
+align-self: self-start; /* Alinha o item flush no início */
+align-self: self-end; /* Alinha o item flush no fim */
+align-self: flex-start; /* Coloca o item flex no início */
+align-self: flex-end; /* Coloca o item flex no fim */
+
+/* Alinhamento a partir da baseline */
+align-self: baseline;
+align-self: first baseline;
+align-self: last baseline;
+align-self: stretch; /* Estica itens de tamanho 'auto' para encaixar no container */
+
+/* Alinhamento com Oveflow */
+align-self: safe center;
+align-self: unsafe center;
+
+/* Valores globais */
+align-self: inherit;
+align-self: initial;
+align-self: unset;
+ +

Valores

+ +
+
auto
+
O valor {{cssxref("align-items")}} é originado do valor de seu pai.
+
normal
+
O efeito dessa palavra-chave depende do modo de layout em que nos encontramos: +
    +
  • Em layouts absolutamente posicionados, a palavra-chave se comporta como start em caixas absolutamente posicionadas replaced, e como stretch em caixas absolutamente posicionadas all other.
  • +
  • Em posição estática de layouts absolutamente posicionados, a palavra-chave se comporta como stretch.
  • +
  • Para itens-flex, a palavra-chave se comporta como stretch.
  • +
  • Para itens-grid, essa palavra-chave leva ao comportamento similar ao de stretch, com exceção de caixas com aspect ratio ou tamanhos intrínsecos onde se comportam como start.
  • +
  • A propriedade não se aplica para caixas block-level, e para células de tabela.
  • +
+
+
self-start
+
Alinha os itens de maneira a mesclar a borda do alinhamento do container correspondente com o lado inicial do item no eixo.
+
self-end
+
Alinha os itens de maneira a mesclar a borda do alinhamento do container correspondente com o lado final do item no eixo.
+
flex-start
+
A borda da margem inicial do item flex é mesclada com a borda inicial da linha.
+
flex-end
+
A borda da margem fim do item flex é mesclada com a borda fim da linha.
+
center
+
A caixa-margem do item flex é centralizada ao longo da linha no eixo transversal. Se o tamanho do item é superior to container flex, então ele irá transbordar de maneira equivalente em ambas direções.
+
baseline
+ first baseline

+ last baseline
+
Specifies participation in first- or last-baseline alignment: aligns the alignment baseline of the box’s first or last baseline set with the corresponding baseline in the shared first or last baseline set of all the boxes in its baseline-sharing group.
+ The fallback alignment for first baseline is start, the one for last baseline is end.
+
stretch
+
Caso o tamanho combinado dos itens ao longo do eixo transversal seja menor do que o tamanho do container de alinhamento, e caso o tamanho do item segue o estilo auto, seu tamanho cresce igualmente (mas não proporcionalmente), enquanto que ainda respeitando as restrições impostas por {{cssxref("max-height")}}/{{cssxref("max-width")}} (ou a funcionalidade equivalente), de maneira que o tamanho combinado de todos itens tamanho-auto preencha exatamente o container de alinhamento ao longo do eixo transversal.
+
safe
+
Caso o tamanho do item supere o alinhamento do container, o item é alinhado como se o modo de alinhamento fosse start.
+
unsafe
+
Independente dos tamanhos relativos do item e do alinhamento do container, o valor do alinhmento dado é mantido.
+
+ +

Sintaxe formal

+ +
{{csssyntax}}
+ +

Exemplo

+ +

HTML

+ +
<section>
+  <div>Item #1</div>
+  <div>Item #2</div>
+  <div>Item #3</div>
+</section>
+ +

CSS

+ +
section {
+  display: flex;
+  align-items: center;
+  height: 120px;
+  background: beige;
+}
+
+div {
+  height: 60px;
+  background: cyan;
+  margin: 5px;
+}
+
+div:nth-child(3) {
+  align-self: flex-end;
+  background: pink;
+}
+ +

Resultado

+ +

{{EmbedLiveSample('Example')}}

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName("CSS3 Box Alignment", "#propdef-align-self", "align-self")}}{{Spec2("CSS3 Box Alignment")}}Atualiza para últimas definições de sintaxe.
{{SpecName("CSS3 Flexbox", "#propdef-align-self", "align-self")}}{{Spec2("CSS3 Flexbox")}}Definição inicial.
+ +

{{cssinfo}}

+ +

Compatibilidade de navegador

+ + + +

Suporte em Flex layout

+ +

{{Compat("css.properties.align-self.flex_context")}}

+ +

Suporte em Grid layout

+ +

{{Compat("css.properties.align-self.grid_context")}}

+ +

Veja também

+ + + +
{{CSSRef}}
diff --git a/files/pt-br/web/css/animation-delay/index.html b/files/pt-br/web/css/animation-delay/index.html new file mode 100644 index 0000000000..e8ed7db06d --- /dev/null +++ b/files/pt-br/web/css/animation-delay/index.html @@ -0,0 +1,145 @@ +--- +title: animation-delay +slug: Web/CSS/animation-delay +tags: + - Animação +translation_of: Web/CSS/animation-delay +--- +
{{CSSRef}}
+ +

A propriedade CSS animation-delay especifíca quando uma animação deve começar.  Você pode começar a animação no futuro, imediatamente ou desde o  início, ou imediatamente e parcialmente através do ciclo de animação.

+ +
/* Uma animação */
+animation-delay: 3s;
+animation-delay: 0s;
+animation-delay: -1500ms;
+
+/* Várias animações */
+animation-delay: 2.1s, 480ms;
+
+ +

Muitas vezes é conveniente usar a propriedade abreviada {{cssxref("animation")}} para definir todas as propriedades de animação de uma só vez. 

+ +

{{cssinfo}}

+ +

Sintaxe

+ +

Valores

+ +
+
{{cssxref("<time>")}}
+
O deslocamento do tempo, a partir do momento em que a animação é aplicada ao elemento, no qual a animação deve começar. Isso pode ser especificado em segundos (s) ou milesegundos or milliseconds (ms). A unidade é necessaria.
+
Um valor positivo indica que a animação deve começar após o período de especificação ter decorrido.  O valor de 0s,  que é o padrão, incida que a animação deve começar desde que foi aplicada.
+
+

Um valor negativo faz com que a animação comece imediatamente, mas parcialmente através do seu ciclo. Por exemplo, se você específicar -1s como tempo da animation-delay , a animação vai começar imediatamente, mas começará 1 segundo na sequência de animação. Se você específicar um valor negativo para a animation-delay, mas o valor inicial é implícito, o valor inicial é retirado do momento em que a animação é aplicada ao elemento.

+
+
+ +
+

Note: Quando você especifica vários valores separados por vírgula em uma propriedade animation-* ,  eles serão atribuídos às animações especificadas na propriedade {{cssxref("animation-name")}} em diferentes modos,  dependendo de quantos existam. Para mais informações veja Setting multiple animation property values.

+
+ +

Sintaxe formal

+ +
{{csssyntax}}
+
+ +

Exemplos

+ +

Veja CSS animations para exemplos.

+ +

Especificação

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('CSS3 Animations', '#animation-delay', 'animation-delay')}}{{Spec2('CSS3 Animations')}}Definição inicial.
+ +

Compatibilidade com os browsers

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{property_prefix("-webkit")}}
+ {{CompatChrome(43.0)}}
{{CompatVersionUnknown}}{{property_prefix("-webkit")}}
+ {{CompatVersionUnknown}}
{{CompatGeckoDesktop("5.0")}}{{property_prefix("-moz")}}
+ {{CompatGeckoDesktop("16.0")}}[1]
1012{{property_prefix("-o")}}
+ 12.10
4.0{{property_prefix("-webkit")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{CompatVersionUnknown}}{{property_prefix("-webkit")}}{{CompatVersionUnknown}}{{property_prefix("-webkit")}}
+ {{CompatVersionUnknown}}
{{CompatGeckoMobile("5.0")}}{{property_prefix("-moz")}}
+ {{CompatGeckoMobile("16.0")}}[1]
{{CompatUnknown}}12{{property_prefix("-o")}}{{CompatVersionUnknown}}{{property_prefix("-webkit")}}{{CompatUnknown}}
+
+ +

[1] Além do suporte não prefixado, Gecko 44.0 {{geckoRelease("44.0")}} adicionou um suporte para uma versão prefixada de -webkit- por razões de compatibilidade na Web por trás da preferência layout.css.prefixes.webkit, padronizando para false. Desde Gecko 49.0 {{geckoRelease("49.0")}} os padrões de preferência são true.

+ +

Quantum CSS notas

+ + + +

Veja também

+ + diff --git a/files/pt-br/web/css/animation-fill-mode/index.html b/files/pt-br/web/css/animation-fill-mode/index.html new file mode 100644 index 0000000000..8e52a69d44 --- /dev/null +++ b/files/pt-br/web/css/animation-fill-mode/index.html @@ -0,0 +1,183 @@ +--- +title: animation-fill-mode +slug: Web/CSS/animation-fill-mode +translation_of: Web/CSS/animation-fill-mode +--- +
{{CSSRef}}
+ +

A propriedade CSS animation-fill-mode define como uma animação CSS aplica estilos ao seu destino antes e depois de sua execução.

+ +
{{EmbedInteractiveExample("pages/css/animation-fill-mode.html")}}
+ + + +

It is often convenient to use the shorthand property {{cssxref("animation")}} to set all animation properties at once.

+ +

Syntax

+ +
/* Single animation */
+animation-fill-mode: none;
+animation-fill-mode: forwards;
+animation-fill-mode: backwards;
+animation-fill-mode: both;
+
+/* Multiple animations */
+animation-fill-mode: none, backwards;
+animation-fill-mode: both, forwards, none;
+
+ +

Values

+ +
+
none
+
A animação não aplicará nenhum estilo ao destino quando não estiver em execução. Em vez disso, o elemento será exibido usando quaisquer outras regras CSS aplicadas a ele. Este é o valor padrão.
+
forwards
+
The target will retain the computed values set by the last keyframe encountered during execution. The last keyframe depends on the value of {{cssxref("animation-direction")}} and {{cssxref("animation-iteration-count")}}: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
animation-directionanimation-iteration-countlast keyframe encountered
normaleven or odd100% or to
reverseeven or odd0% or from
alternateeven0% or from
alternateodd100% or to
alternate-reverseeven100% or to
alternate-reverseodd0% or from
+
+
backwards
+
The animation will apply the values defined in the first relevant keyframe as soon as it is applied to the target, and retain this during the {{cssxref("animation-delay")}} period. The first relevant keyframe depends on the value of {{cssxref("animation-direction")}}: + + + + + + + + + + + + + + + + + +
animation-directionfirst relevant keyframe
normal or alternate0% or from
reverse or alternate-reverse100% or to
+
+
both
+
The animation will follow the rules for both forwards and backwards, thus extending the animation properties in both directions.
+
+ +
+

Note: When you specify multiple comma-separated values on an animation-* property, they will be assigned to the animations specified in the {{cssxref("animation-name")}} property in different ways depending on how many there are. For more information, see Setting multiple animation property values.

+
+ +

Formal syntax

+ +
{{csssyntax}}
+
+ +

Example

+ +

You can see the effect of animation-fill-mode in the following example. It demonstrates how, for an animation that runs for an infinite time, you can cause it to remain in its final state rather than reverting to the original state (which is the default).

+ +

HTML

+ +
<p>Move your mouse over the gray box!</p>
+<div class="demo">
+ <div class="growsandstays">This grows and stays big.</div>
+  <div class="grows">This just grows.</div>
+</div>
+ +

CSS

+ +
.demo {
+  border-top: 100px solid #ccc;
+  height: 300px;
+}
+
+@keyframes grow {
+  0% { font-size: 0; }
+  100% { font-size: 40px; }
+}
+
+.demo:hover .grows {
+  animation-name: grow;
+  animation-duration: 3s;
+}
+
+.demo:hover .growsandstays {
+  animation-name: grow;
+  animation-duration: 3s;
+  animation-fill-mode: forwards;
+}
+ +

{{EmbedLiveSample('Example',700,300)}}

+ +

See CSS animations for more examples.

+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Animations', '#animation-fill-mode', 'animation-fill-mode')}}{{Spec2('CSS3 Animations')}}Initial definition.
+ +

{{cssinfo}}

+ +

Browser compatibility

+ + + +

{{Compat("css.properties.animation-fill-mode")}}

+ +

See also

+ + diff --git a/files/pt-br/web/css/animation/index.html b/files/pt-br/web/css/animation/index.html new file mode 100644 index 0000000000..5c6ba64222 --- /dev/null +++ b/files/pt-br/web/css/animation/index.html @@ -0,0 +1,353 @@ +--- +title: animation +slug: Web/CSS/animation +tags: + - Animações + - Animações CSS + - CSS + - CSS Animations + - CSS3 + - Propriedade CSS + - Referencia + - Web +translation_of: Web/CSS/animation +--- +
{{CSSRef}}
+ +

A propriedade CSS abreviada animation, aplica uma animação entre estilos. É uma abreviação de {{cssxref("animation-name")}}, {{cssxref("animation-duration")}}, {{cssxref("animation-timing-function")}}, {{cssxref("animation-delay")}}, {{cssxref("animation-iteration-count")}}, {{cssxref("animation-direction")}}, {{cssxref("animation-fill-mode")}}, e {{cssxref("animation-play-state")}}.

+ +
{{EmbedInteractiveExample("pages/css/animation.html")}}
+ + + +
/* @keyframes duration | timing-function | delay |
+iteration-count | direction | fill-mode | play-state | name */
+animation: 3s ease-in 1s 2 reverse both paused slidein;
+
+/* @keyframes name | duration | timing-function | delay */
+animation: 3s linear 1s slidein;
+
+/* @keyframes name | duration */
+animation: slidein 3s;
+
+ + + +

{{EmbedLiveSample("animation", "100%", 260, "", "", "example-outcome-frame")}}

+ +

A description of which properties are animatable is available; it's worth noting that this description is also valid for CSS transitions.

+ +

{{cssinfo}}

+ +

Syntax

+ +

A propriedade animation é especificada como uma ou mais animações, separadas por commas.

+ +

Cada animação individual é especificada  como:

+ + + +

A ondem dos valores definidos dentro de cada animação é importante: o primeiro valor pode ser analisado com um {{cssxref("<time>")}} é atribuido para o {{cssxref("animation-duration")}}, and the second one is assigned to {{cssxref("animation-delay")}}.

+ +

The order within each animation definition is also important for distinguishing {{cssxref("animation-name")}} values from other keywords. When parsed, keywords that are valid for properties other than {{cssxref("animation-name")}}, and whose values were not found earlier in the shorthand, must be accepted for those properties rather than for {{cssxref("animation-name")}}. Furthermore, when serialized, default values of other properties must be output in at least the cases necessary to distinguish an {{cssxref("animation-name")}} that could be a value of another property, and may be output in additional cases.

+ +

Values

+ +
+
<single-animation-iteration-count>
+
The number of times the animation is played. The value must be one of those available in {{cssxref("animation-iteration-count")}}.
+
<single-animation-direction>
+
The direction in which the animation is played. The value must be one of those available in {{cssxref("animation-direction")}}.
+
<single-animation-fill-mode>
+
Determines how styles should be applied to the animation's target before and after its execution. The value must be one of those available in {{cssxref("animation-fill-mode")}}.
+
<single-animation-play-state>
+
Determines whether the animation is playing or not. The value must be one of those available in {{cssxref("animation-play-state")}}.
+
+ +

Formal syntax

+ +
{{csssyntax}}
+ +

Examples

+ +

Cylon Eye

+ +
<div class="view_port">
+  <div class="polling_message">
+    Listening for dispatches
+  </div>
+  <div class="cylon_eye"></div>
+</div>
+
+ +
.polling_message {
+  color: white;
+  float: left;
+  margin-right: 2%;
+}
+
+.view_port {
+  background-color: black;
+  height: 25px;
+  width: 100%;
+  overflow: hidden;
+}
+
+.cylon_eye {
+  background-color: red;
+  background-image: linear-gradient(to right,
+      rgba(0, 0, 0, .9) 25%,
+      rgba(0, 0, 0, .1) 50%,
+      rgba(0, 0, 0, .9) 75%);
+  color: white;
+  height: 100%;
+  width: 20%;
+
+  -webkit-animation: 4s linear 0s infinite alternate move_eye;
+          animation: 4s linear 0s infinite alternate move_eye;
+}
+
+@-webkit-keyframes move_eye { from { margin-left: -20%; } to { margin-left: 100%; }  }
+        @keyframes move_eye { from { margin-left: -20%; } to { margin-left: 100%; }  }
+
+ +

{{EmbedLiveSample('Cylon_Eye')}}

+ +

See Using CSS animations for additional examples.

+ +

Accessibility concerns

+ +

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.

+ + + +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Animations', '#animation', 'animation')}}{{Spec2('CSS3 Animations')}}Initial definition.
+ +

Browser compatibility

+ + + +

{{Compat("css.properties.animation")}}

+ +

Quantum CSS notes

+ + + +

See also

+ + diff --git a/files/pt-br/web/css/at-rule/index.html b/files/pt-br/web/css/at-rule/index.html new file mode 100644 index 0000000000..f4ecae9a84 --- /dev/null +++ b/files/pt-br/web/css/at-rule/index.html @@ -0,0 +1,33 @@ +--- +title: Regra At +slug: Web/CSS/At-rule +translation_of: Web/CSS/At-rule +--- +

Uma regra at (at-rule) é uma CSS statement iniciando com um caractere arroba, '@' (U+0040 ARROBA COMERCIAL), seguido por um indetificador e terminando no primeiro ponto e vírgula', ;' (U+003B SEMICOLON), fora de um bloco, ou no fim do primeiro Bloco CSS.

+

Existem muitas regras at, criadas por seu identificador, cada um com uma sintaxe diferente:

+ +

Grupos condicionais de regras

+

Assim como valores de propriedades, cada regra at possui uma sintaxe diferente; várias delas, entretanto, podem ser agrupadas em uma categoria especial, os grupos condicionais de regras. Essas regras compartilham uma sintaxe em comum. Cada uma delas inclui regras aninhadas, que são conjuntos de regras ou regras at aninhadas. Todas elas transmitem um significado semântico em comum: todas indicam uma condição (de um tipo diferente) para que as regras sejam aplicadas.

+

Grupos condicionais de regras são definidos pelo CSS3 e são:

+ +

Cada uma delas sendo também uma regra aninhada, pode haver uma quantidade indeterminada de aninhamentos.

+
+

{{ languages( { "ja": "ja/CSS/At-rule" } ) }}

+
+

 

diff --git a/files/pt-br/web/css/attr()/index.html b/files/pt-br/web/css/attr()/index.html new file mode 100644 index 0000000000..bbcfd0dd4c --- /dev/null +++ b/files/pt-br/web/css/attr()/index.html @@ -0,0 +1,217 @@ +--- +title: attr +slug: Web/CSS/attr() +tags: + - CSS + - Esquema + - Função CSS + - Internet + - Laioute + - Rede + - Referencia + - Web +translation_of: Web/CSS/attr() +--- +
{{CSSRef}}
+ +

A função attr() do CSS  é utilizada para se obter o valor de um determinado atributo do elemento selecionado e usá-lo na folha de estilo. Também pode ser utilizado em pseudo-elementos, nesse caso o valor do atributo no pseudo-elemento do elemento original é retornado.

+ +
/* Uso Simples */
+attr(data-count);
+attr(title);
+
+/* Com o tipo */
+attr(src url);
+attr(data-count number);
+attr(data-width px);
+
+/* Com fallback */
+attr(data-count number, 0);
+attr(src url, '');
+attr(data-width px, inherit);
+attr(data-something, 'default');
+
+ +
+

Nota: A função attr() pode ser utilizada com qualquer propriedade CSS, mas o suporte para propriedades que não sejam {{cssxref("content")}} é experimental.

+
+ +

Sintaxe

+ +

Valores

+ +
+
nome-do-atributo
+
É o nome do atributo HTML do elemento referenciado no CSS.
+
<tipo-ou-unidade> {{experimental_inline}}
+
É uma palavra-chave representando tanto o tipo quanto o valor do atributo, ou sua unidade, assim como no HTML alguns atributos tem unidades implícitas. Se o uso de <tipo-ou-unidade> como um valor para determinado atributo for inválido, a expressão attr() será inválida também. Se omitida, o padrão será string. A lista de valores válidos é: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Palavra-chaveTipo AssociadoComentárioValor Padrão
string{{cssxref("<string>")}}O valor do atributo é tratado como um CSS {{cssxref("<string>")}}. NÃO será reparado, e em particular os caracteres usados .An empty string.
cor {{experimental_inline}}{{cssxref("<color>")}}O valor do atributo é analisado como hash (3- ou 6-valores hash) ou a palavra-chave. Precisa ser um valor {{cssxref("<string>")}} CSS válido.
+ Os espaços do lead e trail são retirados.
corAtual
url {{experimental_inline}}{{cssxref("<url>")}}The attribute value is parsed as a string that is used inside a CSS url()function.
+ Relative URL are resolved relatively to the original document, not relatively to the style sheet.
+ Leading and trailing spaces are stripped.
The url about:invalid that points to a non-existent document with a generic error condition.
integer {{experimental_inline}}{{cssxref("<integer>")}}The attribute value is parsed as a CSS {{cssxref("<integer>")}}. If it is not valid, that is not an integer or out of the range accepted by the CSS property, the default value is used.
+ Leading and trailing spaces are stripped.
0, or, if 0 is not a valid value for the property, the property's minimum value.
number {{experimental_inline}}{{cssxref("<number>")}}The attribute value is parsed as a CSS {{cssxref("<number>")}}. If it is not valid, that is not a number or out of the range accepted by the CSS property, the default value is used.
+ Leading and trailing spaces are stripped.
0, or, if 0 is not a valid value for the property, the property's minimum value.
length {{experimental_inline}}{{cssxref("<length>")}}The attribute value is parsed as a CSS {{cssxref("<length>")}} dimension, that is including the unit (e.g. 12.5em). If it is not valid, that is not a length or out of the range accepted by the CSS property, the default value is used.
+ If the given unit is a relative length, attr()computes it to an absolute length.
+ Leading and trailing spaces are stripped.
0, or, if 0 is not a valid value for the property, the property's minimum value.
em, ex, px, rem, vw, vh, vmin, vmax, mm, cm, in, pt, or pc {{experimental_inline}}{{cssxref("<length>")}}The attribute value is parsed as a CSS {{cssxref("<number>")}}, that is without the unit (e.g. 12.5), and interpreted as a {{cssxref("<length>")}} with the specified unit. If it is not valid, that is not a number or out of the range accepted by the CSS property, the default value is used.
+ If the given unit is a relative length, attr()computes it to an absolute length.
+ Leading and trailing spaces are stripped.
0, or, if 0 is not a valid value for the property, the property's minimum value.
angle {{experimental_inline}}{{cssxref("<angle>")}}The attribute value is parsed as a CSS {{cssxref("<angle>")}} dimension, that is including the unit (e.g. 30.5deg). If it is not valid, that is not an angle or out of the range accepted by the CSS property, the default value is used.
+ Leading and trailing spaces are stripped.
0deg, or, if 0deg is not a valid value for the property, the property's minimum value.
deg, grad, rad {{experimental_inline}}{{cssxref("<angle>")}}The attribute value is parsed as a CSS {{cssxref("<number>")}}, that is without the unit (e.g. 12.5), and interpreted as an {{cssxref("<angle>")}} with the specified unit. If it is not valid, that is not a number or out of the range accepted by the CSS property, the default value is used.
+ Leading and trailing spaces are stripped.
0deg, or, if 0deg is not a valid value for the property, the property's minimum value.
time {{experimental_inline}}{{cssxref("<time>")}}The attribute value is parsed as a CSS {{cssxref("<time>")}} dimension, that is including the unit (e.g. 30.5ms). If it is not valid, that is not a time or out of the range accepted by the CSS property, the default value is used.
+ Leading and trailing spaces are stripped.
0s, or, if 0s is not a valid value for the property, the property's minimum value.
s, ms {{experimental_inline}}{{cssxref("<time>")}}The attribute value is parsed as a CSS {{cssxref("<number>")}}, that is without the unit (e.g. 12.5), and interpreted as an{{cssxref("<time>")}} with the specified unit. If it is not valid, that is not a number or out of the range accepted by the CSS property, the default value is used.
+ Leading and trailing spaces are stripped.
0s, or, if 0s is not a valid value for the property, the property's minimum value.
frequency {{experimental_inline}}{{cssxref("<frequency>")}}The attribute value is parsed as a CSS {{cssxref("<frequency>")}} dimension, that is including the unit (e.g. 30.5kHz). If it is not valid, that is not a frequency or out of the range accepted by the CSS property, the default value is used.0Hz, or, if 0Hz is not a valid value for the property, the property's minimum value.
Hz, kHz {{experimental_inline}}{{cssxref("<frequency>")}}The attribute value is parsed as a CSS {{cssxref("<number>")}}, that is without the unit (e.g. 12.5), and interpreted as a {{cssxref("<frequency>")}} with the specified unit. If it is not valid, that is not a number or out of the range accepted by the CSS property, the default value is used.
+ Leading and trailing spaces are stripped.
0Hz, or, if 0Hz is not a valid value for the property, the property's minimum value.
% {{experimental_inline}}{{cssxref("<percentage>")}}The attribute value is parsed as a CSS {{cssxref("<number>")}}, that is without the unit (e.g. 12.5), and interpreted as a {{cssxref("<percentage>")}}. If it is not valid, that is not a number or out of the range accepted by the CSS property, the default value is used.
+ If the given value is used as a length, attr()computes it to an absolute length.
+ Leading and trailing spaces are stripped.
0%, or, if 0% is not a valid value for the property, the property's minimum value.
+
+
<fallback> {{experimental_inline}}
+
The value to be used if the associated attribute is missing or contains an invalid value. The fallback value must be valid where attr() is used, even if it is not used, and must not contain another attr() expression. If attr() is not the sole component value of a property, its <fallback> value must be of the type defined by <type-or-unit>. If not set, CSS will use the default value defined for each <type-or-unit>.
+
+ +

Sintaxe formal

+ +
{{csssyntax}}
+ +

Exemplos

+ +

HTML

+ +
<p data-foo="hello">world</p>
+
+ +

CSS

+ +
p::before {
+  content: attr(data-foo) " ";
+}
+
+ +

Resultado

+ +

{{EmbedLiveSample("Examples")}}

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('CSS3 Values', '#attr-notation', 'attr()')}}{{Spec2('CSS3 Values')}}Added two optional parameters; can be used on all properties; may return other values than {{cssxref("<string>")}}. These changes are experimental and may be dropped during the CR phase if browser support is too small.
{{SpecName('CSS2.1', 'generate.html#x18', 'attr()')}}{{Spec2('CSS2.1')}}Limited to the {{cssxref("content")}} property; always return a {{cssxref("<string>")}}.
+ +

Compatibilidade dos Navegadores

+ + + +

{{Compat("css.types.attr")}}

diff --git a/files/pt-br/web/css/backdrop-filter/index.html b/files/pt-br/web/css/backdrop-filter/index.html new file mode 100644 index 0000000000..f693e035d4 --- /dev/null +++ b/files/pt-br/web/css/backdrop-filter/index.html @@ -0,0 +1,140 @@ +--- +title: backdrop-filter +slug: Web/CSS/backdrop-filter +tags: + - Filtros + - efeitos + - iOS + - plano de fundo +translation_of: Web/CSS/backdrop-filter +--- +
{{CSSRef}}{{SeeCompatTable}}
+ +

A propriedade CSS backdrop-filter permite que você aplique efeitos gráficos, como desfoque ou mudança de cores, na área ao fundo de um elemento. Como ela se aplica a tudo que fica atrás do elemento, é preciso deixá-lo (ou o seu plando de fundo) ao menos parcialmente transparente para poder ver o efeito em ação.

+ +
/* Valor de palavra-chave */
+backdrop-filter: none;
+
+/* Filtro com URL para SVG */
+backdrop-filter: url(commonfilters.svg#filter);
+
+/* Valores <filter-function> */
+backdrop-filter: blur(2px);
+backdrop-filter: brightness(60%);
+backdrop-filter: contrast(40%);
+backdrop-filter: drop-shadow(4px 4px 10px blue);
+backdrop-filter: grayscale(30%);
+backdrop-filter: hue-rotate(120deg);
+backdrop-filter: invert(70%);
+backdrop-filter: opacity(20%);
+backdrop-filter: sepia(90%);
+backdrop-filter: saturate(80%);
+
+/* Vários filtros */
+backdrop-filter: url(filters.svg#filter) blur(4px) saturate(150%);
+
+/* Valores globais */
+backdrop-filter: inherit;
+backdrop-filter: initial;
+backdrop-filter: unset;
+
+ +

{{cssinfo}}

+ +

Sintaxe

+ +

Valores

+ +
+
none
+
Nenhum filtro é aplicado ao plano de fundo.
+
<filter-function-list>
+
Uma lista de {{cssxref("<filter-function>")}}s separadas por espaços ou um filtro SVG que será aplicado ao plano de fundo.
+
+ +

Sintaxe formal

+ +
{{csssyntax}}
+ +

Exemplo

+ +

CSS

+ +
.box {
+  background-color: rgba(255, 255, 255, 0.3);
+  border-radius: 5px;
+  font-family: sans-serif;
+  text-align: center;
+  line-height: 1;
+ -webkit-backdrop-filter: blur(10px);
+  backdrop-filter: blur(10px);
+  max-width: 50%;
+  max-height: 50%;
+  padding: 20px 40px;
+}
+
+html,
+body {
+  height: 100%;
+  width: 100%;
+}
+
+body {
+  background-image: url('https://lorempixel.com/400/200/');
+  background-position: center center;
+  background-repeat: no-repeat;
+  background-size: cover;
+}
+
+.container {
+  align-items: center;
+  display: flex;
+  justify-content: center;
+  height: 100%;
+  width: 100%;
+}
+ +

HTML

+ +
<div class="container">
+  <div class="box">
+    <p>backdrop-filter: blur(10px)</p>
+  </div>
+</div>
+
+ +

Resultado

+ +

{{EmbedLiveSample("Example", 600, 400)}}

+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusDescrição
{{SpecName('Filters 2.0', '#BackdropFilterProperty', 'backdrop-filter')}}{{Spec2('Filters 2.0')}}Initial definition.
+ +

Compatibilidade em navegadores

+ + + +

{{Compat("css.properties.backdrop-filter")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/css/backface-visibility/index.html b/files/pt-br/web/css/backface-visibility/index.html new file mode 100644 index 0000000000..7e8fa192e3 --- /dev/null +++ b/files/pt-br/web/css/backface-visibility/index.html @@ -0,0 +1,257 @@ +--- +title: backface-visibility +slug: Web/CSS/backface-visibility +translation_of: Web/CSS/backface-visibility +--- +

{{CSSRef}}{{SeeCompatTable}}

+ +

Sumário

+ +

A propriedade CSS backface-visibility determina se deve ser exibido ou não a parte de trás do elemento para o usuário. A parte de trás de um elemento é sempre um fundo transparente, deixando, quando visível, uma imagem espelho da parte da frente a ser exibida.

+ +

Há casos quando nós não queremos que a parte da frente de um elemento seja visível pela parte de trás, quando estamos fazendo um efeito de giro de cartões (colocando dois elementos lado a lado).

+ +

Esta propriedade não possui nenhum efeito em transformações 2D quando não há nenhum tipo de perspectiva.

+ +

{{cssinfo}}

+ +

Sintaxe

+ +
backface-visibility: visible;
+backface-visibility: hidden;
+
+ +

Valores

+ +

Esta propriedade tem dois valores (exclusivos):

+ + + +

Sintaxe formal

+ +
+
+ +
{{csssyntax}}
+ +

Exemplos

+ +

Cubos com faces transparentes

+ +

Conteúdo HTML

+ +
<table>
+  <tbody>
+    <tr>
+      <th><code>backface-visibility: visible;</code></th>
+      <th><code>backface-visibility: hidden;</code></th>
+    </tr>
+    <tr>
+      <td>
+        <div class="container">
+          <div class="cube showbf">
+            <div class="face front">1</div>
+            <div class="face back">2</div>
+            <div class="face right">3</div>
+            <div class="face left">4</div>
+            <div class="face top">5</div>
+            <div class="face bottom">6</div>
+          </div>
+        </div>
+        <p> Todas as faces são transparentes e há três faces atrás que estão visíveis através das faces da frente.</p>
+      </td>
+      <td>
+        <div class="container">
+          <div class="cube hidebf">
+            <div class="face front">1</div>
+            <div class="face back">2</div>
+            <div class="face right">3</div>
+            <div class="face left">4</div>
+            <div class="face top">5</div>
+            <div class="face bottom">6</div>
+          </div>
+        </div>
+        <p>Nenhuma face é opaca, mas as três faces de trás estarão sempre escondidas agora.</p>
+      </td>
+    </tr>
+  </tbody>
+</table>
+ +

Conteúdo CSS

+ +
/* Shorthand classes that will show or hide the three back faces of the "cube" */
+.hidebf div {
+  backface-visibility: hidden;
+  -webkit-backface-visibility: hidden;
+}
+
+.showbf div {
+  backface-visibility: visible;
+  -webkit-backface-visibility: visible;
+}
+
+/* Define the container div, the cube div, and a generic face */
+.container {
+  width: 150px;
+  height: 150px;
+  margin: 75px 0 0 75px;
+  border: none;
+}
+
+.cube {
+  width: 100%;
+  height: 100%;
+  perspective: 550px;
+  perspective-origin: 150% 150%;
+  transform-style: preserve-3d;
+  -webkit-perspective: 300px;
+  -webkit-perspective-origin: 150% 150%;
+  -webkit-transform-style: preserve-3d;
+}
+
+.face {
+  display: block;
+  position: absolute;
+  width: 100px;
+  height: 100px;
+  border: none;
+  line-height: 100px;
+  font-family: sans-serif;
+  font-size: 60px;
+  color: white;
+  text-align: center;
+}
+
+/* Define each face based on direction */
+.front {
+  background: rgba(0, 0, 0, 0.3);
+  transform: translateZ(50px);
+  -webkit-transform: translateZ(50px);
+}
+
+.back {
+  background: rgba(0, 255, 0, 1);
+  color: black;
+  transform: rotateY(180deg) translateZ(50px);
+  -webkit-transform: rotateY(180deg) translateZ(50px);
+}
+
+.right {
+  background: rgba(196, 0, 0, 0.7);
+  transform: rotateY(90deg) translateZ(50px);
+  -webkit-transform: rotateY(90deg) translateZ(50px);
+}
+
+.left {
+  background: rgba(0, 0, 196, 0.7);
+  transform: rotateY(-90deg) translateZ(50px);
+  -webkit-transform: rotateY(-90deg) translateZ(50px);
+}
+
+.top {
+  background: rgba(196, 196, 0, 0.7);
+  transform: rotateX(90deg) translateZ(50px);
+  -webkit-transform: rotateX(90deg) translateZ(50px)
+}
+
+.bottom {
+  background: rgba(196, 0, 196, 0.7);
+  transform: rotateX(-90deg) translateZ(50px);
+  -webkit-transform: rotateX(-90deg) translateZ(50px);
+}
+
+/* Make the table a little nicer */
+th, p, td {
+  background-color: #EEEEEE;
+  margin: 0px;
+  padding: 6px;
+  font-family: sans-serif;
+  text-align: left;
+}
+ +

Resultado

+ +

{{EmbedLiveSample('Cubos_com_faces_transparentes', 620, 460)}}

+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('CSS3 Transforms', '#backface-visibility-property', 'backface-visibility')}}{{Spec2('CSS3 Transforms')}}Definição Inicial
+ +

Compatibilidade de Browsers

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico12{{property_prefix('-webkit')}}{{CompatGeckoDesktop("10")}}{{property_prefix('-moz')}}
+ {{CompatGeckoDesktop("16")}}
1015{{property_prefix('-webkit')}}{{CompatVersionUnknown}}{{property_prefix('-webkit')}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte Básico3.0{{property_prefix('-webkit')}}{{CompatVersionUnknown}}{{property_prefix('-webkit')}}{{CompatGeckoMobile("10")}}{{property_prefix('-moz')}}
+ {{CompatGeckoMobile("16")}}
8.1
+ 11{{property_prefix('-webkit')}}
{{CompatVersionUnknown}}{{property_prefix('-webkit')}}{{CompatVersionUnknown}}{{property_prefix('-webkit')}}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/css/background-attachment/index.html b/files/pt-br/web/css/background-attachment/index.html new file mode 100644 index 0000000000..977f59e4e7 --- /dev/null +++ b/files/pt-br/web/css/background-attachment/index.html @@ -0,0 +1,214 @@ +--- +title: background-attachment +slug: Web/CSS/background-attachment +translation_of: Web/CSS/background-attachment +--- +
{{CSSRef}}
+ +

Resumo

+ +

Se um {{cssxref("background-image")}} é especificado, a propriedade CSS background-attachment determina se aquela posição da imagem é fixa com o viewport, ou se irá rolar juntamente com o seu bloco.

+ +

{{cssinfo}}

+ +

Sintaxe

+ +
background-attachment: scroll;
+background-attachment: fixed;
+background-attachment: local;
+
+background-attachment: inherit;
+
+ +

Valores

+ +
+
fixed
+
Essa chave significa que o background é fixo em relação ao viewport. Mesmo que um elemento tenha um mecanismo de rolar, o  background ‘fixed’ não movimenta com o elemento.
+
local
+
Essa chave significa que o background é fixo em relação ao conteúdo do elemento: ise ele tem um mecanismo de rolar, o background rola com o conteúdo do elemento, e a área pintada e o posicionamento do background são relativos à área de rolagem do elemento ao invés da borda de fronteira deles.
+
scroll
+
Essa chave significa que o background é fixo em relação ao elemento em si e não rola com seu conteúdo. (É efetivamente ligado à borda do elemento.)
+
+

Formal syntax

+
+
+ +
{{csssyntax}}
+
+ +

Exemplos

+ +

Exemplo simpes

+ +

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

Resultado

+ +

{{EmbedLiveSample("Simple_example")}}

+ +

Suporte de múltiplas imagem de background

+ +

Essa propriedade suporta múltiplas imagens de background. Você pode especificar <attachment> para cada background, separado por vírgulas. Cada imagem é combinada com o correspondente tipo de anexo, do primeiro especificado ao último.

+ +

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

Resultado

+ +

{{EmbedLiveSample("Multiple_background_image_support")}}

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('CSS3 Backgrounds', '#the-background-attachment', 'background-attachment')}}{{Spec2('CSS3 Backgrounds')}}The shorthand property has been extended to support multiple backgrounds and the local value.
{{SpecName('CSS2.1', 'colors.html#propdef-background-attachment', 'background-attachment')}}{{Spec2('CSS2.1')}}Mudança não significativa.
{{SpecName('CSS1', '#background-attachment', 'background-attachment')}}{{Spec2('CSS1')}}Mudança não significativa
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1.0{{CompatGeckoDesktop("1.0")}}4.03.51.0
Multiple backgrounds1.0{{CompatGeckoDesktop("1.9.2")}}9.010.51.3
local4.0{{CompatGeckoDesktop("25")}}9.010.55.0
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support2.1{{CompatGeckoMobile("1.9.2")}}{{CompatUnknown}}10.03.2
Multiple backgrounds2.1{{CompatGeckoMobile("1.9.2")}}{{CompatUnknown}}10.03.2
local{{CompatUnknown}}{{CompatGeckoMobile("25")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/css/background-blend-mode/index.html b/files/pt-br/web/css/background-blend-mode/index.html new file mode 100644 index 0000000000..a75c561838 --- /dev/null +++ b/files/pt-br/web/css/background-blend-mode/index.html @@ -0,0 +1,153 @@ +--- +title: background-blend-mode +slug: Web/CSS/background-blend-mode +tags: + - CSS + - Composição de CSS + - Propriedade CSS +translation_of: Web/CSS/background-blend-mode +--- +
{{CSSRef}}
+ +

A propriedade CSS background-blend-mode descreve como as imagens de fundo do elemento devem se misturar entre si e a cor de fundo do elemento.

+ +
/* Um valor */
+background-blend-mode: normal;
+
+/* Dois valores, um por fundo */
+background-blend-mode: darken, luminosity;
+
+/* Valores globais */
+background-blend-mode: initial;
+background-blend-mode: inherit;
+background-blend-mode: unset;
+
+ +

Os modos de mistura devem ser definidos na mesma ordem que a propriedade CSS {{cssxref ("background-image")}}. Se os comprimentos da lista dos modos de mistura e das imagens de fundo não forem iguais, ele será repetido e/ou truncado até que os comprimentos correspondam.

+ +

{{cssinfo}}

+ +

Sintaxe

+ +

Valores

+ +
+
<blend-mode>
+
É um {{cssxref ("<blend-mode>")}} denotando o modo de mesclagem a ser aplicado. Pode haver vários valores, separados por vírgulas.
+
+ +

Sintaxe formal

+ +
{{csssyntax}}
+ +

Exemplos

+ + + + + + + +

{{ EmbedLiveSample('Examples', "330", "330") }}

+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{ SpecName('Compositing', '#background-blend-mode', 'background-blend-mode') }}{{ Spec2('Compositing') }}Initial definition
+ +

Compatibilidade dos navegadores

+ +

{{CompatibilityTable()}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support35{{CompatGeckoDesktop('30.0')}}{{CompatNo()}}227.1
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo()}}{{CompatGeckoMobile('30.0')}}{{CompatNo()}}228
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/css/background-clip/index.html b/files/pt-br/web/css/background-clip/index.html new file mode 100644 index 0000000000..317d5080c2 --- /dev/null +++ b/files/pt-br/web/css/background-clip/index.html @@ -0,0 +1,247 @@ +--- +title: background-clip +slug: Web/CSS/background-clip +tags: + - CSS clip + - cor de fundo +translation_of: Web/CSS/background-clip +--- +
{{CSSRef}}
+ +

A propriedade CSS background-clip especifica se o fundo de um elemento, seja cor ou imagem, se extende debaixo de sua área de borda, preenchimento ou conteúdo.

+ +

{{EmbedInteractiveExample("pages/css/background-clip.html")}}

+ + + +

Se o elemento não possuir as propriedades {{cssxref("background-image")}} ou {{cssxref("background-color")}} definidas, esta propriedade só terá um efeito visual quando a borda tiver regiões transparentes ou regiões parcialmente opacas (devido ao {{cssxref("border-style")}} ou {{cssxref("border-image")}}); caso contrário a borda encobrirá a diferença.

+ +

{{cssinfo}}

+ +

Sintaxe

+ +
/* Valores de palavra-chave */
+background-clip: border-box;
+background-clip: padding-box;
+background-clip: content-box;
+background-clip: text;
+
+/* Valores globais */
+background-clip: inherit;
+background-clip: initial;
+background-clip: unset;
+ +

Valores

+ +
+
border-box
+
O fundo se extende até fora da fronteira da borda (mas por baixo da borda na ordenação-z).
+
padding-box
+
Nenhum fundo é desenhado abaixo da borda (o fundo se extende até a borda externa do preenchimento).
+
content-box
+
O fundo é desenhado dentro (cortado) a caixa de conteúdo.
+
text {{experimental_inline}}
+
O fundo é desenhado dentro (cortado) do texto aparente.
+
+ +

Sintaxe formal

+ +
{{csssyntax}}
+ +

Exemplos

+ +

Usando border-box

+ +

Conteúdo HTML

+ +
<p>O fundo se extende atrás da borda.</p>
+ +

Conteúdo CSS

+ +
p {
+
+  border: .8em darkviolet;
+  border-style: dotted double;
+  margin: 1em 0;
+  padding: 1.4em;
+  background: linear-gradient(60deg, red, yellow, red, yellow, red);
+  font: 900 1.2em sans-serif;
+  text-decoration: underline;
+  background-clip: border-box;
+}
+ +

Resultado

+ +

{{EmbedLiveSample('Using_border-box', 540, 200)}}

+ +

Usando padding-box

+ +

Conteúdo HTML

+ +
<p>O fundo se extende até dentro da fronteira da borda.</p>
+ +

Conteúdo CSS

+ +
p {
+
+  border: .8em darkviolet;
+  border-style: dotted double;
+  margin: 1em 0;
+  padding: 1.4em;
+  background: linear-gradient(60deg, red, yellow, red, yellow, red);
+  font: 900 1.2em sans-serif;
+  text-decoration: underline;
+  background-clip: padding-box;
+}
+ +

Resultado

+ +

{{EmbedLiveSample('Using_padding-box', 540, 200)}}

+ +

Usando content-box

+ +

Conteúdo HTML

+ +
<p>O fundo se extende somente até o limite da caixa de conteúdo.</p>
+ +

Conteúdo CSS

+ +
p {
+  border: .8em darkviolet;
+  border-style: dotted double;
+  margin: 1em 0;
+  padding: 1.4em;
+  background: linear-gradient(60deg, red, yellow, red, yellow, red);
+  font: 900 1.2em sans-serif;
+  text-decoration: underline;
+  background-clip: content-box;
+}
+ +

Resultado

+ +

{{EmbedLiveSample('Using_content-box', 540, 200)}}

+ +

Usando text

+ +

Conteúdo HTML

+ +
<p>O fundo se extende dentro do texto.</p>
+ +

Conteúdo CSS

+ +
p {
+  border: .8em darkviolet;
+  border-style: dotted double;
+  margin: 1em 0;
+  padding: 1.4em;
+  background: linear-gradient(60deg, red, yellow, red, yellow, red);
+  font: 900 1.2em sans-serif;
+  text-decoration: underline;
+
+  /* Note a necessidade de adicionar trânsparência ao texto*/
+  background-clip: text;
+  -webkit-background-clip: text;
+  color: rgba(0,0,0,.2);
+}
+ +

Resultado

+ +

{{EmbedLiveSample('Using_text', 540, 200)}}

+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('CSS3 Backgrounds', '#the-background-clip', 'background-clip')}}{{Spec2('CSS3 Backgrounds')}}
+ +

Compatibilidade de navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico1.0 [3]{{CompatGeckoDesktop("2.0")}} [1]9.0 [2]10.53.0 (522) [3]
content-box1.0 [3]{{CompatGeckoDesktop("2.0")}} [1]9.0 [2]{{CompatVersionUnknown}}3.0 (522) [3]
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Suporte básico4.1{{CompatGeckoMobile("14")}}7.112.1{{CompatVersionUnknown}}
content-box4.1{{CompatGeckoMobile("14")}}7.112.1{{CompatVersionUnknown}}
+
+ +

[1] Gecko suportava, desde a versão 1.1 até a versão 1.9.2, que correspende ao Firefox 1.0 até 3.6 incluso uma sintaxe diferente e prefixada: -moz-background-clip: padding | border.

+ +

[2] Internet Explorer 7 suportava, mas em outras versões do Internet Explorer ele se comporta como background-clip:padding se overflow: hidden | auto | scroll.

+ +

[3] Webkit também suporta a versão prefixada desta propriedade, e neste caso, em adição as palavras chaves atuais, os sinônimos alternativos são: padding, border, and content.

+ +

Veja também

+ + diff --git a/files/pt-br/web/css/background-color/index.html b/files/pt-br/web/css/background-color/index.html new file mode 100644 index 0000000000..8acca2c755 --- /dev/null +++ b/files/pt-br/web/css/background-color/index.html @@ -0,0 +1,157 @@ +--- +title: background-color +slug: Web/CSS/background-color +translation_of: Web/CSS/background-color +--- +
{{CSSRef}}
+ +

A propriedade CSS background-color define a cor de fundo de um elemento.

+ +
{{EmbedInteractiveExample("pages/css/background-color.html")}}
+ + + +

Sintaxe

+ +
/* Valores em chaves */
+background-color: red;
+background-color: indigo;
+
+/* Valores em Hexadecimais */
+background-color: #bbff00;    /* Totalmente opaco */
+background-color: #bf0;       /* Forma abreviada totalmente opaco */
+background-color: #11ffee00;  /* Totalmente transparente */
+background-color: #1fe0;      /* Forma abreviada totalmente transparente */
+background-color: #11ffeeff;  /* Totalmente opaco */
+background-color: #1fef;      /* Forma abreviada totalmente opaco */
+
+/* Valores em RGB */
+background-color: rgb(255, 255, 128);        /* Totalmente opaco */
+background-color: rgba(117, 190, 218, 0.5);  /* 50% transparente */
+
+/* Valores em HSL */
+background-color: hsl(50, 33%, 25%);         /* Totalmente opaco */
+background-color: hsla(50, 33%, 25%, 0.75);  /* 75% transparente */
+
+/* Valores em chaves especiais */
+background-color: currentcolor;
+background-color: transparent;
+
+/* Valores globais */
+background-color: inherit;
+background-color: initial;
+background-color: unset;
+ +

A propriedade background-color recebe um único valor <color>.

+ +

Valores

+ +
+
{{cssxref("<color>")}}
+
A cor uniforme de fundo. É renderizado atrás de qualquer {{cssxref("background-image")}} especificado, embora a cora ainda continue visible através de qualquer transparência da imagem.
+
+ +

Acessibilidade

+ +

É importante assegurar que o contraste entre a cor de fundo e a cor do texto colocado sobre ele é alta o suficiente para pessoas com condições de baixa visão possam ler o conteúdo da página.

+ +

A cor do contrast é determinada comparando a luminância da cor do texto e da cor de fundo.  Para atender às atuais Diretrizes de Acessibilidade de Conteúdo da Web (WCAG), uma proporção de 4.5:1 é necessária para conteúdo de texto e 3:1 para textos maiores como títulos. Texto grande é definido como 18.66px e negrito ou maior, ou 24px ou maior.

+ + + +

Definição formal

+ +

{{cssinfo}}

+ +

Sintaxe formal

+ +
{{csssyntax}}
+ +

Exemplos

+ +

HTML

+ +
<div class="exampleone">
+  Lorem ipsum dolor sit amet, consectetuer
+</div>
+
+<div class="exampletwo">
+  Lorem ipsum dolor sit amet, consectetuer
+</div>
+
+<div class="exemplothree">
+  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("Examples", 200, 150)}}

+ + + +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationCommentFeedback
{{SpecName('CSS3 Backgrounds', '#background-color', 'background-color')}}Though technically removing the transparent keyword, this doesn't change anything as it has been incorporated as a true {{cssxref("<color>")}}Backgrounds Level 3 GitHub issues
{{SpecName('CSS2.1', 'colors.html#propdef-background-color', 'background-color')}}
{{SpecName('CSS1', '#background-color', 'background-color')}}Initial definition
+ +

Compatibilidade de navegadores

+ + + +

{{Compat("css.properties.background-color")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/css/background-origin/index.html b/files/pt-br/web/css/background-origin/index.html new file mode 100644 index 0000000000..7910395b4a --- /dev/null +++ b/files/pt-br/web/css/background-origin/index.html @@ -0,0 +1,107 @@ +--- +title: background-origin +slug: Web/CSS/background-origin +translation_of: Web/CSS/background-origin +--- +
{{CSSRef}}
+ +

A propriedade CSS background-origin define a área de posicionamento do plano de fundo, isto é, a ponto de origem de uma imagem específica usando a propriedade {{cssxref("background-image")}}.

+ +
{{EmbedInteractiveExample("pages/css/background-origin.html")}}
+ + + +

Note que background-origin é ignorado quando {{cssxref("background-attachment")}} é fixed.

+ +
Nota:  A taquigrafia {{cssxref("background")}} redefine o valor desta propriedade para seu valor inicial se esta não foi específicada.
+ +

Sintaxe

+ +
/* Valores chave */
+background-origin: border-box;
+background-origin: padding-box;
+background-origin: content-box;
+
+/* Valores globais */
+background-origin: inherit;
+background-origin: initial;
+background-origin: unset;
+
+ +

A propriedade background-origin é especificada por uma chave de valores listadas abaixo.

+ +

Valores

+ +
+
border-box
+
O plano de fundo é posicionado relativamente nas bordas do elemento.
+
padding-box
+
O plano de fundo é posicionado relativamente no espaçamento do elemento.
+
content-box
+
O plano de fundo é posicionado relativamente para o conteúdo do elemento.
+
+ +

Sintaxe formal

+ +
{{csssyntax}}
+ +

Exemplos

+ +
.exemplo {
+  border: 10px double;
+  padding: 10px;
+  background: url('image.jpg');
+  background-position: center left;
+  background-origin: content-box;
+}
+
+ +
#exemplo2 {
+  border: 4px solid black;
+  padding: 10px;
+  background: url('image.gif');
+  background-repeat: no-repeat;
+  background-origin: border-box;
+}
+
+ +
div {
+  background-image: url('logo.jpg'), url('mainback.png'); /* Applies two images to the background */
+  background-position: top right, 0px 0px;
+  background-origin: content-box, padding-box;
+}
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('CSS3 Backgrounds', '#the-background-origin', 'background-origin')}}{{Spec2('CSS3 Backgrounds')}}Initial definition.
+ +

{{cssinfo}}

+ +

Compatibilidade de navegador

+ +
+ + +

{{Compat("css.properties.background-origin")}}

+
+ +

Veja também

+ + diff --git a/files/pt-br/web/css/background-position/index.html b/files/pt-br/web/css/background-position/index.html new file mode 100644 index 0000000000..44df4c28a1 --- /dev/null +++ b/files/pt-br/web/css/background-position/index.html @@ -0,0 +1,178 @@ +--- +title: background-position +slug: Web/CSS/background-position +translation_of: Web/CSS/background-position +--- +
{{CSSRef}}
+ +

A propriedade CSS background-position define a posição inicial, relativa a posição de fundo na camada definido por {{cssxref("background-origin")}}, para cada background image definido.

+ +
{{EmbedInteractiveExample("pages/css/background-position.html")}}
+ + + +

Sintaxe

+ +
/* Valores chave */
+background-position: top;
+background-position: bottom;
+background-position: left;
+background-position: right;
+background-position: center;
+
+/* Valores <percentuais> */
+background-position: 25% 75%;
+
+/* valores <espessura> */
+background-position: 0 0;
+background-position: 1cm 2cm;
+background-position: 10ch 8em;
+
+/* Multiplas imagens */
+background-position: 0 0, center;
+
+/* Valores de cantos relativos */
+background-position: bottom 10px right 20px;
+background-position: right 3em bottom 10px;
+background-position: bottom 10px right;
+background-position: top right 10px;
+
+/* Valores globais */
+background-position: inherit;
+background-position: initial;
+background-position: unset;
+
+ +

A propriedade background-position é especificada como um determinado numero de valores de <position> , separados por espaços.

+ +

Values

+ +
+
<position>
+
A {{cssxref("<position>")}}. A position defines an x/y coordinate, to place an item relative to the edges of an element's box. It can be defined using one or two values. If two values are used, the first value represents the horizontal position and the second represents the vertical position. If only one value is specified, the second value is assumed to be center.
+
+

1-value syntax: the value may be:

+ +
    +
  • The keyword value center, which centers the image.
  • +
  • One of the keyword values top, left, bottom, right. This specifies an edge against which to place the item. The other dimension is then set to 50%, so the item is placed in the middle of the edge specified.
  • +
  • A {{cssxref("<length>")}} or {{cssxref("<percentage>")}}. This specifies the X coordinate relative to the left edge, with the Y coordinate set to 50%.
  • +
+ +

2-value syntax: one value defines X and the other defines Y. Each value may be:

+ +
    +
  • One of the keyword values top, left, bottom, right. If left or right are given here, then this defines X and the other given value defines Y. If top or bottom are given, then this defines Y and the other value defines X.
  • +
  • A {{cssxref("<length>")}} or {{cssxref("<percentage>")}}. If the other value is left or right, then this value defines Y, relative to the top edge. If the other value is top or bottom, then this value defines X, relative to the left edge. If both values are <length> or <percentage> values, then the first defines X and the second Y.
  • +
+ +

Note that:

+ +
    +
  • If one value is top or bottom, then the other value may not be top or bottom.
  • +
  • If one value is left or right, then the other value may not be left or right.
  • +
+ +

This means, e.g., that top top and left right are not valid.

+
+
+ +

Formal syntax

+ +
{{csssyntax}}
+ +

Examples

+ +

Each of these three examples uses the {{cssxref("background")}} property to create a yellow, rectangular element containing a star image. In each example, the star is in a different position. The third example illustrates how to specify positions for two different background images within one element.

+ +

HTML

+ +
<div class="exampleone">Example One</div>
+<div class="exampletwo">Example Two</div>
+<div class="examplethree">Example Three</div>
+ +

CSS

+ +
/* Shared among all <div>s */
+div {
+  background-color: #FFEE99;
+  background-repeat: no-repeat;
+  width: 300px;
+  height: 80px;
+  margin-bottom: 12px;
+}
+
+/* These examples use the `background` shorthand property */
+.exampleone {
+  background: url("https://mdn.mozillademos.org/files/11987/startransparent.gif") #FFEE99 2.5cm bottom no-repeat;
+}
+.exampletwo {
+  background: url("https://mdn.mozillademos.org/files/11987/startransparent.gif") #FFEE99 3em 50% no-repeat;
+}
+
+/* Multiple background images: Each image is matched with the
+   corresponding position, from first specified to last. */
+.examplethree {
+  background-image:    url("https://mdn.mozillademos.org/files/11987/startransparent.gif"),
+                       url("https://mdn.mozillademos.org/files/7693/catfront.png");
+  background-position: 0px 0px,
+                       center;
+}
+ +

Result

+ +

{{EmbedLiveSample('Examples', 420, 200)}}

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Backgrounds', '#background-position', 'background-position')}}{{Spec2('CSS3 Backgrounds')}}Adds support for multiple backgrounds and the four-value syntax. Modifies the percentage definition to match implementations.
{{SpecName('CSS2.1', 'colors.html#propdef-background-position', 'background-position')}}{{Spec2('CSS2.1')}}Allows for keyword values and {{cssxref("<length>")}} and {{cssxref("<percentage>")}} values to be mixed.
{{SpecName('CSS1', '#background-position', 'background-position')}}{{Spec2('CSS1')}}Initial definition.
+ +

{{cssinfo}}

+ +

Browser compatibility

+ + + +

{{Compat("css.properties.background-position")}}

+ +

Quantum CSS notes

+ + + +

See also

+ + diff --git a/files/pt-br/web/css/background-size/index.html b/files/pt-br/web/css/background-size/index.html new file mode 100644 index 0000000000..c37b0182b4 --- /dev/null +++ b/files/pt-br/web/css/background-size/index.html @@ -0,0 +1,255 @@ +--- +title: background-size +slug: Web/CSS/background-size +translation_of: Web/CSS/background-size +--- +
{{CSSRef}}
+ +

A propriedade background-size do CSS especifica o tamanho das imagens de fundo. O tamanho da imagem pode ser totalmente ou apenas parcialmente comprimido com o objetivo de preservar sua proporção.

+ +
/* Sintaxe */
+background-size: cover;
+background-size: contain;
+
+/* Sintaxe de um valor */
+/* largura da imagem (height é setado como 'auto') */
+background-size: 50%;
+background-size: 3em;
+background-size: 12px;
+background-size: auto;
+
+/* Sintaxe de dois valores */
+/* Primeiro valor: largura da imagem, segundo valor: altura */
+background-size: 50% auto;
+background-size: 3em 25%;
+background-size: auto 6px;
+background-size: auto auto;
+
+/* Múltiplos valores de backgrounds para a imagem de fundo */
+/* Não confunda com background-size: auto auto */
+background-size: auto, auto;
+background-size: 50%, 25%, 25%;
+background-size: 6px, auto, contain;
+
+/* Valores globais */
+background-size: inherit;
+background-size: initial;
+background-size: unset;
+
+ + + +

{{EmbedLiveSample("background-size", "100%", 300, "", "", "example-outcome-frame")}}

+ +

{{cssinfo}}

+ +

Sintaxe

+ +

O tamanho de uma única imagem de fundo pode ser especificado de três maneiras diferentes:

+ + + +

Para especificar usando width e height, você pode fornecer um ou dois valores:

+ + + +

Cada valor pode ser um <length>, uma <percentage>, ou auto.
+
+ Por exemplo:

+ +
background-size: contain;
+
+background-size: 50%;
+background-size: 3em;
+
+background-size: auto 1em;
+background-size: 50% 25%;
+ +


+ Para especificar o tamanho de fundo para mais de uma imagem, forneça múltiplos tamanhos separados por vírgula:

+ +
background-size: 50% 25%, contain, 3em;
+ +

Valores

+ +
+
<length>
+
Um valor {{cssxref("<length>")}} que ajusta a imagem de fundo para o comprimento especificado na dimensão correspondente. Comprimentos negativos não são permitidos.
+
<percentage>
+
Um valor {{cssxref("<percentage>")}} que ajusta a imagem de fundo na dimensão correspondente com a porcentagem especificada para a área do elemento pai, que é determinado pelo valor {{cssxref("background-origin")}}. A área correspondente ao elemento pai é, por padrão, a área que engloba o conteúdo da caixa e seu respectivo padding; a área pode também ser alterada para englobar apenas o conteúdo ou para a área contendo as bordas, o padding e o conteúdo. Se o {{cssxref("background-attachment","attachment")}} está fixed, a área do elemento pai é a área inteira do janela do navegador, não incluindo a área coberta pelas barras de rolagem (se estiverem presentes). Valores negativos de porcentagem não são permitidos.
+
auto
+
Uma palavra-chave que ajusta a imagem de fundo para tal direção de modo que mantenha a proporção da imagem inalterada.
+
contain
+
Uma palavra-chave que aumenta o máximo possível a imagem mantendo a sua proporção (a imagem não fica esticada). A imagem tenta ocupar o espaço inteiro do container. Quando a imagem e o container tem diferentes dimensões, as áreas não preenchidas (tanto top/bottom ou left/right) são preenchidas com a cor de fundo.
+
cover
+
Uma palavra-chave que é o inverso de contain. Ajusta a imagem o mais largamente possível e mantém sua proporção (a imagem não fica esticada). A imagem "cobre" o container inteiro, tanto em altura como em largura. Quando a imagem e o container têm diferentes dimensões,a imagem ultrapassa os limites do container em qualquer direção, para continuar mantendo a proporção.
+
+ +

A interpretação dos possíveis valores depende das dimensões intrínsecas da imagem (largura e altura) e da proporção intrínseca (proporção da largura e altura).  Um imagem bitmap sempre tem dimensões intrínsecas e uma proporção intrínseca.  Uma imagem pode conter ambas as dimensões intrínsecas (e portanto deve ter uma proporção intrínseca).  Poderá contar também uma ou nenhuma dimensão intrínseca, e portanto pode ou não pode conter uma proporção intrínseca.  Gradients são tratados como imagens sem dimensões ou proporções intrínsecas.

+ +
+

Nota: Esse comportamento mudou no Gecko 8.0 {{geckoRelease("8.0")}}. Antes disso, gradients eram tratados como imagens sem dimensões intrínsecas, porém com uma proporção intrínseca idêntica a da área do elemento pai.

+
+ +

Imagens geradas por elementos usando {{cssxref("-moz-element")}} (que na realidade casa com um elemento) são atualmente tratadas como imagens com as dimensões do elemento, ou da área de posicionamento de fundo se o elemento é SVG, com a proporção intrínseca correspondente.

+ +
Nota: Este não é o comportamento atualmente especificado, que é que as dimensões intrínsecas e a proporção devem ser as do elemento em todos os casos.
+ +

O tamanho renderizado da imagem de fundo é então computado da seguinte forma:

+ +
+
Se ambos os componentes do background-size são especificados e não há auto
+
A imagem de fundo é renderizada no tamanho especificado.
+
Se o background-size é contain ou cover:
+
A imagem é renderizada, preservando sua proporção intrínseca, com o maior tamanho contido, ou cobrindo a área do elemento pai. Se a imagem não tiver uma proporção intrínseca, então ela é renderizada no tamanho da área do elemento pai.
+
Se o background-size é auto ou auto auto:
+
Se a imagem tiver duas dimensões intrínsecas, ela é renderizada nesse tamanho. Se não tiver dimensões intrínsecas e nenhuma proporção intrínseca, ela é renderizada ao tamanho da área do elemento pai. Se não tiver dimensões, mas tiver uma proporção, é processado como se contain tivesse sido especificado. Se a imagem tiver uma dimensão intrínseca e uma proporção, ela é renderizada no tamanho determinado por essa dimensão e a proporção. Se a imagem tiver uma dimensão intrínseca mas nenhuma proporção, ela é processada usando a dimensão intrínseca e a dimensão correspondente da área do elemento pai. +
Nota: imagens SVG tem um atributo preserveAspectRatio que é equivalente ao 'contain'. No Firefox 43, ao contrário do Chrome 52, um background-size especificado explicitamente faz com que preserveAspectRatio seja ignorado.
+
+
Se o background-size tem um componente auto e um componente não auto:
+
Se a imagem tiver uma proporção intrínseca, então use a dimensão especificada. Se a imagem não tiver uma proporção intrínseca, use a dimensão especificada para essa dimensão. Para a outra dimensão, use a dimensão intrínseca correspondente da imagem se houver uma. Se não existe essa dimensão intrínseca, use a dimensão correspondente da área do elemento pai.
+
+ +

Observe que o dimensionamento de fundo para vectors que não possuem dimensões ou proporções intrínsecas ainda não está totalmente implementado em todos os navegadores. Tenha cuidado ao confiar no comportamento descrito acima e teste em vários navegadores (especificamente incluindo versões do Firefox 7 ou anteriores e Firefox 8 ou superior) para ter certeza de que diferentes renderizações são aceitáveis.

+ +

Sintaxe formal

+ +
{{csssyntax}}
+
+ +

Exemplos

+ +

Essa demonstração do background-size: cover e essa demonstração do background-size: contain foram feitas para você abrir em uma nova aba para ver como contain e cover se comportam quando as dimensões da área do elemento pai varia. Essa séria de demonstrações de como background-size funciona e interage com outras propriedades background-* devem ser suficientes para entender como usar background-size sozinho e em conjunto com outras propriedades.

+ +

Notas

+ +

Se você estiver especificando um gradient como plano de fundo e tiver especificado um background-size junto, é melhor não especificar um tamanho que use um único componente setado como auto ou seja especificado usando apenas um valor de largura (por exemplo, background-size: 50%).  A renderização de gradients em tais casos mudou no Firefox 8 e, no momento, geralmente é inconsistente em todos os navegadores, pois nem todos implementam a renderização em total conformidade com a especificação background-size do CSS3 e com a especificação do CSS3 para valores de gradient.

+ +
.bar {
+       width: 50px; height: 100px;
+       background-image: gradient(...);
+
+       /* NÃO RECOMENDADO */
+       background-size: 25px;
+       background-size: 50%;
+       background-size: auto 50px;
+       background-size: auto 50%;
+
+       /* OKAY */
+       background-size: 25px 50px;
+       background-size: 50% 50%;
+}
+
+ +

Observe que, em particular, não é recomendável usar uma dimensão de pixel e uma dimensões auto com um gradient, porque é impossível replicar a renderização nas versões do Firefox antes de 8 e nos navegadores que não implementam a renderização do Firefox 8, sem saber o tamanho exato do elemento cujo plano de fundo está sendo especificado.

+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('CSS3 Backgrounds', '#the-background-size', 'background-size')}}{{Spec2('CSS3 Backgrounds')}}Initial definition
+ +

Compatibilidade de navegadores

+ + + +

{{Compat("css.properties.background-size")}}

+ +

Soluções alternativas

+ +

Para Internet Explorer anterior ao IE8

+ +

Como o Internet Explorer 8 não suporta a propriedade background-size, é possível emular algumas de suas funcionalidades usando a propriedade não padrão -ms-filter:

+ +
-ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='path_relative_to_the_HTML_file', sizingMethod='scale')";
+ +

Isso simula o valor cover.

+ +

No Firefox 3.5

+ +

Enquanto essa propriedade foi adicionada no Firefox 3.6, é possível esticar totalmente a imagem no Firefox 3.5 usando {{cssxref("-moz-border-image")}}.

+ +
.foo {
+  background-image: url(bg-image.png);
+
+  -webkit-background-size: 100% 100%;           /* Safari 3.0 */
+     -moz-background-size: 100% 100%;           /* Gecko 1.9.2 (Firefox 3.6) */
+       -o-background-size: 100% 100%;           /* Opera 9.5 */
+          background-size: 100% 100%;           /* Gecko 2.0 (Firefox 4.0) and other CSS3-compliant browsers */
+
+  -moz-border-image: url(bg-image.png) 0;    /* Gecko 1.9.1 (Firefox 3.5) */
+}
+ +

Veja também

+ + diff --git a/files/pt-br/web/css/background/index.html b/files/pt-br/web/css/background/index.html new file mode 100644 index 0000000000..81390eb8e3 --- /dev/null +++ b/files/pt-br/web/css/background/index.html @@ -0,0 +1,129 @@ +--- +title: background +slug: Web/CSS/background +tags: + - Fundo CSS + - Propriedades CSS + - Referencia +translation_of: Web/CSS/background +--- +
{{CSSRef ( "CSS Background")}}
+ +

Resumo

+ +

A propriedade CSS background é um atalho para definir os valores de fundo individuais em um único lugar na folha de estilo. Background pode ser usado para definir os valores para um ou mais dos seguintes: {{cssxref("background-clip")}}, {{cssxref("background-color")}}, {{cssxref("background-image")}}, {{cssxref("background-origin")}}, {{cssxref("background-position")}} , {{cssxref("background-repeat")}}, {{cssxref("background-size")}} e {{cssxref("background-attachment")}}.

+ +

O fundo CSS propriedade estenográfica atribui valores dados explícitos e conjuntos de propriedades para seus valores iniciais em falta.

+ +

{{cssinfo}}

+ +

Sintaxe

+ +
/ * Usando uma <cor-de-fundo> * /
+background: green;
+
+/ * Usando uma <imagem-de-fundo> e <estilo-de-repetição> * /
+background: url("test.jpg") repeat-y;
+
+/ * Usando uma <box> e <cor-de-fundo> * /
+background: border-box red;
+
+/ * Uma única imagem, centrado e escalado * /
+background: no-repeat center/80% url( "../img/image.png");
+
+ +
Nota: O {{cssxref ( "background-color")}} só pode ser definido no último fundo, como há apenas uma cor de fundo para todo o elemento.
+ +

Valores

+ +

Um ou mais dos seguintes, por qualquer ordem:

+ +
+
<anexo>
+
Veja {{cssxref ( "background-attachment")}}
+
<box>
+
Veja {{cssxref ( "background-clip")}}
+
<cor-de-fundo>
+
Veja {{cssxref ( "background-color")}}
+
<imagem-de-fundo>
+
Veja {{Cssxref ( "background-image")}}
+
<posição>
+
Veja {{cssxref ( "background-position")}}
+
<estilo-de-repetição>
+
Veja {{cssxref ( "background-repeat")}}
+
<tamanho-do-fundo>
+
Veja {{cssxref ( "background-size")}}. Esta propriedade deve ser especificado após <posição> , separados com o caractere '/'.
+
+ +

Sintaxe formal

+ +
{{csssyntax}}
+ +

Exemplos

+ +

HTML

+ +
<p class="Topbanner">
+  céu estrelado<br/>
+  Cintilando Cintilando<br/>
+  Céu estrelado
+</p>
+<p class="atencao">Este é um parágrafo<p>
+ +

CSS

+ +
.atencao { 
+  background: red; 
+}
+
+.Topbanner { 
+  background: url("https://mdn.mozillademos.org/files/11983/starsolid.gif") #00D repeat-y fixed; 
+}
+
+ +

Resultado

+ +

{{EmbedLiveSample ( "Exemplos")}}

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoestadoComente
{{SpecName ( 'Fundos CSS3', '# a-fundo', 'fundo')}}{{Spec2 ( 'Fundos CSS3')}}A propriedade taquigráfica foi estendido para suportar múltiplas origens e a nova {{cssxref("background-size")}}, {{cssxref("background-origem")}} e {{cssxref("background-clip")}} propriedades.
{{SpecName ( 'CSS2.1', '# propdef-fundo colors.html', 'background')}}{{Spec2 ( 'CSS2.1')}}Não ocorreram alterações significativas
{{SpecName ( 'CSS1', '#background', 'background')}}{{Spec2 ( 'CSS1')}}definição inicial
+ +

Compatibilidade do navegador

+ + + +

{{Compat("css.properties.background")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/css/blend-mode/index.html b/files/pt-br/web/css/blend-mode/index.html new file mode 100644 index 0000000000..a32cb2876c --- /dev/null +++ b/files/pt-br/web/css/blend-mode/index.html @@ -0,0 +1,389 @@ +--- +title: +slug: Web/CSS/blend-mode +translation_of: Web/CSS/blend-mode +--- +
{{CSSRef}}
+ +

O tipo básico de dados CSS <blend-mode> (modo de mesclagem) descreve como as cores devem aparecer, quando objetos se sobrepõem. Usa-se nas propriedades {{cssxref("background-blend-mode")}} e {{cssxref("mix-blend-mode")}}.

+ +

Para cada pixel sobreposto, o blend-mode obtém o valor da cor do pixel da frente e do pixel do fundo, faz um cálculo com esses valores e devolve um novo valor de cor.

+ +

Syntaxe

+ +

O tipo básico de dados <blend-mode> é definido usando uma palavra chave escolhida da lista abaixo.

+ +

Valores

+ +
+
normal
+
+

A cor firnal é a do pixel de cima, não importando a cor dor o pixel de baixo.
+ O efeito é como duas folhas de papel opacas se sobrepondo.

+ +
+ +
+ +

{{ EmbedLiveSample('normal_example', "300", "300") }}

+
+
multiply
+
+

A cor final é o resultado da multiplicação das cores de cima e de baixo.
+ Quando uma das camadas for preta, a cor final será preta, enquanto uma camada branca não altera a cor final.
+ O efeito é como duas imagens impressas sobrepostas em um filme transparente.

+ +
+ +
+ +

{{ EmbedLiveSample('multiply_example', "300", "300") }}

+
+
screen
+
+

A cor final é o resultado do inverso de cada cor, multiplicados um pelo outro e depois, o inverso desse resultado.
+ Uma camada preta não altera o resultado final, enquanto uma camada branca resulta na cor final branca.
+ O efeito é como o de duas imagens sobrepostas por um projetor, sobre uma tela de projeção.

+ +
+ +
+ +

{{ EmbedLiveSample('screen_example', "300", "300") }}

+
+
overlay
+
A cor final será o resultado de multiply, se a cor de baixo for mais escura ou screen, se a cor de baixo for mais clara.
+ Este blend-mode é equivalente a hard-light mas com as camadas invertidas. +
+ +
+ +

{{ EmbedLiveSample('overlay_example', "300", "300") }}

+
+
darken
+
+

A cor final é composta pelos valores mais escuros dos canais de cores de cada uma das camadas.

+ +
+ +
+ +

{{ EmbedLiveSample('darken_example', "300", "300") }}

+
+
lighten
+
A cor final é composta pelos valores mais claros de cada um dos canais de cores das camadas.
+
+
+ +
+ +

{{ EmbedLiveSample('lighten_example', "300", "300") }}

+
+
color-dodge
+
A cor final é o resultado da divisão da cor de baixo pelo inverso da cor de cima.
+ Um fundo preto não altera as cores. Uma cor de cima inversa a cor de baixo, resulta em uma cor bastante luminosa.
+ Este blend-mode é similar a screen, mas a cor de cima precisa ser apenas tão clara quanto o inverso da cor de fundo para deixar o resultado muito luminoso.
+
+
+ +
+ +

{{ EmbedLiveSample('color-dodge_example', "300", "300") }}

+
+
color-burn
+
+

A cor final é o inverso da cor do fundo, dividido pelo valor da cor da frente e então inverte-se o resultado final.
+ Se a cor de cima for branca, não haverá alteração. Se a cor de cima for o inverso da cor de baixo, resultará em uma cor preta.
+ Este blend-mode é similar ao multiply, mas a cor de cima precisa apenas ser tão escura quanto o inverso da cor de baixo para fazer o resultado final ser preto.

+ +
+ +
+ +

{{ EmbedLiveSample('color-burn_example', "300", "300") }}

+
+
hard-light
+
+

A cor final é o resultado do multiply se a cor de cima for a mais escura, ou o resultado de screen se a cor de cima for mais clara.
+ Este blend-mode é equivalente ao overlay mas com as camadas invertidas.
+ O efeito é o de iluminar o fundo com um holofote muito forte e intenso.

+ +
+ +
+ +

{{ EmbedLiveSample('hard-light_example', "300", "300") }}

+
+
soft-light
+
+

O resultado final é similar ao de hard-light, porém menos intenso.
+ O efeito é o de iluminar o fundo com um holofote difuso.

+ +
+ +
+ +

{{ EmbedLiveSample('soft-light_example', "300", "300") }}

+
+
difference
+
+

The final color is the result of subtracting the darker of the two colors from the lighter one.
+ A black layer has no effect, while a white layer inverts the other layer's color.

+ +
+ +
+ +

{{ EmbedLiveSample('difference_example', "300", "300") }}

+
+
exclusion
+
+

The final color is similar to difference, but with less contrast.
+ As with difference,  a black layer has no effect, while a white layer inverts the other layer's color.

+ +
+ +
+ +

{{ EmbedLiveSample('exclusion_example', "300", "300") }}

+
+
hue
+
+

The final color has the hue of the top color, while using the saturation and luminosity of the bottom color.

+ +
+ +
+ +

{{ EmbedLiveSample('hue_example', "300", "300") }}

+
+
saturation
+
+

The final color has the saturation of the top color, while using the hue and luminosity of the bottom color.
+ A pure gray backdrop, having no saturation, will have no effect.

+ +
+ +
+ +

{{ EmbedLiveSample('saturation_example', "300", "300") }}

+
+
color
+
+

The final color has the hue and saturation of the top color, while using the luminosity of the bottom color.
+ The effect preserves gray levels and can be used to colorize the foreground.

+ +
+ +
+ +

{{ EmbedLiveSample('color_example', "300", "300") }}

+
+
luminosity
+
+

The final color has the luminosity of the top color, while using the hue and saturation of the bottom color.
+ This blend mode is equivalent to color, but with the layers swapped.

+ +
+ +
+ +

{{ EmbedLiveSample('luminosity_example', "300", "300") }}

+
+
+ +

Interpolation of blend modes

+ +

Changes between blends mode are not interpolated. Any change occurs immediately.

+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('Compositing', '#ltblendmodegt', '<blend-mode>') }}{{ Spec2('Compositing') }}Initial definition.
+ +

Browser Compatibility

+ + + +

{{Compat("css.types.blend-mode")}}

+ +

See also

+ + diff --git a/files/pt-br/web/css/block-size/index.html b/files/pt-br/web/css/block-size/index.html new file mode 100644 index 0000000000..0bab1649ec --- /dev/null +++ b/files/pt-br/web/css/block-size/index.html @@ -0,0 +1,104 @@ +--- +title: block-size +slug: Web/CSS/block-size +tags: + - Propriedade CSS + - Propriedade Lógica CSS + - Referencia + - block-size +translation_of: Web/CSS/block-size +--- +
{{CSSRef}}{{SeeCompatTable}}
+ +

A propriedade CSS block-size define o tamanho horizontal ou vertical de um elemento bloco. Corresponde à propriedade {{cssxref("width")}} ou {{cssxref("height")}}, dependendo do valor do {{cssxref("writing-mode")}}.

+ +
{{EmbedInteractiveExample("pages/css/block-size.html")}} 
+ + + +

Sintaxe

+ +
/* valores <length> */
+block-size: 300px;
+block-size: 25em;
+
+/* valores <percentage> */
+block-size: 75%;
+
+/* valores de Keyword */
+block-size: 25em border-box;
+block-size: 75% content-box;
+block-size: max-content;
+block-size: min-content;
+block-size: available;
+block-size: fit-content;
+block-size: auto;
+
+/* valores globais */
+block-size: inherit;
+block-size: initial;
+block-size: unset;
+
+ +

Se o modo de escrita está orientado verticalmente, o valor do block-size refere-se à largura do elemento; senão, refere-se à altura do elemento. Uma propriedade relacionada é {{cssxref("inline-size")}}, que define as outras dimensões do elemento.

+ +

{{cssinfo}}

+ +

Sintaxe

+ +

Valores

+ +

A propriedade block-size leva os mesmos valores que as propriedades {{cssxref("width")}} e {{cssxref("height")}}.

+ +

Sintaxe formal

+ +
{{csssyntax}}
+ +

Exemplo

+ +

HTML

+ +
<p class="exampleText">Example text</p>
+
+ +

CSS

+ +
.exampleText {
+  writing-mode: vertical-rl;
+  background-color: yellow;
+  block-size: 200px;
+}
+ +

{{EmbedLiveSample("Example")}}

+ +

Especificação

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("CSS Logical Properties", "#logical-dimension-properties", "block-size")}}{{Spec2("CSS Logical Properties")}}Definição inicial
+ +

Browser compatibility

+ + + +

{{Compat("css.properties.block-size")}}

+ +

See also

+ + diff --git a/files/pt-br/web/css/border-left-color/index.html b/files/pt-br/web/css/border-left-color/index.html new file mode 100644 index 0000000000..e9ea7a2fb2 --- /dev/null +++ b/files/pt-br/web/css/border-left-color/index.html @@ -0,0 +1,109 @@ +--- +title: border-left-color +slug: Web/CSS/border-left-color +translation_of: Web/CSS/border-left-color +--- +
{{CSSRef}}
+ +

The border-left-color CSS property sets the color of an element's left border. It can also be set with the shorthand CSS properties {{cssxref("border-color")}} or {{cssxref("border-left")}}.

+ +
{{EmbedInteractiveExample("pages/css/border-left-color.html")}}
+ + + +

Syntax

+ +
/* <color> values */
+border-left-color: red;
+border-left-color: #ffbb00;
+border-left-color: rgb(255, 0, 0);
+border-left-color: hsla(100%, 50%, 25%, 0.75);
+border-left-color: currentcolor;
+border-left-color: transparent;
+
+/* Global values */
+border-left-color: inherit;
+border-left-color: initial;
+border-left-color: unset;
+
+ +

The border-left-color property is specified as a single value.

+ +

Values

+ +
+
{{cssxref("<color>")}}
+
The color of the left border.
+
+ +

Formal syntax

+ +
{{csssyntax}}
+ +

Examples

+ +

A simple div with a border

+ +

HTML

+ +
<div class="mybox">
+  <p>This is a box with a border around it.
+     Note which side of the box is
+     <span class="redtext">red</span>.</p>
+</div>
+ +

CSS

+ +
.mybox {
+    border: solid 0.3em gold;
+    border-left-color: red;
+    width: auto;
+}
+
+.redtext {
+    color: red;
+}
+ +

Result

+ +

{{EmbedLiveSample('A_simple_div_with_a_border')}}

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Backgrounds', '#propdef-border-left-color', 'border-left-color')}}{{Spec2('CSS3 Backgrounds')}}No significant changes, though the transparent keyword, now included in {{cssxref("<color>")}} which has been extended, has been formally removed.
{{SpecName('CSS2.1', 'box.html#propdef-border-left-color', 'border-left-color')}}{{Spec2('CSS2.1')}}Initial definition
+ +

{{cssinfo}}

+ +

Browser compatibility

+ + + +

{{Compat("css.properties.border-left-color")}}

+ +

See also

+ + diff --git a/files/pt-br/web/css/border-left/index.html b/files/pt-br/web/css/border-left/index.html new file mode 100644 index 0000000000..0e83f5098c --- /dev/null +++ b/files/pt-br/web/css/border-left/index.html @@ -0,0 +1,155 @@ +--- +title: border-left +slug: Web/CSS/border-left +translation_of: Web/CSS/border-left +--- +

{{CSSRef}}

+ +

Resumo

+ +

O propriedade border-left CSS é um atalho que define os valores de {{ Cssxref("border-left-color") }}, {{ Cssxref("border-left-style") }}, e {{ Cssxref("border-left-width") }}. Estas propriedades descrevem a borda esquerda de elementos.

+ +

Os três valores da propriedade estenográfica pode ser especificada em qualquer ordem, e um ou dois deles podem ser omitidos.

+ +
Tal como acontece com todas as propriedades abreviadas, fronteira esquerda sempre define os valores de todas as propriedades que podem ser definidas, ainda que não são especificadas. Ele define aqueles que não são especificados para os valores padrão. Isso significa que: +
  border-left-style: dotted;
+  border-left: thick green;
+
+ +

é o mesmo que

+ +
  border-left-style: dotted;
+  border-left: none thick green;
+
+ +

e o valor de {{ Cssxref("border-left-style") }} dado antes border-left é ignorado.

+ +

Uma vez que o valor padrão de {{ Cssxref("border-left-style") }} é none, não especificando o border-style parte do valor significa que a propriedade especifica o valor padrão que é none e não significa nenhum border.

+
+ +

{{cssinfo}}

+ +

Sintaxe

+ +
border-left: 1px;
+border-left: 2px dotted;
+border-left: medium dashed green;
+
+ +

Valores

+ +
+
<br-width> 
+
Veja {{ Cssxref("border-left-width") }}.
+
<br-style> 
+
Veja {{ Cssxref("border-left-style") }}.
+
<color> 
+
Veja {{ Cssxref("border-left-color") }}.
+
+ +

Sintaxe formal

+ +
{{csssyntax}}
+ +

Exemplo

+ +

HTML

+ +
<div class='box'>
+  <p>This box has a border on the left side.</p>
+</div>
+ +

CSS

+ +
.box {
+  background-color: #ffaabb;
+  border-left: 4px solid #000;
+  height: 100px;
+  width: 100px;
+}
+
+.box p {
+  font-weight: bold;
+  text-align: center;
+}
+ +

{{ EmbedLiveSample('Example') }}

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{ SpecName('CSS3 Backgrounds', '#border-left', 'border-left') }}{{ Spec2('CSS3 Backgrounds') }}Não ocorreram alterações diretas, através da alteração dos valores para o {{ cssxref("border-left-color") }} se aplicam a ele.
{{ SpecName('CSS2.1', 'box.html#propdef-border-left', 'border-left') }}{{ Spec2('CSS2.1') }}Sem alterações significativas
{{ SpecName('CSS1', '#border-left', 'border-left') }}{{ Spec2('CSS1') }}Definição inicial
+ +

Compatibilidade do browser

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico1.0{{ CompatGeckoDesktop("1.0") }}43.51.0 (85)
+
+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Suporte básico1.0{{ CompatGeckoMobile("1.0") }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
diff --git a/files/pt-br/web/css/border-radius/index.html b/files/pt-br/web/css/border-radius/index.html new file mode 100644 index 0000000000..1c71af8e01 --- /dev/null +++ b/files/pt-br/web/css/border-radius/index.html @@ -0,0 +1,332 @@ +--- +title: border-radius +slug: Web/CSS/border-radius +tags: + - CSS + - border-radius +translation_of: Web/CSS/border-radius +--- +
{{CSSRef}}
+ +

Sumário

+ +

A propriedade CSS border-radius permite definir como bordas arredondadas são. A curva de cada esquina é definida usando um ou dois raios, definindo sua forma: círculo ou elipse.

+ +

Imagens das esquinas arredondadas com CSS3: Sem esquina arredondada, arredondado usando um arco de círculo, arredondado usando um arco de elípse

+ +

O raio é aplicável a todo o {{Cssxref("background")}}, mesmo se o elemento não tiver borda; a posição exata do recorte é definido pela propriedade {{Cssxref("background-clip")}}.

+ +

Esta propriedade é um shorthand para definir as quatro propriedades {{Cssxref("border-top-left-radius")}}, {{Cssxref("border-top-right-radius")}}, {{Cssxref("border-bottom-right-radius")}} e {{Cssxref("border-bottom-left-radius")}}.

+ +
Como com qualquer propriedade shorthand, valores individuais herdados não são possíveis, isto é, border-radius: 0 0 inherit inherit, que substituiria definições parciais existentes. Neste caso, a propriedade individual longhand deve ser usada.
+ +

{{cssinfo}}

+ +

Sintaxe

+ +
/* A sintaxe do primeiro raio permite de um a quatro valores */
+/* O raio é definido para todos os 4 lados */
+border-radius: 10px;
+
+/* top-left-and-bottom-right | top-right-and-bottom-left */
+border-radius: 10px 5%;
+
+/* top-left | top-right-and-bottom-left | bottom-right */
+border-radius: 2px 4px 2px;
+
+/* top-left | top-right | bottom-right | bottom-left */
+border-radius: 1px 0 3px 4px;
+
+/* A sintaxe do segundo raio permite de um a quatro valores */
+/* (first radius values) / radius */
+border-radius: 10px 5% / 20px;
+
+/* (first radius values) / top-left-and-bottom-right | top-right-and-bottom-left */
+border-radius: 10px 5% / 20px 30px;
+
+/* (first radius values) / top-left | top-right-and-bottom-left | bottom-right */
+border-radius: 10px 5px 2em / 20px 25px 30%;
+
+/* (first radius values) / top-left | top-right | bottom-right | bottom-left */
+border-radius: 10px 5% / 20px 25em 30px 35em;
+
+border-radius: inherit;
+
+ +

Valores

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
radiusall-corner.pngIs a {{cssxref("<length>")}} or a {{cssxref("<percentage>")}} denoting a radius to use for the border in each corner of the border. It is used only in the one-value syntax.
top-left-and-bottom-righttop-left-bottom-right.pngIs a {{cssxref("<length>")}} or a {{cssxref("<percentage>")}} denoting a radius to use for the border in the top-left and bottom-right corners of the element's box. It is used only in the two-value syntax.
top-right-and-bottom-lefttop-right-bottom-left.pngIs a {{cssxref("<length>")}} or a {{cssxref("<percentage>")}} denoting a radius to use for the border in the top-right and bottom-left corners of the element's box. It is used only in the two- and three-value syntaxes.
top-lefttop-left.pngIs a {{cssxref("<length>")}} or a {{cssxref("<percentage>")}} denoting a radius to use for the border in the top-left corner of the element's box. It is used only in the three- and four-value syntaxes.
top-righttop-right.pngIs a {{cssxref("<length>")}} or a {{cssxref("<percentage>")}} denoting a radius to use for the border in the top-right corner of the element's box. It is used only in the four-value syntax.
bottom-rightbottom-rigth.pngIs a {{cssxref("<length>")}} or a {{cssxref("<percentage>")}} denoting a radius to use for the border in the bottom-right corner of the element's box. It is used only in the three- and four-value syntaxes.
bottom-leftbottom-left.pngIs a {{cssxref("<length>")}} or a {{cssxref("<percentage>")}} denoting a radius to use for the border in the bottom-left corner of the element's box. It is used only in the four-value syntax.
inherit Is a keyword indicating that all four values are inherited from their parent's element calculated value.
+ +
+
<length>
+
Denotes the size of the circle radius or the semi-major and semi-minor axes of the ellipsis. It can be expressed in any unit allowed by the CSS {{cssxref("<length>")}} data types. Negative values are invalid.
+
<percentage>
+
Denotes the size of the circle radius, or the semi-major and semi-minor axes of the ellipsis, using percentage values. Percentages for the horizontal axis refer to the width of the box, percentages for the vertical axis refer to the height of the box. Negative values are invalid.
+
+ +

For example:

+ +
border-radius: 1em/5em;
+
+/* is equivalent to */
+
+border-top-left-radius:     1em 5em;
+border-top-right-radius:    1em 5em;
+border-bottom-right-radius: 1em 5em;
+border-bottom-left-radius:  1em 5em;
+
+ +
border-radius: 4px 3px 6px / 2px 4px;
+
+/* is equivalent to: */
+
+border-top-left-radius:     4px 2px;
+border-top-right-radius:    3px 4px;
+border-bottom-right-radius: 6px 2px;
+border-bottom-left-radius:  3px 4px;
+
+ +

Sintaxe formal

+ +
{{csssyntax}}
+ +

Examples

+ +
  border: solid 10px;
+  /* the border will curve into a 'D' */
+  border-radius: 10px 40px 40px 10px;
+
+
+ +
  border: groove 1em red;
+  border-radius: 2em;
+
+ +
  background: gold;
+  border: ridge gold;
+  border-radius: 13em/3em;
+
+ +
  border: none;
+  border-radius: 40px 10px;
+
+ +
  border: none;
+  border-radius: 50%;
+
+ +

Live Samples

+ +

Sample 1 : http://jsfiddle.net/Tripad/qnGKj/2/

+ +

Sample 2 : http://jsfiddle.net/Tripad/qnGKj/3/

+ +

Sample 3 : http://jsfiddle.net/Tripad/qnGKj/4/

+ +

Sample 4 : http://jsfiddle.net/Tripad/qnGKj/5/

+ +

Sample 5 : http://jsfiddle.net/Tripad/qnGKj/6/

+ +

Notas

+ + + +

Especificações

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Backgrounds', '#border-radius', 'border-radius')}}{{Spec2('CSS3 Backgrounds')}}Initial definition
+ +

Compatibilidade

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Basic support +

{{CompatGeckoDesktop("1.0")}}{{property_prefix("-moz")}}[1]
+ {{CompatGeckoDesktop("2.0")}}[10]

+
1.0{{property_prefix("-webkit")}}
+ 4.0[9]
9.010.5[8]3.0{{property_prefix("-webkit")}}
+ 5.0[9]
Elliptical borders{{CompatGeckoDesktop("1.9.1")}}{{CompatVersionUnknown}}[7]{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}[7]
4 values for 4 corners{{CompatVersionUnknown}}4.0[6]{{CompatVersionUnknown}}{{CompatVersionUnknown}}5.0[6]
Percentages{{CompatVersionUnknown}}[5]
+ {{CompatGeckoDesktop("2.0")}}
{{CompatVersionUnknown}}[2]{{CompatVersionUnknown}}11.5[3]5.1[2]
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureFirefox Mobile (Gecko)iOS SafariOpera MiniOpera MobileAndroid Browser
Basic support{{CompatVersionUnknown}}[10]3.2{{property_prefix("-webkit")}}{{CompatNo}}{{CompatNo}}2.1{{property_prefix("-webkit")}}
Elliptical borders{{CompatVersionUnknown}}[10]{{CompatUnknown}}{{CompatNo}}{{CompatNo}}{{CompatUnknown}}
4 values for 4 corners{{CompatVersionUnknown}}[10]{{CompatUnknown}}{{CompatNo}}{{CompatNo}}{{CompatUnknown}}
Percentages{{CompatVersionUnknown}}[10]{{CompatVersionUnknown}}[4]{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}[4]
+
+ +

[1] In Gecko 2.0 {{geckoRelease("2.0")}} -moz-border-radius was renamed to border-radius; -moz-border-radius was supported as an alias until Gecko 12.0 {{geckoRelease("12.0")}}. In order to conform to the CSS3 standard, Gecko 2.0 changes the handling of {{cssxref("<percentage>")}} values to match the specification. You can specify an ellipse as border on an arbitrary sized element just with border-radius: 50%;. Gecko 2.0 also makes rounded corners clip content and images (if {{cssxref("overflow")}}: visible is not set)

+ +

Support for the prefixed version (-moz-border-radius) was removed in Gecko 13.0 {{geckoRelease("13.0")}}.

+ +

[2] <percentage> values are not supported in older Chrome and Safari versions (it was fixed in Sepember 2010).

+ +

[3] The implementation of <percentage> values was buggy in Opera prior to 11.50.

+ +

[4] <percentage> values are not supported in iOS versions prior to 5 and Android versions prior to WebKit 532.

+ +

[5] <percentage> values are implemented in a non-standard way prior to Gecko 2.0. Both horizontal and vertical radii were relative to the width of the border box.

+ +

[6] Safari and Chrome versions prior to WebKit 532.5 support only one value for all four corners. For different radii the {{cssxref("border-top-left-radius", "border-top-left-radius", "#Examples")}} long form properties must be used.

+ +

[7] Safari and Chrome versions prior to WebKit 532.5 don't support the slash / notation. If two values are specified, an elliptical border is drawn on all four corners. -webkit-border-radius: 40px 10px; is equivalent to border-radius: 40px/10px;.

+ +

[8] In Opera prior to version 11.60, applying border-radius to replaced elements will not have rounded corners.

+ +

[9] Current Chrome and Safari versions ignore {{cssxref("border-radius")}} on {{HTMLElement("select")}} elements unless {{cssxref("-webkit-appearance")}} is overridden to an appropriate value.

+ +

[10] Prior to Gecko 50.0 {{geckoRelease("50.0")}}, border styles of rounded corners (with {{cssxref("border-radius")}}) were always rendered as if border-style was solid. This has been fixed in Gecko 50.0.

+ +

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.

+ +

Veja também

+ + diff --git a/files/pt-br/web/css/box-shadow/index.html b/files/pt-br/web/css/box-shadow/index.html new file mode 100644 index 0000000000..e94edec82e --- /dev/null +++ b/files/pt-br/web/css/box-shadow/index.html @@ -0,0 +1,265 @@ +--- +title: box-shadow +slug: Web/CSS/box-shadow +translation_of: Web/CSS/box-shadow +--- +
{{CSSRef}}
+ +

O box-shadow é uma propriedade do CSS, é utilizado para adicionar efeitos de sombra em volta de um elemento. Você pode especificar mais de um efeito, os separando com virgulas. Uma box-shadow é descrita pelo deslocamentos (offset) X e Y em relação ao elemento, desfoco e propagação do raio e cor.

+ +
/* offset-x | offset-y | color */
+box-shadow: 60px -16px teal;
+
+/* offset-x | offset-y | blur-radius | color */
+box-shadow: 10px 5px 5px black;
+
+/* offset-x | offset-y | blur-radius | spread-radius | color */
+box-shadow: 2px 2px 2px 1px rgba(0, 0, 0, 0.2);
+
+/* inset | offset-x | offset-y | color */
+box-shadow: inset 5em 1em gold;
+
+/* Any number of shadows, separated by commas */
+box-shadow: 3px 3px red, -1em 0 0.4em olive;
+
+/* Global keywords */
+box-shadow: inherit;
+box-shadow: initial;
+box-shadow: unset;
+
+ +
box-shadow: 60px -16px teal;
+ +
box-shadow: 10px 5px 5px black;
+ +
box-shadow: 3px 3px red, -1em 0 0.4em olive;
+ +
box-shadow: inset 5em 1em gold;
+ +
box-shadow: 0 0 1em gold;
+ +
box-shadow: inset 0 0 1em gold;
+ +
box-shadow: inset 0 0 1em gold, 0 0 1em red;
+ +
+ +

A propriedade box-shadow permite que você adicione uma sombra em quase qualquer elemento. Se um {{cssxref ("border-radius")}} for especificado no elemento com uma box-shadow, a sombra assume os mesmos cantos arredondados. O comando z-ordering de múltiplas box-shadows é o mesmo que múltiplas text shadows (a primeira sombra especificada está na parte superior).

+ +

Box-shadow generator é uma ferrament interativa qu permite a criação de box-shadow.

+ +

{{cssinfo}}

+ +

Sintaxe

+ +

Especificando uma única box-shadow usando:

+ + + +

Para especificar mais de uma sombra, separe-as com virgula.

+ +

Valores

+ +
+
inset
+
Se não for especificado, a sombra ganha o efeito de como se a caixa fosse aumentada acima do conteúdo).
+ A presença da palavra-chave inset muda a sombra para dentro da moldura (como se o conteúdo estivesse pressionado dentro da caixa). As sombras de inserção são desenhadas dentro da borda (mesmo as transparentes), acima do plano de fundo, mas abaixo do conteúdo.
+
<offset-x> <offset-y>
+
Existem dois valores {{cssxref("<length>")}}  para configurar o desvio (offset) da sombra:
+
<offset-x> especifica a distância horizontal. Valores negativos colocarão a sombra à esquerda do elemento.
+
<offset-y> especifca a distância vertical. Valores negativos colocam a sombra acima do elemento.
+
Consulte {{cssxref("<length>")}} para as unidades disponíveis.
+
Se ambos os valores forem 0, a sombra será posicionada atrás do elemento (e poderá gerar um efeito de desfocagem caso <blur-radius> e/ou <spread-radius> estiverem configurados).
+
<blur-radius>
+
Este é um terceiro valor para {{cssxref("<length>")}}. Quanto maior for este valor, maior o efeito de desfocagem, desta forma a sombra se tornará maior e mais clara. Valores negativos não são permitidos. Se não for especificado, o valor padrão é 0 (os limites da sombra serão retos). A especificação não inclui um algoritmo exato de como o raio de esmaecimento deve ser calculado, no entanto, descreve o seguinte:
+
+
...para uma sombra com bordas longas e retas, deverá ser criada uma transição de cor do comprimento da distância de desfocagem que é perpendicular e centralizada com as bordas da sombra, e isto deve variar da cor total da sombra do seu ponto central até totalmente transparente no ponto final fora dela.
+
+
<spread-radius>
+
Este é um quarto valor de {{cssxref("<length>")}}. Valores positivos farão com que a sombra expanda e cresça maior, valores negativos farão com que a sombra encolha. Se não for especificado, o valor padrão é 0 (a sombra terá o mesmo tamanho do elemento)
+
<color>
+
Consulte {{cssxref("<color>")}} para possiveis palavras-chave e notações. Se não for especificada, a cor que será utilizada vai depender do navegador - geralmente é o valor da propriedade {{cssxref("color")}}, mas tenha em mente que o Safari atualmente imprime uma sombra transparente neste caso.
+
+ +

Interpolação

+ +

Each shadow in the list (treating none as a 0-length list) is interpolated via the color (as color) component, and x, y, blur, and (when appropriate) spread (as length) components. For each shadow, if both input shadows are or are not inset, then the interpolated shadow must match the input shadows in that regard. If any pair of input shadows has one inset and the other not inset, the entire shadow list is uninterpolable. If the lists of shadows have different lengths, then the shorter list is padded at the end with shadows whose color is transparent, all lengths are 0, and whose inset (or not) matches the longer list.

+ +

Formal syntax

+ +
{{csssyntax}}
+ +

Live examples

+ + + +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Backgrounds', '#box-shadow', 'box-shadow')}}{{Spec2('CSS3 Backgrounds')}}Initial definition
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support10.0[1]
+ 1.0{{property_prefix("-webkit")}}
{{CompatVersionUnknown}}{{CompatGeckoDesktop("2.0")}}[3]
+ {{CompatGeckoDesktop("1.9.1")}}{{property_prefix("-moz")}}
9.0[2]10.5[1]5.1[1]
+ 3.0 {{property_prefix("-webkit")}}
Multiple shadows10.0
+ 1.0{{property_prefix("-webkit")}}
{{CompatVersionUnknown}}{{CompatGeckoDesktop("2.0")}}
+ {{CompatGeckoDesktop("1.9.1")}}{{property_prefix("-moz")}}
9.010.55.1
+ 3.0 {{property_prefix("-webkit")}}
inset keyword10.0
+ 4.0{{property_prefix("-webkit")}}
{{CompatVersionUnknown}}{{CompatGeckoDesktop("2.0")}}
+ {{CompatGeckoDesktop("1.9.1")}}{{property_prefix("-moz")}}
9.010.55.1
+ 5.0 {{property_prefix("-webkit")}}
Spread radius10.0
+ 4.0{{property_prefix("-webkit")}}
{{CompatVersionUnknown}}{{CompatGeckoDesktop("2.0")}}
+ {{CompatGeckoDesktop("1.9.1")}}{{property_prefix("-moz")}}
9.010.55.1
+ 5.0 {{property_prefix("-webkit")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureEdgeSafari MobileOpera MiniOpera MobileAndroid
Basic support{{CompatVersionUnknown}} +

5.0[1]
+ {{CompatVersionUnknown }}{{ property_prefix("-webkit")}}

+
{{CompatUnknown}}{{CompatVersionUnknown }}[1]{{CompatVersionUnknown }}{{property_prefix("-webkit")}}[1]
Multiple shadows{{CompatVersionUnknown}}5.0
+ {{CompatVersionUnknown }}{{ property_prefix("-webkit")}}
{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
inset keyword{{CompatVersionUnknown}}5.0
+ {{CompatVersionUnknown }}{{ property_prefix("-webkit")}}
{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Spread radius{{CompatVersionUnknown}}5.0
+ {{CompatVersionUnknown }}{{ property_prefix("-webkit")}}
{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Shadows affect layout in older Gecko, Presto, and WebKit; e.g. if you cast an outer shadow to a box with a width of 100%, you'll see a scrollbar.

+ +

[2] Since version 5.5, Internet Explorer supports Microsoft's DropShadow and Shadow Filter. You can use this proprietary extension to cast a drop shadow (though the syntax and the effect are different from CSS3). In order to get box-shadow in IE9 or later, you need to set {{cssxref("border-collapse")}} to separate.

+ +

[3] Gecko 13 {{geckoRelease(13)}} removed support for -moz-box-shadow. Since then, only the unprefixed version is supported. Shadows affect layout in older Gecko, Presto, and WebKit; e.g. if you cast an outer shadow to a box with a width of 100%, you'll see a scrollbar.

+ +

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.

+ +

See also

+ + diff --git a/files/pt-br/web/css/box-sizing/index.html b/files/pt-br/web/css/box-sizing/index.html new file mode 100644 index 0000000000..2d2edba616 --- /dev/null +++ b/files/pt-br/web/css/box-sizing/index.html @@ -0,0 +1,71 @@ +--- +title: box-sizing +slug: Web/CSS/box-sizing +tags: + - CSS + - Propriedades + - Web +translation_of: Web/CSS/box-sizing +--- +

A propriedade CSS box-sizing é utilizada para alterar a propriedade padrão da box model, usada para calcular larguras (widths) e alturas (heights) dos elementos. É possível usar essa propriedade para emular o comportamento dos navegadores (browsers) que não suportam corretamente a especificação da propriedade CSS box model.

+ +

Sintaxe

+ +
Sintaxe formal: {{csssyntax("box-sizing")}}
+
+ +
box-sizing: content-box
+box-sizing: border-box
+
+box-sizing: inherit
+
+ +

Valores

+ +
+
content-box
+
Essa é o estilo padrão, conforme especificado pela norma CSS. As propriedades {{Cssxref("width")}} (largura) e {{Cssxref("height")}} (altura) são medidas incluindo só o conteúdo, mas não o padding, border ou margin. Nota: Padding, border e margin serão fora da box. Exemplo.: Se .box {width: 350px} então se você aplicar uma propriedade {border: 10px solid black;} o resultado renderizado no navegador (browser) será .box {width: 370px;}
+
padding-box{{experimental_inline}} {{obsolete_inline}}
+
As propriedades de largura ({{Cssxref("width")}}) e de altura ({{Cssxref("height")}}) incluem o tamanho padding size, mas não incluem a propriedade border ou margem.
+
border-box
+
As propriedades de largura ({{Cssxref("width")}}) e de altura ({{Cssxref("height")}}) incluem o tamanho padding size e a propriedade border, mas não incluem a propriedade margin.
+
+ +

Exemplos

+ +
/* funciona em Firefox, WebKit, Opera and IE8+ */
+/* exemplo de uso no navegador Firefox */
+
+.exemplo {
+  -moz-box-sizing: border-box;
+       box-sizing: border-box;
+}
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoSituaçãoComentário
{{SpecName('CSS3 Basic UI', '#box-sizing', 'box-sizing')}}{{Spec2('CSS3 Basic UI')}}
+ +

Compatibilidade dos navegadores (browsers)

+ +

{{Compat("css.properties.box-sizing")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/css/box_model/index.html b/files/pt-br/web/css/box_model/index.html new file mode 100644 index 0000000000..8c0db35cf6 --- /dev/null +++ b/files/pt-br/web/css/box_model/index.html @@ -0,0 +1,62 @@ +--- +title: Box model +slug: Web/CSS/box_model +translation_of: Web/CSS/CSS_Box_Model/Introduction_to_the_CSS_box_model +--- +

Resumo

+ +

Em uma página WEB, cada elemento é representado como um box retangular. Determinar o tamanho, propriedades - como sua cor, fundo, estilo das bordas - e a posição desses boxes é o objetivo do mecanismo de renderização.

+ +

No CSS, cada um desses boxes retangulares é descrita usando o box model padrão. Este modelo descreve o conteúdo do espaço ocupado por um elemento. Cada box possui 4 edges: margin edge, border edge, padding edge e content edge.

+ +

CSS Box model

+ +

A área de conteúdo (content area) é a área ocupada pelo conteúdo real do elemento. Ele frequentamente possui um fundo, uma cor de fonte ou uma imagem (nessa ordem, uma imagem opaca esconde a cor de fundo) e é localizada dentro do content edge; suas dimensões são a largura do conteúdo, ou largura do box de conteúdo, e altura do conteúdo, ou altura do box de conteúdo.

+ +

Se a propriedade CSS {{ cssxref("box-sizing") }} está configurada como padrão, as propriedades CSS {{ cssxref("width") }}, {{ cssxref("min-width") }}, {{ cssxref("max-width") }}, {{ cssxref("height") }}, {{ cssxref("min-height") }} e {{ cssxref("max-height") }} controlam o tamanho do conteúdo.

+ +

A área de preenchimento (padding area) estende-se para a borda em torno do enchimento. Quando a área de conteúdo tem um fundo, cor ou imagem, isso será estendido para a área de preenchimento, por esse motivo, você pode pensar o preenchimento como a extensão do conteúdo. O preenchimento está localizado dentro do padding edge, e suas dimensões são a largura do padding-box e a altura do padding-box.

+ +

O espaço entre os edges de preenchimento e conteúdo podem ser controlados utilizando as seguintes propriedades CSS {{ cssxref("padding-top") }}, {{ cssxref("padding-right") }}, {{ cssxref("padding-bottom") }}, {{ cssxref("padding-left") }} e na forma generalizada {{ cssxref("padding") }}.

+ +

A área de borda (border area) estende a área de preenchimento para a área que contém as bordas. Esta é a área de dentro do border edge, e suas dimensões são a largura e a altura do border-box. Esta área depende do tamanho da borda que está definido pela propriedade {{ cssxref("border-width") }} ou pela propriedade {{ cssxref("border") }}.

+ +

A área de margem (margin area) estende a área de borda com um espaço vazio utilizado para separar o elemento dos elementos vizinhos. Esta é a área de dentro do margin edge, e suas dimensões são a largura e a altura do margin-box.

+ +

O tamanho da área de margem é controlada utilizando as seguintes propriedades CSS {{ cssxref("margin-top") }}, {{ cssxref("margin-right") }}, {{ cssxref("margin-bottom") }}, {{ cssxref("margin-left") }} e na forma generalizada {{ cssxref("margin") }}.

+ +

Quando ocorre um colapso de margens, a área de margem não está claramente definida, uma vez que as margens são compartilhadas entre os boxes.

+ +

Finalmente, note que, para elementos não substituídos inline, o total de espaço ocupado (para a altura da linha) é determinado pela propriedade {{ cssxref('line-height') }}, mesmo que a borda e o padding aparecerem visualmente em torno do conteúdo.

+ +

Especificação

+ + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{ SpecName("CSS2.1","box.html#box-dimensions")}}{{ Spec2('CSS2.1') }}Embora mais precisamente formulada, não existem mudanças práticas
{{ SpecName("CSS1","#formatting-model")}}{{ Spec2('CSS1') }} 
+ +

Veja também

+ + diff --git a/files/pt-br/web/css/break-after/index.html b/files/pt-br/web/css/break-after/index.html new file mode 100644 index 0000000000..da446b6402 --- /dev/null +++ b/files/pt-br/web/css/break-after/index.html @@ -0,0 +1,187 @@ +--- +title: break-after +slug: Web/CSS/break-after +translation_of: Web/CSS/break-after +--- +
{{CSSRef}}
+ +

A propriedade break-after do CSS configura como uma quebra de página, coluna ou região deve se comportar após renderizar um elemento. Se nenhum elemento foi renderizado, a propriedade é ignorada.

+ +
/* Generic break values */
+break-after: auto;
+break-after: avoid;
+break-after: always;
+break-after: all;
+
+/* Page break values */
+break-after: avoid-page;
+break-after: page;
+break-after: left;
+break-after: right;
+break-after: recto;
+break-after: verso;
+
+/* Column break values */
+break-after: avoid-column;
+break-after: column;
+
+/* Region break values */
+break-after: avoid-region;
+break-after: region;
+
+/* Global values */
+break-after: inherit;
+break-after: initial;
+break-after: unset;
+
+ +

Each possible break point (in other words, each element boundary) is affected by three properties: the break-after value of the previous element, the {{cssxref("break-before")}} value of the next element, and the {{cssxref("break-inside")}} value of the containing element.

+ +

To determine if a break must be done, the following rules are applied:

+ +
    +
  1. If any of the three concerned values is a forced break value (always, left, right, page, column, or region), it has precedence. If more than one of them are such a break, the one of the element that appears the latest in the flow is taken (i.e., the break-before value has precedence over the break-after value, which itself has precedence over the break-inside value).
  2. +
  3. If any of the three concerned values is an avoid break value (avoid, avoid-page, avoid-region, or avoid-column), no such break will be applied at that point.
  4. +
+ +

Once forced breaks have been applied, soft breaks may be added if needed, but not on element boundaries that resolve in a corresponding avoid value.

+ +

{{cssinfo}}

+ +

Syntax

+ +

The break-after property is specified as one of the keyword values from the list below.

+ +

Values

+ +

Generic break values

+ +
+
auto
+
Allows, but does not force, any break (page, column, or region) to be inserted right after the principal box.
+
avoid
+
Avoids any break (page, column, or region) from being inserted right after the principal box.
+
always {{experimental_inline}}
+
Forces a page break right after the principal box. The type of this break is that of the immediately-containing fragmentation context. If we are inside a multicol container then it would force a column break, inside paged media (but not inside a multicol container) a page break.
+
all {{experimental_inline}}
+
Forces a page break right after the principal box. Breaking through all possible fragmentation contexts. So a break inside a multicol container, which was inside a page container would force a column and page break.
+
+ +

Page break values

+ +
+
avoid-page
+
Avoids any page break right after the principal box.
+
page
+
Forces a page break right after the principal box.
+
left
+
Forces one or two page breaks right after the principal box, whichever will make the next page into a left page.
+
right
+
Forces one or two page breaks right after the principal box, whichever will make the next page into a right page.
+
recto {{experimental_inline}}
+
Forces one or two page breaks right after the principal box, whichever will make the next page into a recto page. (A recto page is a right page in a left-to-right spread or a left page in a right-to-left spread.)
+
verso {{experimental_inline}}
+
Forces one or two page breaks right after the principal box, whichever will make the next page into a verso page. (A verso page is a left page in a left-to-right spread or a left right in a right-to-left spread.)
+
+ +

Column break values

+ +
+
avoid-column
+
Avoids any column break right after the principal box.
+
column
+
Forces a column break right after the principal box.
+
+ +

Region break values

+ +
+
avoid-region {{experimental_inline}}
+
Avoids any region break right after the principal box.
+
region {{experimental_inline}}
+
Forces a region break right after the principal box.
+
+ +

Formal syntax

+ +
{{csssyntax}}
+ +

Page break aliases

+ +

For compatibility reasons, the legacy {{cssxref("page-break-after")}} property should be treated by browsers as an alias of break-after. This ensures that sites using page-break-after continue to work as designed. A subset of values should be aliased as follows:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
page-break-afterbreak-after
autoauto
leftleft
rightright
avoidavoid
alwayspage
+ +
+

The always value of page-break-* was implemented by browsers as a page break, and not as a column break. Therefore the aliasing is to page, rather than the always value in the Level 4 spec.

+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Fragmentation', '#break-between', 'break-after')}}{{Spec2('CSS3 Fragmentation')}}Adds the recto and verso keywords. Changes the media type of this property from paged to {{xref_cssvisual}}. Defines the breaking algorithm with different kinds of breaks.
{{SpecName('CSS3 Regions', '#region-flow-break', 'break-after')}}{{Spec2('CSS3 Regions')}}Extends the property to handle region breaks. Adds the avoid-region and region keywords.
{{SpecName('CSS3 Multicol', '#break-before-break-after-break-inside', 'break-after')}}{{Spec2('CSS3 Multicol')}}Initial definition. Extends the CSS 2.1 {{cssxref("page-break-after")}} property to handle both page and column breaks.
+ +

Browser compatibility

+ + + +

Support in multi-column layout

+ +

{{Compat("css.properties.break-after.multicol_context")}}

+ +

Support in paged media

+ +

{{Compat("css.properties.break-after.paged_context")}}

diff --git a/files/pt-br/web/css/calc()/index.html b/files/pt-br/web/css/calc()/index.html new file mode 100644 index 0000000000..b765f7c051 --- /dev/null +++ b/files/pt-br/web/css/calc()/index.html @@ -0,0 +1,164 @@ +--- +title: calc() +slug: Web/CSS/calc() +tags: + - CSS + - Calculate + - Função + - Função CSS + - Layout + - Web + - calc +translation_of: Web/CSS/calc() +--- +
{{CSSRef}}
+ +

A função  calc() CSS permite você executar cálculos quando especificar os valores de propriedades no CSS. Pode ser utilizada em qualquer lugar , como  {{cssxref("<length>")}}, {{cssxref("<frequency>")}}, {{cssxref("<angle>")}}, {{cssxref("<time>")}}, {{cssxref("<percentage>")}}, {{cssxref("<number>")}}, e {{cssxref("<integer>")}} é permitido.

+ +
/* propriedade: calc(expressão) */
+width: calc(100% - 80px);
+
+ +

Syntax

+ +

A função  calc() recebe uma simples expressão como parâmetro e o resultado desta expressão é utilizado como valor. Pode ser uma simples expressão, combinando os seguintes operadores, utilizando padrão operator precedence rules:

+ +
+
+
+
Adição.
+
-
+
Subtração.
+
*
+
Multiplicação. Pelo menos um dos argumentos deve ser um {{cssxref("<number>")}}.
+
/
+
Divisão. O operador da direita deve ser um {{cssxref("<number>")}}.
+
+ +

Os operandos na expressão podem ser qualquer valor de sintaxe {{cssxref ("<length>")}}. Você pode usar unidades diferentes para cada valor em sua expressão, se desejar. Você também pode usar parênteses para estabelecer a ordem de computação quando necessário.

+ +

Notas

+ + + +

Formal syntax

+ +
{{csssyntax}}
+ +

Exemplos

+ +

Posicionando um objeto na tela usando margin

+ +

calc() torna mais fácil posicionar um objeto com uma margem definida. Nesse exemplo, o CSS cria um banner que se estende pela janela, com um espaço de 40px entre os dois lados do banner e das bordas da janela:

+ +
.banner {
+  position: absolute;
+  left: 40px;
+  width: calc(100% - 80px);
+  border: solid black 1px;
+  box-shadow: 1px 2px;
+  background-color: yellow;
+  padding: 6px;
+  text-align: center;
+  box-sizing: border-box;
+}
+
+ +
<div class="banner">This is a banner!</div>
+ +

{{EmbedLiveSample('Positioning_an_object_on_screen_with_a_margin', 'auto', '60')}}

+ +

Dimensionar campos de formulário automaticamente para caber em seu contêiner

+ +

Outro caso para calc() é ajudar a garantir que os campos do formulário caibam no espaço disponível, sem expandir para além da borda do seu contêiner, enquanto mantém uma margem apropriada.

+ +

Veja-mos no CSS:

+ +
input {
+  padding: 2px;
+  display: block;
+  width: calc(100% - 1em);
+}
+
+#formbox {
+  width: calc(100% / 6);
+  border: 1px solid black;
+  padding: 4px;
+}
+
+ +

Aqui, o próprio formulário é estabelecido para utilizar 1/6 da largura da janela disponível. Então, para garantir que os campos de entrada mantenham um tamanho apropriado, utilizamos calc() novamente para estabelecer que eles devem ter a largura de seu contêiner menos 1em. Então, o seguinte HTML utiliza este CSS:

+ +
<form>
+  <div id="formbox">
+  <label>Type something:</label>
+  <input type="text">
+  </div>
+</form>
+
+ +

{{EmbedLiveSample('Automatically_sizing_form_fields_to_fit_their_container', '700', '80')}}

+ +

calc( ) inserido em variáveis de CSS

+ +

Você também pode utilizar calc() com variáveis de CSS. Considere o seguinte código:

+ +
.foo {
+  --widthA: 100px;
+  --widthB: calc(var(--widthA) / 2);
+  --widthC: calc(var(--widthB) / 2);
+  width: var(--widthC);
+}
+ +

Depois que todas as variáveis forem expandidas, o valor de widthC será calc( calc( 100px / 2) / 2), então quando for atribuído à propriedade de largura .foo, todos os calc() internos (não importa o qquão profundamente atribuídos) serão nivelados para apenas parênteses, de modo que o valor da propriedade width será eventualmente calc( ( 100px / 2) / 2), i.e. 25px. Resumindo: um calc() dentro de um calc() é idêntico à parênteses.

+ +

Questões de acessibilidade

+ +

Quando calc() é usado para controlar o tamanho do texto, certifique-se de que um dos valores inclui uma unidade de comprimento relativo, por exemplo:

+ +
h1 {
+  font-size: calc(1.5rem + 3vw);
+}
+ +

Isso garante que o tamanho do texto será redimensionado se a página for ampliada.

+ + + +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('CSS3 Values', '#calc-notation', 'calc()')}}{{Spec2('CSS3 Values')}}Definição inicial
+ +

Compatibilidade do navegador

+ + + +

{{Compat("css.types.calc")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/css/class_selectors/index.html b/files/pt-br/web/css/class_selectors/index.html new file mode 100644 index 0000000000..dc624c3733 --- /dev/null +++ b/files/pt-br/web/css/class_selectors/index.html @@ -0,0 +1,106 @@ +--- +title: Seletores de classe +slug: Web/CSS/Class_selectors +tags: + - CSS + - Classe + - Referencia + - Seletores +translation_of: Web/CSS/Class_selectors +--- +

O seletor de classes CSS corresponde aos elementos com base no conteúdo de seus atributos class.

+ +
/* Todos os elementos com class="espaçoso" */
+.espaçoso {
+  margin: 2em;
+}
+
+/* Todos os elementos <li> com class="espaçoso" */
+li.espaçoso {
+  margin: 2em;
+}
+
+/* Todos os elementos <li> cujo conteúdo do atributo class possua "espaçoso" e "elegante" */
+/* Por exemplo, class="elegante antigo espaçoso" */
+li.espaçoso.elegante {
+  margin: 2em;
+}
+
+ +

Sintaxe

+ +
.classe_nome { propriedades de estilo }
+ +

Observe que isso é o mesmo que seletor de atributo:

+ +
[classe~=classe_nome] { propriedades de estilo  }
+ +

Exemplo

+ +

CSS

+ +
.vermelho {
+  color: #f33;
+}
+
+.amarelo-bg {
+  background: #ffa;
+}
+
+.elegante {
+  font-weight: bold;
+  text-shadow: 4px 4px 3px #77f;
+}
+
+ +

HTML

+ +
<p class="vermelho">Este parágrafo tem o texto vermelho.</p>
+<p class="vermelho amarelo-bg">Este parágrafo possui texto em vermelho e fundo amarelo.</p>
+<p class="vermelho elegante">Este parágrafo possui texto em vermelho e uma propriedade de estilo "elegante".</p>
+<p>Este é um parágrafo comum.</p>
+
+ +

Resultado

+ +

{{EmbedLiveSample('Example')}}

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('CSS4 Selectors', '#class-html', 'class selectors')}}{{Spec2('CSS4 Selectors')}}Sem mudança
{{SpecName('CSS3 Selectors', '#class-html', 'class selectors')}}{{Spec2('CSS3 Selectors')}}
{{SpecName('CSS2.1', 'selector.html#class-html', 'child selectors')}}{{Spec2('CSS2.1')}}
{{SpecName('CSS1', '#class-as-selector', 'child selectors')}}{{Spec2('CSS1')}}Definição inicial
+ +

Compatibilidade do navegador

+ + + +

{{Compat("css.selectors.class")}}

diff --git a/files/pt-br/web/css/clear/index.html b/files/pt-br/web/css/clear/index.html new file mode 100644 index 0000000000..6b108c4ece --- /dev/null +++ b/files/pt-br/web/css/clear/index.html @@ -0,0 +1,239 @@ +--- +title: clear +slug: Web/CSS/clear +tags: + - CSS + - CSS Positioning + - CSS Property + - Reference +translation_of: Web/CSS/clear +--- +
{{CSSRef}}
+ +

A propriedade clear do CSS especifica se um elemento pode ter elementos flutuantes ao seu lado ou se devem ser movidos para abaixo dele (clear). Essa propriedade se aplica à elementos flutuantes ou não flutuantes. 

+ +
{{EmbedInteractiveExample("pages/css/clear.html")}}
+ + + +

Quando essa propriedade é aplicada em elementos não flutuantes, ele move a borda (border edge) desse elemento para a borda da margem (margin edge) de todos os elementos flutuantes relevantes. Ocorre um colapso das margens verticais dos elementos não flutuantes.

+ +

As margens verticais entre dois elementos flutuantes não irão sofrer esse colapso. Quando aplicada a elementos flutuantes, a borda de margem (margin edge) do elemento inferior é movida abaixo da borda de margem (border edge) de todos os elementos flutuantes relevantes. Isso afeta a posição dos elementos flutuantes posteriores, sendo que os elementos flutuantes posteriores não podem ser posicionados acima dos anteriores.

+ +

Os elementos flutuantes que devem ser limpos (clear) são os elementos anteriores dentro do mesmo contexto de bloco (block formatting context).

+ +
+

Nota: se um elemento possuir apenas elementos flutuantes, sua altura é zerada. Se você quiser que o mesmo seja redimensionado, de modo que contenha elementos flutuantes dentro dele, você precisa limpar(clear) seus filhos automaticamente. Isso é chamado clearfix, e uma maneira de fazê-lo é adicionando um {{cssxref("::after")}} pseudo-elemento com a propriedade clear.

+ +
#container::after {
+  content: "";
+  display: block;
+  clear: both;
+}
+
+
+ +

Sintaxe

+ +
/* Valores chaves */
+clear: none;
+clear: left;
+clear: right;
+clear: both;
+clear: inline-start;
+clear: inline-end;
+
+/* Valores globais */
+clear: inherit;
+clear: initial;
+clear: unset;
+
+ +

Valores

+ +
+
none
+
É uma palavra-chave que indica que o elemento não foi movido para baixo para limpar os elementos flutuantes anteriores.
+
left
+
É uma palavra-chave que indica que o elemento foi movido para baixo para limpar os últimos flutuantes da esquerda.
+
right
+
É uma palavra-chave que indica que o elemento foi movido para baixo para liberar os últimos elementos flutuantes.
+
both
+
É uma palavra-chave que indica que o elemento será movido para baixo para limpar os elementos flutuantes do lado esquerdo e direito.
+
inline-start
+
É uma palavra-chave que indica que o elemento será movido para baixo para limpar os elementos flutuantes no lado inicial de seu bloco, ou seja, os da esquerda flutuam nos scripts de ltr e os da direita nos scripts de rtl.
+
inline-end
+
É uma palavra-chave que indica que o elemento será movido para baixo para limpar os flutuantes no final de seu bloco, os da direita nos scripts de ltr e os flutuantes da esquerda nos scripts de rtl.
+
+ +

Sintaxe

+ +
{{csssyntax}}
+ +

Exemplos

+ +

clear: left

+ +

HTML

+ +
<div class="wrapper">
+  <p class="black">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Phasellus sit amet diam. Duis mattis varius dui. Suspendisse eget dolor.</p>
+  <p class="red">Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</p>
+  <p class="left">This paragraph clears left.</p>
+</div>
+
+ +

CSS

+ +
.wrapper{
+  border:1px solid black;
+  padding:10px;
+}
+.left {
+  border: 1px solid black;
+  clear: left;
+}
+.black {
+  float: left;
+  margin: 0;
+  background-color: black;
+  color: #fff;
+  width: 20%;
+}
+.red {
+  float: left;
+  margin: 0;
+  background-color: pink;
+  width:20%;
+}
+p {
+  width: 50%;
+}
+
+ +

{{ EmbedLiveSample('clear:_left','100%','250') }}

+ +

clear: right

+ +

HTML

+ +
<div class="wrapper">
+  <p class="black">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Phasellus sit amet diam. Duis mattis varius dui. Suspendisse eget dolor.</p>
+  <p class="red">Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</p>
+  <p class="right">This paragraph clears right.</p>
+</div>
+
+ +

CSS

+ +
.wrapper{
+  border:1px solid black;
+  padding:10px;
+}
+.right {
+  border: 1px solid black;
+  clear: right;
+}
+.black {
+  float: right;
+  margin: 0;
+  background-color: black;
+  color: #fff;
+  width:20%;
+}
+.red {
+  float: right;
+  margin: 0;
+  background-color: pink;
+  width:20%;
+}
+p {
+  width: 50%;
+}
+ +

{{ EmbedLiveSample('clear:_right','100%','250') }}

+ +

clear: both

+ +

HTML

+ +
<div class="wrapper">
+  <p class="black">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Phasellus sit amet diam. Duis mattis varius dui. Suspendisse eget dolor. Fusce pulvinar lacus ac dui.</p>
+  <p class="red">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Phasellus sit amet diam. Duis mattis varius dui. Suspendisse eget dolor.</p>
+  <p class="both">This paragraph clears both.</p>
+</div>
+
+ +

CSS

+ +
.wrapper{
+  border:1px solid black;
+  padding:10px;
+}
+.both {
+  border: 1px solid black;
+  clear: both;
+}
+.black {
+  float: left;
+  margin: 0;
+  background-color: black;
+  color: #fff;
+  width:20%;
+}
+.red {
+  float: right;
+  margin: 0;
+  background-color: pink;
+  width:20%;
+}
+p {
+  width: 45%;
+}
+ +

{{ EmbedLiveSample('clear:_both','100%','300') }}

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS Logical Properties', '#float-clear', 'float and clear')}}{{Spec2('CSS Logical Properties')}}Adds the values inline-start and inline-end
{{SpecName('CSS2.1', 'visuren.html#flow-control', 'clear')}}{{Spec2('CSS2.1')}}No significant changes, though details are clarified.
{{SpecName('CSS1', '#clear', 'clear')}}{{Spec2('CSS1')}}Initial definition
+ +

{{cssinfo}}

+ +

Compatibilidade dos browsers

+ + + +

{{Compat("css.properties.clear")}}

+ +
 
+ +

Veja também

+ + diff --git a/files/pt-br/web/css/color/index.html b/files/pt-br/web/css/color/index.html new file mode 100644 index 0000000000..2248c1ebe8 --- /dev/null +++ b/files/pt-br/web/css/color/index.html @@ -0,0 +1,168 @@ +--- +title: Propriedade color do CSS +slug: Web/CSS/color +tags: + - CSS + - HTML + - Layout + - Web + - color +translation_of: Web/CSS/color +--- +
{{CSSRef}}
+ +

A propriedade color do CSS definine o valor da cor de um elemento com seu conteúdo em texto e seus decorações (estilos). Também define o valorer da {{cssxref("currentcolor")}}, no qual pode ser usado um valor indireto de outra propriedade, e tem como padrão as cores de outras propriedades (enquanto não definida), tal como a propriedade {{cssxref("border-color")}}.

+ +
{{EmbedInteractiveExample("pages/css/color.html")}}
+ + + + + +

Para uma visão geral de como usar a propriedade color e semelhantes no HTML, veja Cor - CSS, como começar.

+ +

Syntaxe

+ +
/* Valores com Palavras-chave */
+color: white; /* Aqui será definida a cor atual*/
+
+/* Valores com Palavras-chave */
+/* color define a cor do texto no elemento*/
+color: red;    /* Define como 'vermelho'*/
+color: blue;   /* Define como 'laranja'*/
+color: cyan;   /* Define como 'verde-água'*/
+
+/* Obs: Utilizando "light" antes da cor, ela ficará clara.
+   ex: lightblue;
+   E utilizando "dark", ela ficará mais escura.
+   ex: darkblue;
+*/
+
+/* Cores com valores Hexa-decimais,
+ou seja de 1 à 15, sendo de 0 à 9 normais,mas de 10 à 15
+são as letras do alfabeto , logo de "a" à "f". */
+
+color: #090;
+color: #0099fg;
+color: #090a;
+color: #0099bcaa;
+
+/* Valores "rgb" ou "rgba",
+ou seja, o primeiro é vermelho, o segundo é verde e
+o terceiro é azul, o "a" é o nível de transparência da cor,
+e vai de 0 à 1;
+Ex: preto meio transparênte = rgba(255,255,255,0.5); */
+
+color: rgb(34, 12, 64, 0.6);
+color: rgba(34, 12, 64, 0.6);
+color: rgb(34 12 64 / 0.6);
+color: rgba(34 12 64 / 0.3);
+color: rgb(34.0 12 64 / 60%);
+color: rgba(34.6 12 64 / 30%);
+
+/* Valores "hsl()", sendo
+hsl(num da cor"1-369"saturação"0-100"luminosidade"0-100")*/
+color: hsl(30, 100%, 50%, 0.6);
+color: hsla(30, 100%, 50%, 0.6);
+color: hsl(30 100% 50% / 0.6);
+color: hsla(30 100% 50% / 0.6);
+color: hsl(30.0 100% 50% / 60%);
+color: hsla(30.2 100% 50% / 60%);
+
+/* Valores globais, pega algun valor já definido,
+para todo o <body>, por exemplo. */
+color: inherit;
+color: initial;
+color: unset;
+
+ +

A propriedade color é especificada somente com o valor {{cssxref("<color>")}} .

+ +

Note que o valor sempre será uniforme para {{cssxref("color")}}. Não podendo ter  {{cssxref("<gradient>")}}(gradiente), que é atualmente um tipo para {{cssxref("<image>")}}.

+ +

Valores

+ +
+
{{cssxref("<color>")}}
+
 Define a cor dos caracteres presentes no elemento a ser estilizado.
+
+ +

Syntaxe formal

+ +
p { color: gray; }
+ +

Exemplos

+ +

A seguir, você verá várias maneira de tornar a cor de um texto num parágrafo vermelha:

+ +
p { color: red; }
+p { color: #f00; }
+p { color: #ff0000; }
+p { color: rgb(255,0,0); }
+p { color: rgb(100%, 0%, 0%); }
+p { color: hsl(0, 100%, 50%); }
+
+/* 50% translúcido(transparênte) */
+p { color: rgba(255, 0, 0, 0.5); }
+p { color: hsla(0, 100%, 50%, 0.5); }
+
+ +

Preocupações com acessibilidade

+ +

É extremamente crucial que todo site, contenha um contraste de cores adequado, para que pessoas com níveis baixos de visão tenha um aboa experiência ao utilizar o site.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS4 Colors', '#the-color-property', 'color')}}{{Spec2('CSS4 Colors')}}Adiciona syntaxes sem emendas para as funções rgb(), rgba(), hsl() e hsla() . Permite valores alpha em rgb() e hsl(), dirando rgba() e hsla() em (descontinuada).
+ Adiciona a palavra-chave rebeccapurple.
+ Adiciona valores de cores hexa-decimais de 4 à 8 dígitos, where the last digit(s) represents the alpha value.
+ Adiona as funcões hwb(), device-cmyk() e color() .
{{SpecName('CSS3 Transitions', '#animatable-css', 'color')}}{{Spec2('CSS3 Transitions')}}Define color como animável.
{{SpecName('CSS3 Colors', '#color', 'color')}}{{Spec2('CSS3 Colors')}}Deprecia as cores do Sistema. Adiciona cores SVG. Adicionando as funções rgba(), hsl(), and hsla().
{{SpecName('CSS2.1', 'colors.html#colors', 'color')}}{{Spec2('CSS2.1')}}Adiciona a cor laranja orange color e o Sistema de Cores.
{{SpecName('CSS1', '#color', 'color')}}{{Spec2('CSS1')}}Definição Inicial
+ +
{{cssinfo}}
+ +

Browser compatibility

+ + + +

{{Compat("css.properties.color")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/css/color_value/index.html b/files/pt-br/web/css/color_value/index.html new file mode 100644 index 0000000000..501ae9fa46 --- /dev/null +++ b/files/pt-br/web/css/color_value/index.html @@ -0,0 +1,1521 @@ +--- +title: +slug: Web/CSS/color_value +tags: + - CSS + - Layout + - Referencia + - Tipo de dado CSS + - Web +translation_of: Web/CSS/color_value +--- +
{{CSSRef}}
+ +

Sumário

+ +

O tipo de dado CSS <color> indica uma cor no espaço sRGB. Uma cor pode ser descrita em qualquer uma destas formas:

+ +
    +
  • usando uma palavra-chave
  • +
  • usando o sistema de coordenada-cúbica RGB  (via #-hexadecimal ou das notações funcional rgb()rgba())
  • +
  • usando o sistema de coordenada-cilíndrica HSL (via hsl() e notações funcionais hsla() )
  • +
+ +

Observe que a lista de valores de cores aceitas foi estendida à medida que a especificação evoluiu, culminando com as cores CSS3 mais recentes.

+ +

Associado à cor no espaço sRGB, um valor <color> também pode consistir de uma coordenada de valor de transparência canal-alfa, Indicando como a cor deve se composta com sua cor de fundo.

+ +

Embora os valores de cores CSS sejam definidos com precisão, eles podem aparecer de forma diferente em dispositivos de saída diferentes. A maioria deles não está calibrada e alguns navegadores não suportam o perfil de cores dos dispositivos de saída. Sem estes, a renderização de cores pode variar muito.

+ +
Nota: A recomendação WCAG 2.0 do W3C aconselha fortemente aos autores web não usarem cor como o único meio para transmitir uma mensagem específica, ação ou resultado. Alguns usuários têm problemas em distinguir cores e as informações transmitidas podem não ser compreendidas. Claro, isso não impede o uso da cor, mas o seu uso apenas como o único meio para descrever certas coisas (veja Cor e contraste de cor para mais informações).
+ +

Interpolação

+ +

Valores do tipo de dados CSS <color> podem ser interpolados para realizar animações ou para criar valores <gradient>. Nesse caso, eles são interpolados em cada um de seus componentes vermelho, verde, azul, cada um manipulado como um número real, de ponto flutuante. Observe que a interpolação de cores ocorre no espaço de cores sRGBA alfa-pré-multiplicado para evitar que cores cinzentas inesperadas apareçam. Nas animações, a velocidade da interpolação é determinada pela função de temporização associada à animação.

+ +

Valores

+ +

Existem várias maneiras de descrever um valor <color>.

+ +

Palavras-chave de cores

+ +

As palavras-chave de cor são identificadores não sensíveis a maiúsculas e minúsculas que representam uma cor específica, ex.: redbluebrown, ou lightseagreen. O nome descreve a cor, embora seja principalmente artificial. A lista de valores aceitos variou muito ao longo das diferentes especificações:

+ +
    +
  • CSS nível 1 aceita apenas16 cores básicas, denominadas cores VGA já que foram tiradas do conjunto de cores exibíveis das placas gráficas VGA.
  • +
  • CSS nível 2 Adicionou a palavra-chave orange.
  • +
  • Desde o início, os navegadores aceitaram outras cores, principalmente a lista de cores nomeadas X11 já que alguns dos primeiros navegadores foram aplicações X11, embora com algumas diferenças. O SVG 1.0 foi o primeiro padrão a definir formalmente essas palavras-chave; As cores no CSS nível 3 também formalmente definiram essas palavras-chave. Elas são muitas vezes referidas como palavras-chave de cor estendida, cores X11 ou cores SVG.
  • +
+ +

Existem algumas restrições a serem consideradas ao usar palavras-chave:

+ +
    +
  • Com exceção das 16 cores básicas comuns com HTML, as outras não podem ser usadas em HTML. O HTML vai converter esses valores desconhecidos com um algoritmo específico levando a cores completamente diferentes. Essas palavras-chave só devem ser usadas em SVG & CSS.
  • +
  • Palavras-chave desconhecidas tornam a propriedade CSS inválida. Propriedades inválidas sendo ignoradas, a cor não terá efeito. Esse é um comportamento diferente do HTML.
  • +
  • Nenhuma palavra-chave de core definida em CSS têm qualquer transparência — eles são cores simples, sólidas.
  • +
  • Várias palavras-chave indicam as mesmas cores: +
      +
    • darkgray / darkgrey
    • +
    • darkslategray / darkslategrey
    • +
    • dimgray / dimgrey
    • +
    • lightgray / lightgrey
    • +
    • lightslategray / lightslategrey
    • +
    • gray / grey
    • +
    • slategray / slategrey
    • +
    +
  • +
  • Embora os nomes das palavras-chave tenham sido tomadas pelos nomes de cores X11 habituais, a cor pode divergir da cor do sistema correspondente em sistemas X11 como estes são adaptados para o hardware específico pelo fabricante.
  • +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoCorPalavra-chavevalores hex RGBResultado
{{SpecName("CSS1")}} black#000000 
 silver#c0c0c0 
 gray#808080 
 white#ffffff 
 maroon#800000 
 red#ff0000 
 purple#800080 
 fuchsia#ff00ff 
 green#008000 
 lime#00ff00 
 olive#808000 
 yellow#ffff00 
 navy#000080 
 blue#0000ff 
 teal#008080 
 aqua#00ffff 
{{SpecName("CSS2.1")}} orange#ffa500 
{{SpecName("CSS3 Colors")}} aliceblue#f0f8ff 
 antiquewhite#faebd7 
 aquamarine#7fffd4 
 azure#f0ffff 
 beige#f5f5dc 
 bisque#ffe4c4 
 blanchedalmond#ffebcd 
 blueviolet#8a2be2 
 brown#a52a2a 
 burlywood#deb887 
 cadetblue#5f9ea0 
 chartreuse#7fff00 
 chocolate#d2691e 
 coral#ff7f50 
 cornflowerblue#6495ed 
 cornsilk#fff8dc 
 crimson#dc143c 
 cyan#00ffff 
 darkblue#00008b 
 darkcyan#008b8b 
 darkgoldenrod#b8860b 
 darkgray#a9a9a9 
 darkgreen#006400 
 darkgrey#a9a9a9 
 darkkhaki#bdb76b 
 darkmagenta#8b008b 
 darkolivegreen#556b2f 
 darkorange#ff8c00 
 darkorchid#9932cc 
 darkred#8b0000 
 darksalmon#e9967a 
 darkseagreen#8fbc8f 
 darkslateblue#483d8b 
 darkslategray#2f4f4f 
 darkslategrey#2f4f4f 
 darkturquoise#00ced1 
 darkviolet#9400d3 
 deeppink#ff1493 
 deepskyblue#00bfff 
 dimgray#696969 
 dimgrey#696969 
 dodgerblue#1e90ff 
 firebrick#b22222 
 floralwhite#fffaf0 
 forestgreen#228b22 
 gainsboro#dcdcdc 
 ghostwhite#f8f8ff 
 gold#ffd700 
 goldenrod#daa520 
 greenyellow#adff2f 
 grey#808080 
 honeydew#f0fff0 
 hotpink#ff69b4 
 indianred#cd5c5c 
 indigo#4b0082 
 ivory#fffff0 
 khaki#f0e68c 
 lavender#e6e6fa 
 lavenderblush#fff0f5 
 lawngreen#7cfc00 
 lemonchiffon#fffacd 
 lightblue#add8e6 
 lightcoral#f08080 
 lightcyan#e0ffff 
 lightgoldenrodyellow#fafad2 
 lightgray#d3d3d3 
 lightgreen#90ee90 
 lightgrey#d3d3d3 
 lightpink#ffb6c1 
 lightsalmon#ffa07a 
 lightseagreen#20b2aa 
 lightskyblue#87cefa 
 lightslategray#778899 
 lightslategrey#778899 
 lightsteelblue#b0c4de 
 lightyellow#ffffe0 
 limegreen#32cd32 
 linen#faf0e6 
 mediumaquamarine#66cdaa 
 mediumblue#0000cd 
 mediumorchid#ba55d3 
 mediumpurple#9370db 
 mediumseagreen#3cb371 
 mediumslateblue#7b68ee 
 mediumspringgreen#00fa9a 
 mediumturquoise#48d1cc 
 mediumvioletred#c71585 
 midnightblue#191970 
 mintcream#f5fffa 
 mistyrose#ffe4e1 
 moccasin#ffe4b5 
 navajowhite#ffdead 
 oldlace#fdf5e6 
 olivedrab#6b8e23 
 orangered#ff4500 
 orchid#da70d6 
 palegoldenrod#eee8aa 
 palegreen#98fb98 
 paleturquoise#afeeee 
 palevioletred#db7093 
 papayawhip#ffefd5 
 peachpuff#ffdab9 
 peru#cd853f 
 pink#ffc0cb 
 plum#dda0dd 
 powderblue#b0e0e6 
 rosybrown#bc8f8f 
 royalblue#4169e1 
 saddlebrown#8b4513 
 salmon#fa8072 
 sandybrown#f4a460 
 seagreen#2e8b57 
 seashell#fff5ee 
 sienna#a0522d 
 skyblue#87ceeb 
 slateblue#6a5acd 
 slategray#708090 
 slategrey#708090 
 snow#fffafa 
 springgreen#00ff7f 
 steelblue#4682b4 
 tan#d2b48c 
 thistle#d8bfd8 
 tomato#ff6347 
 turquoise#40e0d0 
 violet#ee82ee 
 wheat#f5deb3 
 whitesmoke#f5f5f5 
 yellowgreen#9acd32 
{{SpecName("CSS4 Colors")}} rebeccapurple#663399 
+ +

A cor rebeccapurple é equivalente à cor #639, e mais informações sobre por que foi introduzida pode ser encontrada neste post no blog Codepen por Trezy "Honoring a Great Man" (em inglês)

+ +

palavra-chave transparent

+ +

A palavra-chave transparent representa uma cor totalmente transparente, isto é, a cor vista será a cor de fundo. Tecnicamente, é um preto com canal alfa no seu valor mínimo e é um atalho para rgba(0,0,0,0).

+ +
Nota histórica
+A palavra-chave transparent não era uma cor verdadeira no CSS nível 2 (Revisão 1). Era uma palavra-chave específica que poderia ser usada no lugar de um valor <color> regular em duas propriedades CSS: {{Cssxref("background")}} e {{Cssxref("border")}}. Ela foi adicionada essencialmente para permitir a substituição de cores sólidas herdadas.
+
+Com o apoio da opacidade através de canais alfal, transparent foi redefinida como uma cor verdadeira no Cores CSS nível 3 permitindo seu uso em qualquer lugar onde for exigido um valor para <color>, como a propriedade {{Cssxref("color")}}.
+ +

palavra-chave currentcolor

+ +

A palavra-chave currentcolor representa o valor calculado da propriedade {{Cssxref("color")}} dos elementos . Ela permite que as propriedades de cor sejam herdadas por propriedades ou propriedades de elemento filho que não a herdam por padrão.

+ +

Ela também pode ser usada em propriedades que herdam o valor calculado da propriedade {{Cssxref ("color")}} do elemento e será equivalente à palavra-chave inherit nesses elementos, se houver.

+ +

Exemplo ao vivo

+ +

A cor da linha (uma div preenchida com cor) se adapta à cor de sua propriedade {{Cssxref ("color")}}, herdada de seu pai.

+ +
+
Exemplo 1
+ +
<div style="color:darkred">
+A cor deste texto é a mesma da linha:  <div style="background:currentcolor; height:1px"></div>
+ Mais algum texto.
+</div>
+
+ +

{{EmbedLiveSample('Live_example_1')}}

+ +
Exemplo 2
+ +
<div style="color:blue; border-bottom: 1px dashed currentcolor;">
+A cor deste texto é a mesma da linha:  <div style="background:currentcolor; height:1px"></div>
+ Mais algum texto.
+</div> 
+ +

{{EmbedLiveSample('Live_example_2')}}

+
+ +

rgb()

+ +
+

Nota: Na especificação Módulo de cor CSS Color nível 4, a rgba() foi definida como uma função herdada com gramática e comportamento idênticos à rgb(); na verdade, um apelido. Mais para frente, ambas podem aceitar exatamente os mesmos parâmetros.

+
+ +

Colors can be defined using the red-green-blue (RGB) model in two ways:

+ +
+
Hexadecimal notation #RRGGBB, #RGB
+
+
    +
  • "#", followed by six hexadecimal characters (0-9, A-F), where the first two digits represent the red part, the second two the green part and the last two the blue part.
  • +
  • "#", followed by three hexadecimal characters (0-9, A-F), where the first digit represents the red part, the second the green part and the last one the blue part.
  • +
+ The three-digit RGB notation (#RGB) and the six-digit form (#RRGGBB) are equal, for example #f03 and #ff0033 represent the same color.
+
Functional Notation rgb(R,G,B)
+
"rgb", followed by three {{cssxref("<integer>")}} or three {{cssxref("<percentage>")}} values, plus an optional alpha value that specifies the transparency of the color (this can be a {{cssxref("<number>")}} between 0 and 1, or a {{cssxref("<percentage>")}})
+ The integer number 255 corresponds to 100%, and to F or FF in the hexadecimal notation.
+
+ +
/* These examples all specify the same RGB color: */
+
+#f03
+#F03
+#ff0033
+#FF0033
+rgb(255,0,51)
+rgb(255, 0, 51)
+rgb(255, 0, 51.2) /* ERROR! Don't use fractions, use integers */
+rgb(100%,0%,20%)
+rgb(100%, 0%, 20%)
+rgb(100%, 0, 20%) /* ERROR! Don't mix up integer and percentage notation */
+
+/* whitespace syntax */
+rgb(255 0 0)
+
+/* optional alpha value */
+rgb(255,0,0,0.4)  /* 40% opaque red */ 
+rgb(255,0,0,40%)  /* 40% opaque red with percentage value for alpha */ 
+rgb(255 0 0 / 0.4)  /* 40% opaque red */ 
+rgb(255 0 0 / 40%)  /* 40% opaque red with percentage value for alpha */ 
+
+
+ +

hsl()

+ +
+

Note: In the CSS Color Module Level 4 spec, hsla() has been defined as a legacy function with identical grammar and behaviour to hsl(); in effect, an alias. Going forward, both can accept exactly the same parameters.

+
+ +

Colors can also be defined via hue, saturation, and lightness, or HSL, by using the hsl() functional notation. The advantage of HSL over RGB is that it is far more intuitive: you can guess at the colors you want, and then tweak. It is also easier to create sets of matching colors (by keeping the hue the same and varying the lightness/darkness, and saturation).

+ +

Hue is represented as an angle of the color circle (i.e. the rainbow represented in a circle). This angle is given as a unitless {{cssxref("<number>")}}. By definition red=0=360, and the other colors are spread around the circle, so green=120, blue=240, etc. As an angle, it implicitly wraps around such that -120=240 and 480=120.

+ +

Saturation and lightness are represented as percentages.
+ 100% is full saturation, and 0% is a shade of grey.
+ 100% lightness is white, 0% lightness is black, and 50% lightness is “normal.”

+ +
hsl(0,  100%,50%)    /* red */   
+hsl(30, 100%,50%)                
+hsl(60, 100%,50%)                
+hsl(90, 100%,50%)                
+hsl(120,100%,50%)    /* green */ 
+hsl(150,100%,50%)                
+hsl(180,100%,50%)                
+hsl(210,100%,50%)                
+hsl(240,100%,50%)    /* blue */  
+hsl(270,100%,50%)                
+hsl(300,100%,50%)                
+hsl(330,100%,50%)                
+hsl(360,100%,50%)    /* red */   
+
+hsl(120,100%,25%)    /* dark green */  
+hsl(120,100%,50%)    /* green */       
+hsl(120,100%,75%)    /* light green */ 
+
+hsl(120,100%,50%)    /* green */  
+hsl(120, 67%,50%)                 
+hsl(120, 33%,50%)                 
+hsl(120,  0%,50%)                 
+
+hsl(120, 60%,70%)    /* pastel green */ 
+
+/* whitespace syntax */
+hsl(120 60% 70%)  /* pastel green */ 
+
+/* angle values for hue component; also accepts rad, grad, turn */
+hsl(120deg 60% 70%)  /* pastel green */ 
+
+/* optional alpha value */
+hsl(240,100%,50%,0.05)  /* 5% opaque blue */ 
+hsl(240,100%,50%,5%)  /* 5% opaque blue with percentage value for alpha */ 
+hsl(240 100% 50% / 0.05) /* 5% opaque blue */
+hsl(240 100% 50% / 5%) /* 5% opaque blue with percentage value for alpha */
+
+ +

rgba()

+ +

Colors can be defined in the Red-green-blue-alpha model (RGBa) in two ways:

+ +
+
Hexadecimal notation #RRGGBBAA and #RGBA
+
+
    +
  • "#", followed by eight hexadecimal characters (0-9, A-F), where the first two digits represent the red part, the second two the green part, the third two the blue part and the last two the transparency.
  • +
  • "#", followed by four hexadecimal characters (0-9, A-F), where the first digit represents the red part, the second the green part, the third one the blue part and the last one the transparency.
  • +
+ The four-digit RGB notation (#RGBA) and the eight-digit form (#RRGGBBAA) are equal, for example, #f038 and #ff003388 represent the same color.
+
using the rgba() functional notation.
+
RGBa extends the RGB color model to include the alpha channel, allowing specification of the opacity of a color.
+ a means opacity: 0=transparent; 1=opaque;
+
+ +
#f030                /* 0% opaque red */  
+#F03F                /* full opaque red */  
+#ff003300            /* 0% opaque red */  
+#FF003388            /* 50% opaque red */  
+rgba(255,0,0,0.1)    /* 10% opaque red */  
+rgba(255,0,0,0.4)    /* 40% opaque red */  
+rgba(255,0,0,0.7)    /* 70% opaque red */  
+rgba(255,0,0,  1)    /* full opaque red */ 
+
+/* whitespace syntax */
+rgba(255 0 0 / 0.4)  /* 40% opaque red */ 
+
+/* percentage value for alpha */
+rgba(255 0 0 / 40%)  /* 40% opaque red */ 
+
+ +
+

Note: In the CSS Color Module Level 4 spec, rgba() has been defined as a legacy function with identical grammar and behaviour to rgb(); in effect, an alias. Going forward, both can accept exactly the same parameters.

+
+ +

hsla()

+ +

Colors can be defined in the hue-saturation-lightness-alpha model (HSLa) using the hsla() functional notation. HSLa extends the HSL color model to include the alpha channel, allowing specification of the opacity of a color.
+ a means opacity: 0=transparent; 1=opaque;

+ +
hsla(240,100%,50%,0.05)   /* 5% opaque blue */   
+hsla(240,100%,50%, 0.4)   /* 40% opaque blue */  
+hsla(240,100%,50%, 0.7)   /* 70% opaque blue */  
+hsla(240,100%,50%,   1)   /* full opaque blue */ 
+
+/* whitespace syntax */
+hsla(240 100% 50% / 0.05) /* 5% opaque blue */ 
+
+/* percentage value for alpha */
+hsla(240 100% 50% / 5%) /* 5% opaque blue */ 
+
+/* angle values for hue component; also accepts rad, grad, turn */
+hsla(240deg 100% 50% / 5%) /* 5% opaque blue */ 
+hsla(240deg,100%,50%, 0.4)  /* 40% opaque blue */ 
+
+ +
+

Note: In the CSS Color Module Level 4 spec, hsla() has been defined as a legacy function with identical grammar and behaviour to hsl(); in effect, an alias. Going forward, both can accept exactly the same parameters.

+
+ +

System Colors

+ +

Not all system colors are supported on all systems. {{deprecated_inline}} for use on public web pages.

+ +
+
ActiveBorder
+
Active window border.
+
ActiveCaption
+
Active window caption. Should be used with CaptionText as foreground color.
+
AppWorkspace
+
Background color of multiple document interface.
+
Background
+
Desktop background.
+
ButtonFace
+
Face background color for 3-D elements that appear 3-D due to one layer of surrounding border.  Should be used with the ButtonText foreground color.
+
ButtonHighlight
+
The color of the border facing the light source for 3-D elements that appear 3-D due to that layer of surrounding border.
+
ButtonShadow
+
The color of the border away from the light source for 3-D elements that appear 3-D due to that layer of surrounding border.
+
ButtonText
+
Text on push buttons. Should be used with the ButtonFace or ThreeDFace background color.
+
CaptionText
+
Text in caption, size box, and scrollbar arrow box. Should be used with the ActiveCaption background color.
+
GrayText
+
Grayed (disabled) text.
+
Highlight
+
Item(s) selected in a control.  Should be used with the HighlightText foreground color.
+
HighlightText
+
Text of item(s) selected in a control. Should be used with the Highlight background color.
+
InactiveBorder
+
Inactive window border.
+
InactiveCaption
+
Inactive window caption. Should be used with the InactiveCaptionText foreground color.
+
InactiveCaptionText
+
Color of text in an inactive caption.  Should be used with the InactiveCaption background color.
+
InfoBackground
+
Background color for tooltip controls. Should be used with the InfoText foreground color.
+
InfoText
+
Text color for tooltip controls.  Should be used with the InfoBackground background color.
+
Menu
+
Menu background. Should be used with the MenuText or  -moz-MenuBarText foreground color.
+
MenuText
+
Text in menus. Should be used with the Menu background color.
+
Scrollbar
+
Background color of scroll bars.
+
ThreeDDarkShadow
+
The color of the darker (generally outer) of the two borders away from the light source for 3-D elements that appear 3-D due to two concentric layers of surrounding border.
+
ThreeDFace
+
The face background color for 3-D elements that appear 3-D due to two concentric layers of surrounding border. Should be used with the ButtonText foreground color.
+
ThreeDHighlight
+
The color of the lighter (generally outer) of the two borders facing the light source for 3-D elements that appear 3-D due to two
+ concentric layers of surrounding border.
+
ThreeDLightShadow
+
The color of the darker (generally inner) of the two borders facing the light source for 3-D elements that appear 3-D due to two
+ concentric layers of surrounding border.
+
ThreeDShadow
+
The color of the lighter (generally inner) of the two borders away from the light source for 3-D elements that appear 3-D due to two concentric layers of surrounding border.
+
Window
+
Window background. Should be used with the WindowText foreground color.
+
WindowFrame
+
Window frame.
+
WindowText
+
Text in windows. Should be used with the Window background color.
+
+ +

Mozilla System Color Extensions

+ +
+
-moz-ButtonDefault
+
The border color that goes around buttons that represent the default action for a dialog box.
+
-moz-ButtonHoverFace
+
The background color of a button that the mouse pointer is over (which would be ThreeDFace or ButtonFace when the mouse pointer is not over it). Should be used with the -moz-ButtonHoverText foreground color.
+
-moz-ButtonHoverText
+
The text color of a button that the mouse pointer is over (which would be ButtonText when the mouse pointer is not over it).  Should be used with the -moz-ButtonHoverFace background color.
+
-moz-CellHighlight
+
Background color for selected item in a tree widget.  Should be used with the -moz-CellHighlightText foreground color. See also -moz-html-CellHighlight.
+
-moz-CellHighlightText
+
Text color for a selected item in a tree. Should be used with the -moz-CellHighlight background color. See also -moz-html-CellHighlightText.
+
-moz-Combobox
+
{{Gecko_minversion_inline("1.9.2")}} Background color for combo-boxes.  Should be used with the -moz-ComboboxText foreground color. In versions prior to 1.9.2, use -moz-Field instead.
+
-moz-ComboboxText
+
{{Gecko_minversion_inline("1.9.2")}} Text color for combo-boxes. Should be used with the -moz-Combobox background color.  In versions prior to 1.9.2, use -moz-FieldText instead.
+
-moz-Dialog
+
Background color for dialog boxes.  Should be used with the -moz-DialogText foreground color.
+
-moz-DialogText
+
Text color for dialog boxes. Should be used with the -moz-Dialog background color.
+
-moz-dragtargetzone
+
-moz-EvenTreeRow
+
{{gecko_minversion_inline("1.9")}} Background color for even-numbered rows in a tree.  Should be used with the -moz-FieldText foreground color. In Gecko versions prior to 1.9, use -moz-Field.  See also -moz-OddTreeRow.
+
-moz-Field
+
Text field background color.  Should be used with the -moz-FieldText foreground color.
+
-moz-FieldText
+
Text field text color. Should be used with the -moz-Field, -moz-EvenTreeRow, or -moz-OddTreeRow background color.
+
-moz-html-CellHighlight
+
{{gecko_minversion_inline("1.9")}} Background color for highlighted item in HTML {{HTMLElement("select")}}s. Should be used with the -moz-html-CellHighlightText foreground color. Prior to Gecko 1.9, use -moz-CellHighlight.
+
-moz-html-CellHighlightText
+
{{gecko_minversion_inline("1.9")}} Text color for highlighted items in HTML {{HTMLElement("select")}}s.  Should be used with the -moz-html-CellHighlight background color. Prior to Gecko 1.9, use -moz-CellHighlightText.
+
-moz-mac-accentdarkestshadow
+
-moz-mac-accentdarkshadow
+
-moz-mac-accentface
+
-moz-mac-accentlightesthighlight
+
-moz-mac-accentlightshadow
+
-moz-mac-accentregularhighlight
+
-moz-mac-accentregularshadow
+
-moz-mac-chrome-active
+
{{Gecko_minversion_inline("1.9.1")}}
+
-moz-mac-chrome-inactive
+
{{Gecko_minversion_inline("1.9.1")}}
+
-moz-mac-focusring
+
-moz-mac-menuselect
+
-moz-mac-menushadow
+
-moz-mac-menutextselect
+
-moz-MenuHover
+
Background color for hovered menu items. Often similar to Highlight. Should be used with the -moz-MenuHoverText or -moz-MenuBarHoverText foreground color.
+
-moz-MenuHoverText
+
Text color for hovered menu items. Often similar to HighlightText.  Should be used with the -moz-MenuHover background color.
+
-moz-MenuBarText
+
{{Gecko_minversion_inline("1.9.2")}} Text color in menu bars. Often similar to MenuText. Should be used on top of Menu background.
+
-moz-MenuBarHoverText
+
Color for hovered text in menu bars. Often similar to -moz-MenuHoverText. Should be used on top of -moz-MenuHover background.
+
-moz-nativehyperlinktext
+
{{Gecko_minversion_inline("1.9.1")}} Default platform hyperlink color.
+
-moz-OddTreeRow
+
{{gecko_minversion_inline("1.9")}} Background color for odd-numbered rows in a tree.  Should be used with the -moz-FieldText foreground color. In Gecko versions prior to 1.9, use -moz-Field. See also -moz-EvenTreeRow.
+
-moz-win-communicationstext
+
{{gecko_minversion_inline("1.9")}} Should be used for text in objects with {{cssxref("-moz-appearance")}}: -moz-win-communications-toolbox;.
+
-moz-win-mediatext
+
{{gecko_minversion_inline("1.9")}} Should be used for text in objects with {{cssxref("-moz-appearance")}}: -moz-win-media-toolbox.
+
+ +

Mozilla Color Preference Extensions

+ +
+
-moz-activehyperlinktext
+
User's preference for text color of active links. Should be used with the default document background color.
+
-moz-default-background-color
+
{{Gecko_minversion_inline("5.0")}} User's preference for the document background color.
+
-moz-default-color
+
{{Gecko_minversion_inline("5.0")}} User's preference for the text color.
+
-moz-hyperlinktext
+
User's preference for the text color of unvisited links. Should be used with the default document background color.
+
-moz-visitedhyperlinktext
+
User's preference for the text color of visited links. Should be used with the default document background color.
+
+ +

Specificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificaçãoEstadoComentário
{{SpecName('CSS4 Colors', '#colorunits', '<color>')}}{{Spec2('CSS4 Colors')}}Added rebeccapurple, four- (#RGBA) and eight-digit (#RRGGBBAA) hexadecimal notations, rgba() and hsla() as aliases of rgb() and hsl() (both with identical parameter syntax), space-separated function parameters rather than commas, percentages for alpha values, and angles for the hue component in hsl() colors.
{{SpecName('CSS3 Colors', '#colorunits', '<color>')}}{{Spec2('CSS3 Colors')}}Deprecated system-colors; added SVG colors; added rgba(), hsl(), hsla() functional notation.
{{SpecName('CSS2.1', 'syndata.html#value-def-color', '<color>')}}{{Spec2('CSS2.1')}}Added the orange color and the system-colors.
{{SpecName('CSS1', '#color-units', '<color>')}}{{Spec2('CSS1')}}Initial definition.
+ +

Compatibilidade do navegador

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
keywords colors1.01.0 (1.0)3.0 [1]3.51.0 (85)
#RRGGBB, #RGB1.01.0 (1.0)3.03.51.0 (85)
rgb()1.01.0 (1.0)4.03.51.0 (85)
hsl()1.01.0 (1.5)9.09.53.1 (525)
rgba(), hsla()1.03.0 (1.9)9.010.03.1 (525)
currentcolor1.01.5 (1.8)9.09.54.0 (528)
transparent1.03.0 (1.9)9.0 [2]10.03.1 (525)
rebeccapurple38.0{{CompatGeckoDesktop("33")}}1125.07.1
#RRGGBBAA, #RGBA52.0{{CompatGeckoDesktop("49")}}{{CompatUnknown}}39.09.1
rgba() and hsla() as aliases of rgb() and hsl()
+ Space-separated function parameters rather than commas
+ Percentages for alpha values
+ Angles for the hue component in hsl() colors.
{{CompatUnknown}}{{CompatGeckoDesktop("52")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
rgba(), hsla(){{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
rebeccapurple{{CompatVersionUnknown}}{{CompatGeckoMobile("33")}}{{CompatUnknown}}{{CompatUnknown}}8
#RRGGBBAA, #RGBA52.0{{CompatGeckoMobile("49")}}{{CompatNo}}{{CompatNo}}{{CompatUnknown}}
rgba() and hsla() as aliases of rgb() and hsl()
+ Space-separated function parameters rather than commas
+ Percentages for alpha values
+ Angles for the hue component in hsl() colors.
{{CompatUnknown}}{{CompatGeckoMobile("52")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] The 'e'-grey colors (with an e) (grey, darkgrey, darkslategrey, dimgrey, lightgrey, lightslategrey) are only supported since IE 8.0. IE 3 to IE 7 only support the 'a' variants: gray, darkgray, darkslategray, dimgray, lightgray, lightslategray.

+ +

[2] IE 7-8 supports the transparent keyword only for {{Cssxref("background")}} and {{cssxref("border")}}. color: transparent; is drawn black in IE. IE6 renders transparent borders as black, as well.

+ +

[3] This feature is supported in Chrome Canary since version 52.0.

+ +

Ver também

+ +
    +
  • The {{Cssxref("opacity")}} property, allowing to define the transparency of color at the element level.
  • +
  • The {{Cssxref("color")}}, {{Cssxref("background-color")}}, {{Cssxref("border-color")}}, {{Cssxref("outline-color")}}, {{Cssxref("text-shadow")}}, {{Cssxref("box-shadow")}} properties.
  • +
diff --git "a/files/pt-br/web/css/coment\303\241rio/index.html" "b/files/pt-br/web/css/coment\303\241rio/index.html" new file mode 100644 index 0000000000..dabb46a04f --- /dev/null +++ "b/files/pt-br/web/css/coment\303\241rio/index.html" @@ -0,0 +1,49 @@ +--- +title: Comentário +slug: Web/CSS/Comentário +tags: + - CSS + - CSS Reference + - Iniciante +translation_of: Web/CSS/Comments +--- +
ios{{CSSRef}}
+ +

Sumário

+ +

Comments are used to add explanatory notes or prevent the browser from interpreting parts of the style sheet.

+ +

Comments can be placed where ever white space is allowed within a style sheet.

+ +

Sintaxe

+ +
/* Comment */
+ +

Exemplos

+ +
/* A single line comment */
+
+/*
+A comment
+which stretches
+over several
+lines
+*/
+
+ +

Notas

+ +

The /* */ comment syntax is used for both single and multi line comments. There is no other way to specify comments in external style sheets. However, when using the <style> element, you may use <!-- --> to hide CSS from older browsers, although this is not recommended. As in most programming languages that use the /* */ comment syntax, comments cannot be nested. In other words, the first instance of */ that follows an instance of /* closes the comment.

+ +

Especificações

+ + + +

Veja também

+ + diff --git a/files/pt-br/web/css/contain/index.html b/files/pt-br/web/css/contain/index.html new file mode 100644 index 0000000000..dda6afe29e --- /dev/null +++ b/files/pt-br/web/css/contain/index.html @@ -0,0 +1,134 @@ +--- +title: contain +slug: Web/CSS/contain +translation_of: Web/CSS/contain +--- +
{{CSSRef}}{{SeeCompatTable}}
+ +

A propriedade contain  permite que um autor indique que elemento e seus conteúdos são, na medida do possível, independente do resto da árvore do documento. Isso permite que o navegador recalcule o layout, estilo, pintura, tamanho ou alguma combinação deles para uma área limitada do DOM e não da página inteira. 

+ +
/* Sem contenção de layout. */
+contain: none;
+
+/* Ativa a contenção para layout, estilo, pintura, e tamanho. */
+contain: strict;
+
+/* Ativa a contenção para layout, estilo, e pintura. */
+contain: content;
+
+/* Ativa a contenção para um elemento. */
+contain: size;
+
+/* Ativa a contenção de layout para um elemento. */
+contain: layout;
+
+/* Ativa a contenção de estilo para um elemento. */
+contain: style;
+
+/* Ativa a contenção de pintura para um elemento. */
+contain: paint;
+
+ +

Esta propriedade é útil em páginas que contêm um monte de widgets que são todos independentes, uma vez que pode ser usado para impedir que as regras CSS de um widget mude outras coisas na página.

+ +
{{cssinfo}}
+ +

Sintaxe

+ +

Valores

+ +
+
none
+
Indica que o elemento processa como normal, sem contenção aplicada.
+
strict
+
Indica que todas as regras de contenção são aplicadas ao elemento. Isso equivale acontain: size layout style paint.
+
content
+
Indica que todas as regras de contenção, exceto size são aplicadas ao elemento. Isso equivale a  contain: layout style paint.
+
size
+
Indica que o elemento pode ser dimensionado sem a necessidade de examinar seus dependentes para alterações de tamanho.
+
layout
+
Indica que nada fora do elemento pode afetar seu layout interno e vice-versa. 
+
style
+
Indica que, para propriedades que podem ter efeitos em mais do que apenas um elemento e seus descendentes, esses efeitos não escape o elemento que contém.
+
paint
+
Indica que os descendentes do elemento não são exibidos fora de seus limites. Se um elemento estiver fora da tela ou de outra forma não visível, seus descendentes também são garantidos para não ser visível.
+
+ +

Sintaxe Formal

+ +
{{csssyntax}}
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('CSS Containment')}}{{Spec2('CSS Containment')}}Initial definition
+ +

Compatibilidade do navegador

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(52.0)}}{{CompatNo}}[1]{{CompatUnknown}}40{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support{{CompatChrome(52.0)}}{{CompatChrome(52.0)}}{{CompatNo}}[1]{{CompatUnknown}}{{CompatUnknown}}40{{CompatUnknown}}
+
+ +

[1] This feature implemented behind the preference layout.css.contain.enabled, defaulting to false, currently only supporting the values none and paint (see {{bug(1170781)}}). See {{bug(1150081)}} for the overall implementation status.

diff --git a/files/pt-br/web/css/content/index.html b/files/pt-br/web/css/content/index.html new file mode 100644 index 0000000000..603f0e9511 --- /dev/null +++ b/files/pt-br/web/css/content/index.html @@ -0,0 +1,322 @@ +--- +title: content +slug: Web/CSS/content +tags: + - Propriedade CSS + - Referencia +translation_of: Web/CSS/content +--- +
{{CSSRef}}
+ +

A propriedade CSS content é usada com os pseudoelementos {{cssxref("::before")}} e {{cssxref("::after")}} para gerar conteúdo em um elemento. Objetos inseridos usando a propriedade content são elementos substituídos anônimos.

+ +
/* Palavras-chave que não podem ser combinadas com outros valores */
+content: normal;
+content: none;
+
+/* Valores <string> com caracteres especiais devem ser escritos */
+/* com escape Unicode, por exemplo \00A0 para &nbsp; */
+content: "prefixo";
+
+/* Valores <url> */
+content: url("http://www.example.com/test.png");
+
+/* Valores <counter> */
+content: counter(contador_capitulo);
+content: counters(contador_secao, ".");
+
+/* Valores attr() associados ao valor do atributo HTML */
+content: attr(valor string);
+
+/* Palavras-chave que variam com o idioma e posição */
+content: open-quote;
+content: close-quote;
+content: no-open-quote;
+content: no-close-quote;
+
+/* Com exceção de normal e none, vários valores */
+/* podem ser usados simultaneamente */
+content: open-quote chapter_counter;
+
+/* Valores globais */
+content: inherit;
+content: initial;
+content: unset;
+
+ +

{{cssinfo}}

+ +

Sintaxe

+ +

Valores

+ +
+
none
+
O pseudoelemento não será gerado.
+
normal
+
Equivalente a none para os pseudoelementos ::before e ::after.
+
{{cssxref("<string>")}}
+
Um ou mais caracteres de texto.
+
{{cssxref("<url>")}}
+
Uma URL que designa um recurso externo (como uma imagem). Se o recurso não puder ser exibido, ele será ignorado ou um placeholder será exibido no seu lugar.
+
{{cssxref("<counter>")}}
+
O valor de um contador CSS, geralmente um número. Ele pode ser exibido usando a função counter() ou counters().
+
+

A função counter() tem duas formas: 'counter(nome)' ou 'counter(nome, estilo)'. O texto gerado será o valor do contador mais próximo do nome fornecido no pseudoelemento. Ele será formatado com o estilo especificado (o padrão é decimal).

+ +

A função counters() também tem duas formas: 'counters(nome, string)' ou 'counters(nome, separador, estilo)'. O texto gerado será o valor de todos os contadores com o mesmo nome no escopo do pseudoelemento, do mais afastado ao mais próximo, separados pelo separador especificado. Os contadores serão exibidos no estilo indicado (o padrão é decimal).

+
+
attr(x)
+
O valor do atributo x do elemento. Se não houver um atributo x, uma string vazia será retornada. A diferenciação de maiúsculas e minúsculas dependerá da linguagem do documento.
+
open-quote | close-quote
+
Esses valores serão substituídos pela string apropriada da propriedade {{cssxref("quotes")}}.
+
no-open-quote | no-close-quote
+
Não introduzem nenhum conteúdo, mas aumentam (ou diminuem) o nível de aninhamento de aspas.
+
+ +

Sintaxe formal

+ +
{{csssyntax}}
+
+ +

Exemplos

+ +

Cabeçalhos e citações

+ +

Este exemplo insere aspas ao redor de citações e adiciona a palavra "Capítulo" antes dos cabeçalhos.

+ +

HTML

+ +
<h1>5</h1>
+<p>De acordo com o Sr. Tim Berners-Lee,
+  <q cite="http://www.w3.org/People/Berners-Lee/FAQ.html#Internet">I was
+    lucky enough to invent the Web at the time when the Internet
+    already existed - and had for a decade and a half.</q>
+  Devemos entender que não há nada fundamentalmente errado em criar
+  algo com base nas contribuições de outras pessoas.
+</p>
+
+<h1>6</h1>
+<p>De acordo com o Manifesto Mozilla,
+  <q cite="https://www.mozilla.org/about/manifesto/">As pessoas
+    precisam ter a capacidade de moldar a Internet e suas
+    experiências com ela.</q>
+  Portanto, podemos concluir que contribuir para a Web aberta pode
+  proteger nossas próprias experiências individuais nela.
+</p>
+ +

CSS

+ +
q {
+  color: blue;
+}
+
+q::before {
+  content: open-quote;
+}
+
+q::after {
+  content: close-quote;
+}
+
+h1::before  {
+  content: "Cap\00EDtulo ";  /* O espaço no final cria uma separação
+                                entre o conteúdo adicionado e o
+                                resto do conteúdo */
+}
+ +

Resultado

+ +

{{EmbedLiveSample('Headings_and_quotes', '100%', 200)}}

+ +

Imagem combinada com texto

+ +

Este exemplo insere uma imagem antes do link. Se a imagem não for encontrada, o texto será exibido no seu lugar.

+ +

HTML

+ +
<a href="https://www.mozilla.org/">Mozilla Home Page</a>
+ +

CSS

+ +
a::before {
+  content: url("https://mozorg.cdn.mozilla.net/media/img/favicon.ico") " MOZILLA: ";
+  font: x-small Arial, sans-serif;
+  color: gray;
+}
+ +

Resultado

+ +

{{EmbedLiveSample('Image_combined_with_text', '100%', 60)}}

+ +

Alterando classes específicas

+ +

Este exemplo insere texto adicional no final de itens especiais em uma lista.

+ +

HTML

+ +
<h2>Categoriass mais vendidas</h2>
+<ol>
+  <li>Suspenses políticos</li>
+  <li class="new-entry">Histórias de terror</li>
+  <li>Biografias</li>
+  <li class="new-entry">Romances de Vampiros</li>
+</ol>
+ +

CSS

+ +
.new-entry::after {
+  content: " Novo!";  /* O espaço no final cria uma separação
+                         entre o conteúdo adicionado e o
+                         resto do conteúdo */
+  color: red;
+}
+ +

Resultado

+ +

{{EmbedLiveSample('Targeting_classes', '100%', 160)}}

+ +

Imagens e atributos de elementos

+ +

Este exemplo insere uma imagem antes de cada link e adiciona o conteúdo do seu atributo id depois.

+ +

HTML

+ +
<ul>
+  <li><a id="moz" href="http://www.mozilla.org/">
+    Mozilla Home Page</a></li>
+  <li><a id="mdn" href="https://developer.mozilla.org/">
+    Mozilla Developer Network</a></li>
+</ul>
+ +

CSS

+ +
a {
+  text-decoration: none;
+  border-bottom: 3px dotted navy;
+}
+
+a::after {
+  content: " (" attr(id) ")";
+}
+
+#moz::before {
+  content: url("https://mozorg.cdn.mozilla.net/media/img/favicon.ico") ;
+}
+
+#mdn::before {
+  content: url("https://mdn.mozillademos.org/files/7691/mdn-favicon16.png") ;
+}
+
+li {
+  margin: 1em;
+}
+
+ +

Resultado

+ +

{{EmbedLiveSample('Images_and_element_attributes', '100%', 160)}}

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName("CSS3 Content", "#content-property", "content")}}{{Spec2("CSS3 Content")}} 
{{SpecName("CSS2.1", "generate.html#content", "content")}}{{Spec2("CSS2.1")}}Definição inicial
+ +

Compatibilidade com navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
RecursoChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte Básico1.0{{CompatVersionUnknown}}{{CompatGeckoDesktop("1")}}8.04.01.0
Suporte a url()1.0{{CompatUnknown}}{{CompatGeckoDesktop("1")}}8.07.01.0
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
RecursoAndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Suporte Básico1.0{{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}}8.09.51.0
Suporte a url(){{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Veja também

+ +
    +
  • {{Cssxref("::after")}}
  • +
  • {{Cssxref("::before")}}
  • +
  • {{Cssxref("quotes")}}
  • +
diff --git a/files/pt-br/web/css/css_animations/detecting_css_animation_support/index.html b/files/pt-br/web/css/css_animations/detecting_css_animation_support/index.html new file mode 100644 index 0000000000..f26773f0c9 --- /dev/null +++ b/files/pt-br/web/css/css_animations/detecting_css_animation_support/index.html @@ -0,0 +1,99 @@ +--- +title: Detectando suporte a animação CSS +slug: Web/CSS/CSS_Animations/Detecting_CSS_animation_support +tags: + - Animações CSS + - Avançado + - CSS + - Guía + - JavaScript + - Lixo + - Referencia +translation_of: Web/CSS/CSS_Animations/Detecting_CSS_animation_support +--- +
{{CSSRef}}
+ +

Animações CSS torna possível a criação de conteúdo animado e criativo utilizando nada além de CSS. No entando, haverá momentos em que este recurso não estará disponível, e você pode querer lidar com isso utilizando um código JavaScript que simule um efeito semelhante. Este artigo, baseado neste post do blog de Chris Heilmann, demonstra uma técnica para fazer isso.

+ +

Testando por suporte de animação CSS

+ +

Este código irá verificar se o suporte a animação CSS está disponível:

+ +
var animation = false,
+    animationstring = 'animation',
+    keyframeprefix = '',
+    domPrefixes = 'Webkit Moz O ms Khtml'.split(' '),
+    pfx  = '',
+    elem = document.createElement('div');
+
+if( elem.style.animationName !== undefined ) { animation = true; }
+
+if( animation === false ) {
+  for( var i = 0; i < domPrefixes.length; i++ ) {
+    if( elem.style[ domPrefixes[i] + 'AnimationName' ] !== undefined ) {
+      pfx = domPrefixes[ i ];
+      animationstring = pfx + 'Animation';
+      keyframeprefix = '-' + pfx.toLowerCase() + '-';
+      animation = true;
+      break;
+    }
+  }
+}
+
+ +

Para iniciantes definimos algumas variáveis. Assumimos que a animação não é suportada iniciando animation com false. Setamos animationstring com animation que é a propriedade que desejamos setar posteriormente para com true. Criamos um array de prefixos de navegadores para percorrê-lo e setamos pfx com uma string vazia.

+ +

Então verificamos se a propriedade CSS {{ cssxref("animation-name") }} na coleção de estilo do elemento especificado pelo nome elem está definido. Isto significa que o navegador suporta animação CSS sem nenhum prefixo.

+ +

Se o navegador não suporta animação não prefixada e animation permanece falso, iteramos através de todas as possibilidade de prefixos dos principais navegadores que prefixam esta propriedade e acrescentamos este prefixo ao atributo AnimationName.

+ +

Quando a execução deste código termina, o valor de animation será false se não houver suporte a animação CSS, ou true no caso contrário. Se seja true tanto a propriedade de nome de animação quanto o prefixo de keyframe estarão corretos. Se utiliza o novo Firefox, a propriedade será MozAnimation e o prefixo de keyframe -moz-, para o Chrome será WebkitAnimation e -webkit-. Observe que os navegadores não deixam fácil a adoção de camelCase ou hifenização.

+ +

Animando utilizando a sintaxe correta para navegadores diferentes

+ +

Agora que sabe se a animação CSS é suportada ou não, nós iremos animar.

+ +
if( animation === false ) {
+
+  // chamada para a animação em JavaScript
+
+} else {
+  elem.style[ animationstring ] = 'rotate 1s linear infinite';
+
+  var keyframes = '@' + keyframeprefix + 'keyframes rotate { '+
+                    'from {' + keyframeprefix + 'transform:rotate( 0deg ) }'+
+                    'to {' + keyframeprefix + 'transform:rotate( 360deg ) }'+
+                  '}';
+
+  if( document.styleSheets && document.styleSheets.length ) {
+
+      document.styleSheets[0].insertRule( keyframes, 0 );
+
+  } else {
+
+    var s = document.createElement( 'style' );
+    s.innerHTML = keyframes;
+    document.getElementsByTagName( 'head' )[ 0 ].appendChild( s );
+
+  }
+
+}
+
+ +

Este código analisa o valor de animation; se é false, saberemos que precisaremos utilizar nosso código JavaScript para executar a animação. Por outro lado, podemos usar o JavaScript para criar um efeito de animação CSS desejado.

+ +

Modificar a propriedade de animação é fácil; basta atualizar seu valor na coleção de estilos. No entanto, adicionar keyframes é mais difícil, pois não é definito utilizando a sintaxe tradicional do CSS (que torna-o mais flexível, mas difícil em definir de um script).

+ +

Para definir nosso keyframes usando JavaScript, precisamos escrevê-lo como uma string CSS. Tudo que precisamos é setar a variável keyframes, prefixando cada atributo que será construído. Esta variável, uma vez construída, contém a descrição completa de todos os keyframes necessários pela nossa sequência de animação.

+ +

A tarefa seguinte é adicionar os keyframes ao CSS da página. A primeira coisa a se fazer é procurar se existe uma folha de estilos no documento; caso exista, inserimos a descrição do keyframe nesta folha de estilo; isto é feito nas linhas 13-15.

+ +

Se não existe uma folha de estilos, um novo elemento {{ HTMLElement("style") }} é criado, e seu conteúdo é setado com o valor dos keyframes. Então o novo elemento {{ HTMLElement("style") }} é inserido no {{ HTMLElement("head") }} do documento, adicionando assim uma nova folha de estilos ao documento.

+ +

View on JSFiddle

+ +

Veja também

+ + diff --git a/files/pt-br/web/css/css_animations/index.html b/files/pt-br/web/css/css_animations/index.html new file mode 100644 index 0000000000..7c953b2359 --- /dev/null +++ b/files/pt-br/web/css/css_animations/index.html @@ -0,0 +1,136 @@ +--- +title: CSS Animations +slug: Web/CSS/CSS_Animations +tags: + - CSS + - CSS Animations + - Experimental + - Overview + - Reference +translation_of: Web/CSS/CSS_Animations +--- +

{{CSSRef}}{{SeeCompatTable}}

+ +

CSS Animations is a module of CSS that defines how to animate the values of CSS properties over time, using keyframes. The behavior of these keyframe animations can be controlled by specifying their duration, their number of repetitions, and how they repeat.

+ +

Reference

+ +

CSS Properties

+ +
+
    +
  • {{cssxref("animation")}}
  • +
  • {{cssxref("animation")}}
  • +
  • {{cssxref("animation-delay")}}
  • +
  • {{cssxref("animation-direction")}}
  • +
  • {{cssxref("animation-duration")}}
  • +
  • {{cssxref("animation-fill-mode")}}
  • +
  • {{cssxref("animation-iteration-count")}}
  • +
  • {{cssxref("animation-name")}}
  • +
  • {{cssxref("animation-play-state")}}
  • +
  • {{cssxref("animation-timing-function")}}
  • +
+
+ +

CSS At-rules

+ +
+
    +
  • {{cssxref("@keyframes")}}
  • +
+
+ +

Guides

+ +
+
Detecting CSS animation support
+
Describes a technique for detecting if the browser supports CSS animations.
+
Using CSS animations
+
Step-by-step tutorial about how to create animations using CSS, this article describes each relevant CSS property and at-rule and explains how they interact.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSS3 Animations') }}{{ Spec2('CSS3 Animations') }}Initial definition.
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{property_prefix("-webkit")}}
+ 43.0
{{CompatGeckoDesktop("5.0")}}{{property_prefix("-moz")}}
+ {{CompatGeckoDesktop("16.0")}}
1012{{property_prefix("-o")}}
+ 12.10[2]
4.0{{property_prefix("-webkit")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support2.1 {{property_prefix("-webkit")}} [1]
+ 4.0 {{property_prefix("-webkit")}}
{{CompatGeckoMobile("5.0")}}{{property_prefix("-moz")}}
+ {{CompatGeckoMobile("16.0")}}
{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{property_prefix("-webkit")}}
+
+ +

[1] Partial support: {{cssxref("animation-fill-mode")}} property is not supported in Android browser below 2.3.

+ +

[2] See the release notes to Opera 12.50.

+ +

See also

+ +
    +
  • Related to CSS Animations, CSS Transitions can trigger animations on user actions.
  • +
+ +

 

diff --git a/files/pt-br/web/css/css_animations/tips/index.html b/files/pt-br/web/css/css_animations/tips/index.html new file mode 100644 index 0000000000..48df63997b --- /dev/null +++ b/files/pt-br/web/css/css_animations/tips/index.html @@ -0,0 +1,105 @@ +--- +title: CSS Animations tips and tricks +slug: Web/CSS/CSS_Animations/Tips +tags: + - Animações CSS + - CSS + - Comofazer + - Exemplo + - Tutorial +translation_of: Web/CSS/CSS_Animations/Tips +--- +

Animações CSS tornam possível fazer coisas incríveis com os elementos que compoem seus documentos e aplicativos. No entanto, existem coisas que você pode querer fazer que não são óbvias, ou jeitos espertos de fazer coisas que você pode não ter pensado de imediato. Esse artigo é uma coleção de dicas e truques que descobrimos que podem tornar seu trabalho mais fácil, incluindo como rodar uma animação parada novamente.

+ +

Rode uma animação novamente

+ +

A especificação Animações CSS não oferece um modo de rodar uma animação novamente. Não existe um método mágico resetAnimation() nos elementos, e você não pode nem mesmo apenas atribuir o {{cssxref("animation-play-state")}} do elemento para "running" de novo. Ao invés disso, você tem que usar macetes para fazer com que uma animação parada reexecute.

+ +

Aqui está um modo de fazer o qual achamos estável e confiável o suficiente para sugerir à você.

+ +

Conteúdo HTML

+ +

Primeiro, vamos definir o HTML para uma {{HTMLElement("div")}} que gostaríamos de animar e um botão que vai executar (ou reexecutar) a animação.

+ +
<div class="box">
+</div>
+
+<div class="runButton">Clique em mim para rodar a animação</div>
+ +

Conteúdo CSS

+ +

Agora vamos definir a animação em sí usando CSS. Algum CSS que não é importante (o estilo do botão "Rodar" em sí) não é mostrado aqui, por brevidade.

+ + + +
@keyframes colorchange {
+  0% { background: yellow }
+  100% { background: blue }
+}
+
+.box {
+  width: 100px;
+  height: 100px;
+  border: 1px solid black;
+}
+
+.changing {
+  animation: colorchange 2s;
+}
+ +

Existem duas classes aqui. A classe "box" é a descrição básica da aparência da caixa, sem nenhuma informação de animação inclusa. Os detalhes da animação são incluídos na classe "changing", a qual diz que o {{cssxref("@keyframes")}} chamado "colorchange" deveria ser usado no decorrer de dois segundos para animar a caixa.

+ +

Perceba que por isso a caixa não começa com nenhum efeito de animação configurado, então não será animada.

+ +

Conteúdo JavaScript

+ +

A seguir vamos olhar para o JavaScript que faz o trabalho. O macete dessa técnica está na função play() , a qual é chamada quando o usuário clica no botão de "rodar".

+ +
function play() {
+  document.querySelector(".box").className = "box";
+  window.requestAnimationFrame(function(time) {
+    window.requestAnimationFrame(function(time) {
+      document.querySelector(".box").className = "box changing";
+    });
+  });
+}
+ +

Isso parece esquisito, não parece? É porque a única maneira de executar uma animação novamente é removendo o efeito de animação, deixar o documento recomputar os estilos para que ele saiba que você fez isso, e então adicionar o efeito de animação de volta ao elemento. Para fazer isso acontecer temos que ser criativos.

+ +

Aqui está o que acontece quando a função play() é chamada:

+ +
    +
  1. The box's list of CSS classes is reset to simply "box". This has the effect of removing any other classes currently applied to the box, including the "changing" class that handles animation. In other words, we're removing the animation effect from the box. However, changes to the class list don't take effect until the style recomputation is complete and a refresh has occurred to reflect the change.
  2. +
  3. To be sure that the styles are recalculated, we use {{domxref("window.requestAnimationFrame()")}}, specifying a callback. Our callback gets executed just before the next repaint of the document. The problem for us is that because it's before the repaint, the style recomputation hasn't actually happened yet! So...
  4. +
  5. Our callback cleverly calls requestAnimationFrame() a second time! This time, the callback is run before the next repaint, which is after the style recomputation has occurred. This callback adds the "changing" class back onto the box, so that the repaint will start the animation once again.
  6. +
+ +

Claro, também precisamos adicionar um tratador de evento para o nosso botão de "rodar" para que ele de fato faça algo:

+ +
document.querySelector(".runButton").addEventListener("click", play, false);
+ +

Resultado

+ +

{{ EmbedLiveSample('Run_an_animation_again', 320, 160) }}

+ +

Veja também

+ +
    +
  • Animações CSS
  • +
  • Usando Animações CSS
  • +
  • {{domxref("Window.requestAnimationFrame()")}}
  • +
diff --git "a/files/pt-br/web/css/css_animations/usando_anima\303\247\303\265es_css/index.html" "b/files/pt-br/web/css/css_animations/usando_anima\303\247\303\265es_css/index.html" new file mode 100644 index 0000000000..4bdd91ad9f --- /dev/null +++ "b/files/pt-br/web/css/css_animations/usando_anima\303\247\303\265es_css/index.html" @@ -0,0 +1,332 @@ +--- +title: Usando animações CSS +slug: Web/CSS/CSS_Animations/Usando_animações_CSS +tags: + - Advanced + - CSS + - CSS Animations + - Example + - Experimental + - Guide +translation_of: Web/CSS/CSS_Animations/Using_CSS_animations +--- +

{{SeeCompatTable}}{{CSSRef}}

+ +

Animações CSS tornam possível animar transições de um estilo CSS para outro. Animações se consistem de dois componentes: um estilo descrevendo a animação e um set de keyframes que indicam o estado final e inicial do estilo CSS da animação, bem como possíveis waypoints intermediários ao longo do caminho.

+ +

Existem três vantagens chave para animações CSS além das técnicas tradicionais de animação dirigidas por script:

+ +
    +
  1. São de fácil utilização para animações simples; você pode criá-las sem mesmo ter que conhecer JavaScript.
  2. +
  3. As animações executam bem, mesmo sobre moderada carga do sistema. Animações simples podem normalmente ser executadas precariamente em JavaScript (a não ser que sejam bem feitas). A ferramenta de renderização pode usar frame-skipping e outras técnicas para manter a performance o mais estável possível.
  4. +
  5. Deixando o navegador controlar a sequência de animação permite ao navegador otimizar a performance e eficiência em, por exemplo, reduzir a frequência de update de animações correndo em abas que não estão visíveis no momento.
  6. +
+ +

Configurando a animação

+ +

Para criar uma sequência de animação CSS, você estiliza o elemento que deseja animar com a propriedade {{ cssxref("animation") }} ou suas sub-propriedades. Isso permite que você configure a sincronização da animação, bem como outros detalhes de como a de como a sequência de animação deveria progredir. Isso não configura a aparência atual da animação, que é feita usando a regra com parênteses (at-rule) {{ cssxref("@keyframes") }} como descrito em {{ anch("Defining the animation sequence using keyframes") }} abaixo.

+ +

As sub-propriedades da propriedade {{cssxref("animation")}} são:

+ +
+
{{ cssxref("animation-delay") }}
+
Configura o delay entre o tempo em que o elemento é carregado e o inicio da sequência de animação.
+
{{ cssxref("animation-direction") }}
+
Configura se a animação deve ou nao alternar a direção em cada execução durante a sequência ou voltar ao ponto inicial e se repetir.
+
{{ cssxref("animation-duration") }}
+
Configura o tempo que uma animação deveria levar para completar um ciclo.
+
{{ cssxref("animation-iteration-count") }}
+
Configura o numero de vezes que uma animação deveria se repetir; você pode especificar infinito para repetir a animação indefinidamente.
+
{{ cssxref("animation-name") }}
+
Especifica o nome da regra com parênteses (at-rule) {{ cssxref("@keyframes") }} at-rule descrevendo os keyframes da animação.
+
{{ cssxref("animation-play-state") }}
+
Permite voce pausar e resumir a sequência da animação.
+
{{ cssxref("animation-timing-function") }}
+
Configura a sincronização da animação; que é, como a animação transita por keyframes, por estabilizar curvas de aceleração.
+
{{ cssxref("animation-fill-mode") }}
+
Configura que valores são aplicados pela animação antes e depois de se executar.
+
+ +

Definindo a sequência de animação usando keyframes

+ +

Uma vez que você configurou a sincronização da animação, você precisa definir a aparência da animação. Isso é feito por estabelecer duas ou mais keyframes usando a regra com parênteses (at-rule) {{cssxref("@keyframes")}}. Cada keyframe descreve como o elemento animado deveria se renderizar a um tempo dado durante a sequência de animação.

+ +

Como a sincronização da animação é definida por um estilo CSS que configura a animação, keyframes usam uma {{cssxref("percentage")}} para indicar o tempo durante a sequência de animação que eles fazem parte. 0% indica o primeiro momento da sequência de animação, enquanto 100% indica o estado final da animação. Esses dois tempos devem ser especificados para que o navegador então saiba onde a animação deve começar e parar; por serem tão importantes, esses dois tempos tem expressões equivalentes especiais: from e to.

+ +

Você pode opcionalmente incluir keyframes adicionais que descrevem passos intermediários ao longo do caminho do ponto inicial ao ponto final da animação.

+ +

Exemplos

+ +
Nota Os exemplos aqui não usam nenhum prefixo nas propriedades de animação CSS. Navegadores mais antigos podem precisar de prefixos; os exemplos ao vivo que você pode clicar pra ver em seu navegadores também incluem as versões prefixadas -webkit.
+ +

Fazendo o texto deslizar através da janela do navegador

+ +

Esse exemplo simples estiliza o elemento {{HTMLElement("p")}} onde o elemento então desliza para dentro vindo de fora da lateral direita da janela do navegador.

+ +

Perceba que animações como essa podem fazer com que a página se torne mais larga que a janela do navegador. Para evitar esse problema coloque o elemento a ser animado dentro de um container, e atribua {{cssxref("overflow")}}:hidden ao container.

+ +
p {
+  animation-duration: 3s;
+  animation-name: slidein;
+}
+
+@keyframes slidein {
+  from {
+    margin-left: 100%;
+    width: 300%
+  }
+
+  to {
+    margin-left: 0%;
+    width: 100%;
+  }
+}
+
+ +

O estilo para o elemento {{ HTMLElement("p") }} aqui especifica que a animação deveria levar 3 segundos para executar do início ao fim, usando a propriedade {{cssxref("animation-duration")}}, e que o nome da regra com parênteses (at-rule){{cssxref("@keyframes")}} definindo os keyframes para a sequência de animação é nomeado por "slidein".

+ +

Se quiséssemos quaisquer estilização customizada no elemento {{ HTMLElement("p") }} para aparecer em navegadores que não suportam animações CSS, incluiríamos aqui também; no entanto, nesse caso não queremos nenhuma estilização customizada a não ser o efeito da animação.

+ +

Os keyframes são definidos utilizando-se as regras{{cssxref("@keyframes") }}. Neste caso, utilizamos apenas dois keyframes. O primeiro ocorre no progresso de 0% (ou seja, o primeiro keyframe da animação, através do pseudônimo from). Nesta etapa, configuramos a margem esquerda do elemento para ser 100% - quer dizer, como a margem está à esquerda e com valor 100%, o elemento irá se deslocar para o seu limite, ou seja, para a parte direita – e sua largura será de 300%, ou seja, 3 vezes a largura do seu tamanho original. Isto faz com que o elemento, em seu primeiro frame da animação, seja “empurrado” para fora do limite da parte direita da janela do navegador.

+ +

O segundo (e último) keyframe ocorre na etapa 100% do progresso (ou seja, o último keyframe da animação, através do pseudônimo to). A margem esquerda está com valor de 0% e a largura do elemento está com valor de 100%. Isto resulta na animação do elemento {{ HTMLElement("p") }}, que entra gradativamente na área de conteúdo até atingir uma margem esquerda de 0%.

+ +
 
+ +

A Caterpillar e a Alice se olharam por algum tempo em silêncio: Finalmente, a Caterpillar tirou o narguilé da boca e dirigiu-se Ela com uma voz lenta e sonolenta.

+ +

{{EmbedLiveSample("Making_text_slide_across_the_browser_window","100%","250")}}

+ +

Adicionando outro keyframe

+ +

Vamos adicionar outro keyframe à animação do exemplo anterior. Digamos que nós queremos que o tamanho da fonte aumente durante o movimento da direita para a esquerda por um determinado momento, e que depois ele reduzisse ao seu tamanho original. Você precisaria simplesmente adicionar este keyframe:

+ +
75% {
+  font-size: 300%;
+  margin-left: 25%;
+  width: 150%;
+}
+
+ + + + + +

A Caterpillar e a Alice se olharam por algum tempo em silêncio: Finalmente, a Caterpillar tirou o narguilé da boca e dirigiu-se Ela com uma voz lenta e sonolenta.

+ +

Isso indica ao navegador que até atingir a etapa 75% do progresso da sequência da animação o elemento deve ter 25% no valor da sua margem esquerda e sua largura deve ser de 150%.

+ +

{{EmbedLiveSample("Adicionando_outro_keyframe","100%","250")}}

+ +

Faça repetir-se

+ +

Para fazer a animação se repetir, simplesmente use a propriedade{{ cssxref("animation-iteration-count") }} para indicar a quantidade de vezes que a animação deve se repetir. Neste caso, vamos usar infinite para que a animação se repita indefinidamente:

+ +
p {
+  animation-duration: 3s;
+  animation-name: slidein;
+  animation-iteration-count: infinite;
+}
+
+ + + + + +

A Caterpillar e a Alice se olharam por algum tempo em silêncio: Finalmente, a Caterpillar tirou o narguilé da boca e dirigiu-se Ela com uma voz linda e sonolenta.

+ +

{{EmbedLiveSample("Faça_repetir-se","100%","250")}}

+ +

Fazendo a animação se mover para trás e para frente

+ +

Com o exemplo anterior, fizemos a animação se repetir, mas é muito estranho tê-la pulando lá do início toda vez que a animação inicia. O que nós realmente queremos é que a animação se mova para trás e para frente por toda tela. Isso é facilmente realizado se adicionarmos o valor alternate à propriedade {{cssxref("animation-direction")}}:

+ +
p {
+  animation-duration: 3s;
+  animation-name: slidein;
+  animation-iteration-count: infinite;
+  animation-direction: alternate;
+}
+
+ + + +
<p> A Lagarta e Alice olharam-se por algum tempo em silêncio:
+finalmente, a Lagarta tirou o narguilé da boca e dirigiu-se a
+ela com uma voz lânguida e sonolenta.</p>
+ +

{{EmbedLiveSample("Fazendo_a_animação_se_mover_para_trás_e_para_frente","100%","250")}}

+ +

Usando eventos de animação

+ +

Você pode ter controle adicional sobre animações -- como também informações úteis sobre elas -- através do uso de eventos de animação. Esses eventos, representados pelo objeto {{ domxref("event/AnimationEvent", "AnimationEvent") }} , podem ser usados para detectar quando animações iniciam, terminam, e começam uma nova iteração. Cada evento inclui o tempo no qual ele ocorreu como também o nome da animação que lançou o evento.

+ +

Nós vamos modificar o exemplo de deslizamento de texto para gerar alguma informação sobre cada evento de animação quando ele ocorrer, para que possamos perceber como eles funcionam.

+ +

Adicionando o CSS

+ +

Nós começamos criando o CSS para a animação. Essa animação vai durar por 3 segundos, se chamar "slidein", repetir 3 vezes, e alternar a direção cada vez. No {{ cssxref("@keyframes") }}, a largura (width) e a margem esquerda (margin-left) são manipulados para fazer o elemento deslizar na tela.

+ +
.slidein {
+  -moz-animation-duration: 3s;
+  -webkit-animation-duration: 3s;
+  animation-duration: 3s;
+  -moz-animation-name: slidein;
+  -webkit-animation-name: slidein;
+  animation-name: slidein;
+  -moz-animation-iteration-count: 3;
+  -webkit-animation-iteration-count: 3;
+  animation-iteration-count: 3;
+  -moz-animation-direction: alternate;
+  -webkit-animation-direction: alternate;
+  animation-direction: alternate;
+}
+
+@-moz-keyframes slidein {
+  from {
+    margin-left:100%;
+    width:300%
+  }
+
+  to {
+    margin-left:0%;
+    width:100%;
+  }
+}
+
+@-webkit-keyframes slidein {
+  from {
+    margin-left:100%;
+    width:300%
+  }
+
+  to {
+   margin-left:0%;
+   width:100%;
+ }
+}
+
+@keyframes slidein {
+  from {
+    margin-left:100%;
+    width:300%
+  }
+
+  to {
+   margin-left:0%;
+   width:100%;
+ }
+}
+ +

Adicionando animação a lista de eventos

+ +

Nós vamos usar o código JavaScript para escutar todos três possíveis eventos de animação. Esse código configura nossos escutadores de evento; nós o chamamos quando o documento é primeiramente carregado para configurar as coisas.

+ +
var e = document.getElementById("watchme");
+e.addEventListener("animationstart", listener, false);
+e.addEventListener("animationend", listener, false);
+e.addEventListener("animationiteration", listener, false);
+
+e.className = "slidein";
+
+
+ +

Isso é simplesmente código padrão; você pode ter detalhes sobre como ele funciona na documentação para {{ domxref("element.addEventListener()") }}. A última coisa que este código faz é atribuir a classe no elemento o qual estaremos animando para "deslizar" (slidein); nós fazemos isso para iniciar a animação.

+ +

Por que? Porque o evento animationstart dispara assim que a animação começa, e no nosso caso, isso acontece antes do nosso código rodar. Então nós mesmos vamos iniciar a animação através de atribuição da classe do elemento para o estilo que é animado depois do ocorrido.

+ +

Recebendo os eventos

+ +

Os eventos são entregues à função listener(), a qual é mostrada abaixo.

+ +
function listener(e) {
+  var l = document.createElement("li");
+  switch(e.type) {
+    case "animationstart":
+      l.innerHTML = "Started: elapsed time is " + e.elapsedTime;
+      break;
+    case "animationend":
+      l.innerHTML = "Ended: elapsed time is " + e.elapsedTime;
+      break;
+    case "animationiteration":
+      l.innerHTML = "New loop started at time " + e.elapsedTime;
+      break;
+  }
+  document.getElementById("output").appendChild(l);
+}
+
+ +

Esse código também é bem simples. Ele simplemente olha no {{ domxref("event.type") }} para determinar qual tipo de evento de animação ocorreu, então adiciona uma nota apropriada no {{ HTMLElement("ul") }} (lista não ordenada) que estamos usando para logar esses eventos.

+ +

A saída, quando tudo foi dito e feito, parece com algo assim:

+ +
    +
  • Started: elapsed time is 0
  • +
  • New loop started at time 3.01200008392334
  • +
  • New loop started at time 6.00600004196167
  • +
  • Ended: elapsed time is 9.234000205993652
  • +
+ +

Perceba que os tempos são bem próximos, mas não exatamente iguais, àqueles esperados dado o tempo estabelecido quando a animação foi configurada. Perceba também que após a ultima iteração da animação, o evento animationiteration não é enviado; ao invés disso, o evento animationend é enviado.

+ +

O HTML

+ +

Apenas por questão de completude, aqui está o HTML que exibe o conteúdo da pagina, incluindo a lista na qual o script insere informação sobre os eventos recebidos:

+ +
 
+ +

Veja-me mover

+ +

Este exemplo mostra como usar animações CSS para fazer o elemento H1 se mover pela página.

+ +

Além disso, emitimos algum texto sempre que um evento de animação dispara, para que você possa vê-los em ação.

+ +
    +
+ +

{{EmbedLiveSample('Using_animation_events', '600', '300')}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/css/css_background_and_borders/index.html b/files/pt-br/web/css/css_background_and_borders/index.html new file mode 100644 index 0000000000..87b26bd607 --- /dev/null +++ b/files/pt-br/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

+ +
+
    +
  • {{cssxref("background")}}
  • +
  • {{cssxref("background-attachment")}}
  • +
  • {{cssxref("background-clip")}}
  • +
  • {{cssxref("background-color")}}
  • +
  • {{cssxref("background-image")}}
  • +
  • {{cssxref("background-origin")}}
  • +
  • {{cssxref("background-position")}}
  • +
  • {{cssxref("background-repeat")}}
  • +
  • {{cssxref("background-size")}}
  • +
  • {{cssxref("box-shadow")}}
  • +
  • {{cssxref("border")}}
  • +
  • {{cssxref("border-bottom")}}
  • +
  • {{cssxref("border-bottom-color")}}
  • +
  • {{cssxref("border-bottom-left-radius")}}
  • +
  • {{cssxref("border-bottom-right-radius")}}
  • +
  • {{cssxref("border-bottom-style")}}
  • +
  • {{cssxref("border-bottom-width")}}
  • +
  • {{cssxref("border-collapse")}}
  • +
  • {{cssxref("border-color")}}
  • +
  • {{cssxref("border-image")}}
  • +
  • {{cssxref("border-image-outset")}}
  • +
  • {{cssxref("border-image-repeat")}}
  • +
  • {{cssxref("border-image-slice")}}
  • +
  • {{cssxref("border-image-source")}}
  • +
  • {{cssxref("border-image-width")}}
  • +
  • {{cssxref("border-left")}}
  • +
  • {{cssxref("border-left-color")}}
  • +
  • {{cssxref("border-left-style")}}
  • +
  • {{cssxref("border-left-width")}}
  • +
  • {{cssxref("border-radius")}}
  • +
  • {{cssxref("border-right")}}
  • +
  • {{cssxref("border-right-color")}}
  • +
  • {{cssxref("border-right-style")}}
  • +
  • {{cssxref("border-right-width")}}
  • +
  • {{cssxref("border-style")}}
  • +
  • {{cssxref("border-top")}}
  • +
  • {{cssxref("border-top-color")}}
  • +
  • {{cssxref("border-top-left-radius")}}
  • +
  • {{cssxref("border-top-right-radius")}}
  • +
  • {{cssxref("border-top-style")}}
  • +
  • {{cssxref("border-top-width")}}
  • +
  • {{cssxref("border-width")}}
  • +
+
+ +

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-br/web/css/css_background_and_borders/using_css_multiple_backgrounds/index.html b/files/pt-br/web/css/css_background_and_borders/using_css_multiple_backgrounds/index.html new file mode 100644 index 0000000000..cd35421288 --- /dev/null +++ b/files/pt-br/web/css/css_background_and_borders/using_css_multiple_backgrounds/index.html @@ -0,0 +1,57 @@ +--- +title: Multiple backgrounds +slug: Web/CSS/CSS_Background_and_Borders/Using_CSS_multiple_backgrounds +tags: + - CSS + - CSS Background + - Example + - Guide + - Intermediate +translation_of: Web/CSS/CSS_Backgrounds_and_Borders/Using_multiple_backgrounds +--- +

{{CSSRef}}

+ +

Com CSS3, você pode aplicar aos elementos multiplos planos de fundo. Estes ficam em camadas empilhadas uma acima da outra onde o o primeiro fundo dado será desenhado no topo e apenas o último fundo da lista poderá definir uma cor sólida de fundo.

+ +

Especificar planos de fundo múltplos é fácil:

+ +
.minhaClasse {
+  background: fundo1, fundo2, ..., fundoN;
+}
+
+ +

Você pode fazer isso com a propriedade reduzida {{ cssxref("background") }} e também com as propriedade individuais, com a excessão de {{ cssxref("background-color") }}. Isto é, as seguintes propriedades de plano de fundo podem ser especificadas com uma lista, uma por fundo: {{ 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 planos de fundos estão empilhados: o logo do Firefox, um degradê linear, 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;
+}
+
+ + + + + + + + + + + + +
Captura de TelaDemonstração
css_multibg.png 
+ +

Como pode ver, o logo do firefox (listado primeiro) está no topo, seguido do gradiente que está uma camada acima do fundo florido. Cada uma das sub-propriedade subsequente, ({{ cssxref("background-repeat") }} e {{ cssxref("background-position") }}) se aplicam aos fundos correspondentes. Então o primeiro valor para {{ cssxref("background-repeat") }} se aplica ao primeiro plano de fundo (o mais da frente), e assim por adiante.

+ +

Veja também

+ + diff --git a/files/pt-br/web/css/css_basic_user_interface/index.html b/files/pt-br/web/css/css_basic_user_interface/index.html new file mode 100644 index 0000000000..a8acf19b3b --- /dev/null +++ b/files/pt-br/web/css/css_basic_user_interface/index.html @@ -0,0 +1,74 @@ +--- +title: CSS Basic User Interface +slug: Web/CSS/CSS_Basic_User_Interface +tags: + - CSS + - CSS Basic User Interface + - Overview + - Reference +translation_of: Web/CSS/CSS_Basic_User_Interface +--- +

{{CSSRef}}

+ +

CSS Basic User Interface é um módulo CSS que permite definir a renderização e a funcionalidade de recursos relacionados à interface do usuário.

+ +

Referência

+ +

Propriedades

+ +
+
    +
  • {{CSSxRef("appearance")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef("box-sizing")}}
  • +
  • {{CSSxRef("cursor")}}
  • +
  • {{CSSxRef("ime-mode")}} {{Deprecated_Inline}}
  • +
  • {{CSSxRef("nav-down")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef("nav-left")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef("nav-right")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef("nav-up")}} {{Experimental_Inline}}
  • +
  • {{CSSxRef("outline")}}
  • +
  • {{CSSxRef("outline-width")}}
  • +
  • {{CSSxRef("outline-style")}}
  • +
  • {{CSSxRef("outline-color")}}
  • +
  • {{CSSxRef("outline-offset")}}
  • +
  • {{CSSxRef("resize")}}
  • +
  • {{CSSxRef("text-overflow")}}
  • +
  • {{CSSxRef("user-select")}} {{Experimental_Inline}}
  • +
+
+ +

Guias

+ +
+
Usando valores URL na propriedade cursor
+
Explica como uma URL pode ser usada com a propriedade {{CSSxRef("cursor")}} para criar cursores personalizados.
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName("CSS4 Basic UI")}}{{Spec2("CSS4 Basic UI")}} 
{{SpecName("CSS3 Basic UI")}}{{Spec2("CSS3 Basic UI")}} 
{{SpecName("CSS2.1", "ui.html")}}{{Spec2("CSS2.1")}}Definição inicial.
diff --git a/files/pt-br/web/css/css_box_model/index.html b/files/pt-br/web/css/css_box_model/index.html new file mode 100644 index 0000000000..41f2f7cf8b --- /dev/null +++ b/files/pt-br/web/css/css_box_model/index.html @@ -0,0 +1,170 @@ +--- +title: CSS Box Model +slug: Web/CSS/CSS_Box_Model +tags: + - CSS + - CSS Box Model + - CSS Reference + - Modelo de Caixa CSS + - NeedsTranslation + - Overview + - Referencia CSS + - TopicStub +translation_of: Web/CSS/CSS_Box_Model +--- +
{{CSSRef}}
+ +

CSS Box Model (Modelo de Caixa CSS) é um módulo de CSS que define caixas retangulares, incluindo preenchimento (padding) e margem (margin), que são gerados por elementos e dispostos de acordo com o modelo de formato visual.

+ +

Referência

+ +

Propriedades

+ +

Propriedades que controlam o fluxo de conteúdo em uma caixa

+ +
+
    +
  • {{cssxref("box-decoration-break")}}
  • +
  • {{cssxref("box-sizing")}}
  • +
  • {{cssxref("overflow")}}
  • +
  • {{cssxref("overflow-x")}}
  • +
  • {{cssxref("overflow-y")}}
  • +
+
+ +

Propriedades que controlam o tamanho de uma caxia

+ +
+
    +
  • {{cssxref("height")}}
  • +
  • {{cssxref("width")}}
  • +
  • {{cssxref("max-height")}}
  • +
  • {{cssxref("max-width")}}
  • +
  • {{cssxref("min-height")}}
  • +
  • {{cssxref("min-width")}}
  • +
+
+ +

Propriedades que controlam as margens de uma caixa

+ +
+
    +
  • {{cssxref("margin")}}
  • +
  • {{cssxref("margin-bottom")}}
  • +
  • {{cssxref("margin-left")}}
  • +
  • {{cssxref("margin-right")}}
  • +
  • {{cssxref("margin-top")}}
  • +
+
+ +

Propriedades que controlam o preenchimento (padding) de uma caixa

+ +
+
    +
  • {{cssxref("padding")}}
  • +
  • {{cssxref("padding-bottom")}}
  • +
  • {{cssxref("padding-left")}}
  • +
  • {{cssxref("padding-right")}}
  • +
  • {{cssxref("padding-top")}}
  • +
+
+ +

Outras propriedades

+ +
+
    +
  • {{cssxref("box-shadow")}}
  • +
  • {{cssxref("visibility")}}
  • +
+
+ +

Guias e ferramentas

+ +
+
+
Introdução ao modelo de caixa CSS
+
Explicações de uma concepção fundamental no CSS, o modelo de caixa: descreve o sentido de margem, preenchimento, tambem como as diferentes áreas da caixa.
+
Dominando o colapso da margem
+
Na maioria dos casos, duas margens adjacentes são colapsadas em uma. Este artigo descreve quando isso acontecwe e como controlar isso.
+
Gerador de sombra de caixa
+
Uma ferramenta interativa que permite criar sombras visualmente e gerar a sintaxe necessária para a propriedade {{cssxref("box-shadow")}}.
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoSituaçãoComentário
{{SpecName("CSS3 Box")}}{{Spec2("CSS3 Box")}}
{{SpecName("CSS2.1", "box.html")}}{{Spec2("CSS2.1")}}
{{SpecName("CSS1")}}{{Spec2("CSS1")}}Initial definition
+ + + +

{{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-br/web/css/css_box_model/margin_collapsing/index.html b/files/pt-br/web/css/css_box_model/margin_collapsing/index.html new file mode 100644 index 0000000000..cb658d4131 --- /dev/null +++ b/files/pt-br/web/css/css_box_model/margin_collapsing/index.html @@ -0,0 +1,74 @@ +--- +title: Dominando margin collapsing +slug: Web/CSS/CSS_Box_Model/margin_collapsing +tags: + - CSS + - CSS Box Model + - Guía + - Intermediario(2) + - Referencia +translation_of: Web/CSS/CSS_Box_Model/Mastering_margin_collapsing +--- +
{{CSSRef}}
+ +
As margens superior e inferior dos blocos às vezes são combinadas(colapsadas/reduzidas) para uma única margem cujo o tamanho é a maior das margens (se os elementos tiverem a mesma margem, uma delas não será somada), combinado a ele, um comportamento conhecido como margin collapsing. Note que as margens de elementos flutuantes e posicionados de forma absoluta nunca colapsam.
+ +
 
+ +

Margin collapsing ocorre em três casos básicos:

+ +
+
Irmãos adjacentes
+
As margens de irmãos adjacentes são colapsadas (execeto quando  o último irmão precisar ser limpado devido ao uso de floats  em elementos anteriores ). Por exemplo:
+
+
 <p>A margem inferior deste parágrafo é colapsada...</p>
+ <p>... com margem superior deste parágrafo.</p>
+
+
+
Pai e primeiro/último filho
+
Se não houver border, padding, parte inline, contexto de formatação de bloco criado ou livre para separar o {{cssxref("margin-top")}} de um bloco do {{cssxref("margin-top")}} do seu primeiro bloco filho, ou nenhum border, padding, conteúdo inline, {{cssxref("height")}}, {{cssxref("min-height")}}, ou {{cssxref("max-height")}} para separar o  {{cssxref("margin-bottom")}} de um bloco do {{cssxref("margin-bottom")}} do seu último filho, então essas margens colapsam. A margem colapsada acaba fora do pai.
+
 
+
+ +
+
Blocos vázios
+
Se não houver border, padding, conteúdo inline, {{cssxref("height")}}, ou  {{cssxref("min-height")}} para separar um bloco {{cssxref("margin-top")}} de sua {{cssxref("margin-bottom")}}, então as margens superior e inferior são colapsadas.
+
 
+
+ +

Algumas coisas podem ser observadas:

+ +
    +
  • Margin collapsing mais complexo (de mais de duas margens) ocorrem quando esses casos são combinados.
  • +
  • Essas regras se aplicam até mesmo a margens que são zero, portanto a margem e um primeiro/último filho termina fora de seu pai(de acordo com as regras acima) sendo a margem do pai zero ou não.
  • +
  • Quando margens negativas são envolvidas, o tamanho da margem colapsada é a soma da maior margem positiva e da menor margem negativa(a mais negativa).
  • +
  • Se ambos são negativos, o valor negativo maior será usado. Essa definição se aplica a elementos adjacentes e a elementos aninhados. 
  • +
+ +

Margens de elementos flutuantes e posicionados de forma absoluta nunca colapsam.

+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspeficicaçõesStatusComentário
{{SpecName("CSS2.1", "box.html#collapsing-margins", "margin collapsing")}}{{Spec2("CSS2.1")}}Definição inicial
+ +

Veja Também

+ + diff --git a/files/pt-br/web/css/css_colors/seletor_de_cores/index.html b/files/pt-br/web/css/css_colors/seletor_de_cores/index.html new file mode 100644 index 0000000000..a98aaf9342 --- /dev/null +++ b/files/pt-br/web/css/css_colors/seletor_de_cores/index.html @@ -0,0 +1,3241 @@ +--- +title: Seletor de cores +slug: Web/CSS/CSS_Colors/seletor_de_cores +tags: + - CSS + - Cores CSS + - Cores HTML + - Ferramenta para Seleção de Cores CSS + - Ferramenta para Seleção de Cores HTML + - Ferramentas + - Seletor de Cores + - Seletor de Cores CSS + - Seletor de Cores HTML + - cor + - cores +translation_of: Web/CSS/CSS_Colors/Color_picker_tool +--- +
+

ColorPicker tool

+ +

HTML Content

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

+ +
/*
+ * 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 com cores personalizadas para uso na web. Ela também facilita a conversão entre vários formatos de cores suportados por CSS, incluindo cores HEXA, RGB (vermelho, verde, azul) e HSL (tonalidade, saturação, luminosidade). Controle sobre o canal alfa também é suportado nos formatos RGB (rgba) e (hsla).

+ +

Enquanto você ajusta os parâmetros que definem a cor, ela é apresentada nos 3 formatos padrão para CSS web. Além disso, com base na seleção de cor atual, é gerada uma paleta para HSL, HSV e também alfa. O selecionador de cor estilo "conta-gotas" pode alternar os estilos HSL e HSV. Você também pode testar as cores e ver como elas se sobrepõem umas sobre às outras. 

+ +

{{ EmbedLiveSample('ColorPicker_Tool', '100%', '900') }}

+ +

As cores geradas por você acima podem ser usadas em qualquer lugar em que a cor é usada em CSS e HTML, a menos que seja indicado de outra forma.

+ +

Veja também

+ +

Para mais aplicações de cores, veja:

+ + diff --git a/files/pt-br/web/css/css_columns/index.html b/files/pt-br/web/css/css_columns/index.html new file mode 100644 index 0000000000..ea227ced5d --- /dev/null +++ b/files/pt-br/web/css/css_columns/index.html @@ -0,0 +1,114 @@ +--- +title: CSS Columns +slug: Web/CSS/CSS_Columns +tags: + - CSS + - CSS Reference + - NeedsTranslation + - Overview + - TopicStub +translation_of: Web/CSS/CSS_Columns +--- +
{{CSSRef}}
+ +

CSS Columns is a module of CSS that defines a multi-column layout, allowing to express how content should flow between columns and how gaps and rules are handled.

+ +

Reference

+ +

CSS Properties

+ +
+
    +
  • {{cssxref("break-after")}}
  • +
  • {{cssxref("break-before")}}
  • +
  • {{cssxref("break-inside")}}
  • +
  • {{cssxref("column-count")}}
  • +
  • {{cssxref("column-fill")}}
  • +
  • {{cssxref("column-gap")}}
  • +
  • {{cssxref("column-rule")}}
  • +
  • {{cssxref("column-rule-color")}}
  • +
  • {{cssxref("column-rule-style")}}
  • +
  • {{cssxref("column-rule-width")}}
  • +
  • {{cssxref("column-span")}}
  • +
  • {{cssxref("column-width")}}
  • +
  • {{cssxref("columns")}}
  • +
+
+ +

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')}}1011.1
+ 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')}}1011.5
+ 32{{property_prefix('-webkit')}}
3.2{{property_prefix('-webkit')}}
+
diff --git a/files/pt-br/web/css/css_display/index.html b/files/pt-br/web/css/css_display/index.html new file mode 100644 index 0000000000..426aece9cd --- /dev/null +++ b/files/pt-br/web/css/css_display/index.html @@ -0,0 +1,110 @@ +--- +title: CSS Display +slug: Web/CSS/CSS_Display +translation_of: Web/CSS/CSS_Display +--- +
{{CSSRef}}
+ +

CSS Display É um módulo de CSS que define como a árvore da caixa de formatação CSS é gerada a partir da árvore de elementos do documento e define as propriedades que a controlam.

+ +

Referência

+ +

CSS Propriedades

+ +
+
    +
  • {{CSSxRef("display")}}
  • +
+
+ +

CSS tipos de dados

+ +
+
    +
  • {{CSSxRef("<display-outside>")}}
  • +
  • {{CSSxRef("<display-inside>")}}
  • +
  • {{CSSxRef("<display-listitem>")}}
  • +
  • {{CSSxRef("<display-box>")}}
  • +
  • {{CSSxRef("<display-internal>")}}
  • +
  • {{CSSxRef("<display-legacy>")}}
  • +
+
+ +

Guias

+ +

CSS Fluxo Layout (display: block, display: inline)

+ + + +

display: flex

+ + + +

display: grid

+ + + +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("CSS3 Display", "#the-display-properties", "display")}}{{Spec2("CSS3 Display")}}Adicionado run-in, flow, flow-root, contents e valores de várias palavras-chave.
{{SpecName("CSS2.1", "visuren.html#display-prop", "display")}}{{Spec2("CSS2.1")}}Adicionados os valores do modelo de tabela e inline-block.
{{SpecName("CSS1", "#display", "display")}}{{Spec2("CSS1")}}Definição inicial. Valores básicos: none, block, inline e list-item.
+ +

Além do nível de especificação de exibição CSS 3, outras especificações definem o comportamento de vários valores da exibição.

+ +

Compatibilidade do navegador

+ + + +

{{Compat("css.properties.display", 10)}}

diff --git a/files/pt-br/web/css/css_flexible_box_layout/aligning_items_in_a_flex_container/index.html b/files/pt-br/web/css/css_flexible_box_layout/aligning_items_in_a_flex_container/index.html new file mode 100644 index 0000000000..971912174f --- /dev/null +++ b/files/pt-br/web/css/css_flexible_box_layout/aligning_items_in_a_flex_container/index.html @@ -0,0 +1,209 @@ +--- +title: Aligning Items in a Flex Container +slug: Web/CSS/CSS_Flexible_Box_Layout/Aligning_Items_in_a_Flex_Container +translation_of: Web/CSS/CSS_Flexible_Box_Layout/Aligning_Items_in_a_Flex_Container +--- +

{{CSSRef}}

+ +

Uma das razões pela qual flexbox rapidamente despertou interesse dos desenvolvedores web é que ela trouxe capacidade de alinhamento apropriada para web pela primeira vez. Tem capacidade de alinhamento vertical apropriada, e assim finalmente podemos de modo fácil centralizar uma caixa. Neste guia, veremos detalhadamente como as propriedades de alinhamento e justificação funcionam no Flexbox.

+ +

Para centralizar nossa caixa nós usamos a propriedade align-items para alinhar nosso item no eixo transversal, que neste caso é o eixo do bloco indo verticalmente. Nós usamos justify-content para alinhar o item no eixo principal, que neste caso é o eixo indo horizontalmente.

+ +

A containing element with another box centered inside it.

+ +

Você pode dar uma olhada no código deste exemplo abaixo. Altere o tamanho do container ou elemento aninhado e o elemento aninhado sempre permanece centralizado.

+ +

{{EmbedGHLiveSample("css-examples/flexbox/alignment/intro.html", '100%', 700)}}

+ +

Propriedades que controlam o alinhamento

+ +

As propriedades que nós veremos neste guia são as seguintes.

+ +
    +
  • {{cssxref("justify-content")}} — controla o alinhamento de todos os itens no eixo principal.
  • +
  • {{cssxref("align-items")}} — controla o alinhamento de todos os itens no eixo transversal.
  • +
  • {{cssxref("align-self")}} — controla o alinhamento individual de um item no eixo transversal.
  • +
  • {{cssxref("align-content")}} — descrito na especificação como “packing flex lines”; controla o espaço entre as linhas no eixo transversal.
  • +
+ +

Nós também descobriremos como margens automáticas podem ser utilizadas para o alinhamento no flexbox.

+ +
+

Note: The alignment properties in Flexbox have been placed into their own specification — CSS Box Alignment Level 3. It is expected that this spec will ultimately supersede the properties as defined in Flexbox Level One.

+
+ +

The Cross Axis

+ +

As propriedades align-items e align-self controlam o alinhamento dos nossos itens no eixo transversal, em colunas se flex-direction é row e entre linhas se flex-direction é column.

+ +

Nós estamos usando o alinhamento transversal na maioria dos exemplos. Se adicionarmos display: flex para um contêiner, todos os itens filhos se tornam itens flexíveis organizados em uma linha. Todos irão se esticar para serem tão altos quanto o item mais alto, pois este item define a altura dos itens no eixo transversal. Se o seu contêiner possui uma altura definida, então os itens se estenderão para esta altura, independemente da quantidade de conteúdo que está dentro deste 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 itens passam a ter a mesma altura é que o valor inicial do align-items, a propriedade que controla o alinhamento do eixo transversal, está definida como stretch.

+ +

Nós podemos usar outros valores para controlar como os itens se alinham:

+ +
    +
  • align-items: flex-start
  • +
  • align-items: flex-end
  • +
  • align-items: center
  • +
  • align-items: stretch
  • +
  • align-items: baseline
  • +
+ +

No exemplo abaixo, o valor do align-items está definido como stretch. Tente outros valores e veja como todos os itens se alinham no contêiner.

+ +

{{EmbedGHLiveSample("css-examples/flexbox/alignment/align-items.html", '100%', 520)}} 

+ +

Alinhando um item com align-self

+ +

A propriedade align-items adiciona a propriedade align-self em todos os itens flex como um grupo. Ou seja, você pode explicitamente declarar a propriedade align-self para impactar um único item. A propriedade align-self aceita todos os mesmo valores que align-items mais o valor auto, que irá resetar o valor que está configurado no container flex.

+ +

Neste próximo exemplo, o container flex possui align-items: flex-start, que implica em todos os itens estarem alinhados ao início do eixo transversal. Foquei no primeiro item usando o seletor first-child e configurei este item para align-self: stretch; outro item foi selecionado usando a classe selected e align-self: center. Você pode mudar o valor do align-items ou mudar o valor do align-self para focar em itens individuais para ver como funciona.

+ +

{{EmbedGHLiveSample("css-examples/flexbox/alignment/align-self.html", '100%', 650)}}

+ +

Changing the main axis

+ +

So far we have looked at the behaviour when our flex-direction is row, and while working in a language written top to bottom. This means that the main axis runs along the row horizontally, and our cross axis alignment moves the items up and down.

+ +

Three items, the first aligned to flex-start, second to center, third to flex-end. Aligning on the vertical axis.

+ +

If we change our flex-direction to column, align-items and align-self will align the items to the left and right.

+ +

Three items, the first aligned to flex-start, second to center, third to flex-end. Aligning on the horizontal axis.

+ +

You can try this out in the example below, which has a flex container with flex-direction: column yet otherwise is exactly the same as the previous example.

+ +

{{EmbedGHLiveSample("css-examples/flexbox/alignment/align-self-column.html", '100%', 730)}} 

+ +

Aligning content on the cross axis — the align-content property

+ +

So far we have been aligning the items, or an individual item inside the area defined by the flex-container. If you have a wrapped multiple-line flex container then you might also want to use the align-content property to control the distribution of space between the rows. In the specification this is described as packing flex lines.

+ +

For align-content to work you need more height in your flex container than is required to display the items. It then works on all the items as a set, and dictates what happens with that free space, and the alignment of the entire set of items within it.

+ +

The align-content property takes the following values:

+ +
    +
  • align-content: flex-start
  • +
  • align-content: flex-end
  • +
  • align-content: center
  • +
  • align-content: space-between
  • +
  • align-content: space-around
  • +
  • align-content: stretch
  • +
  • align-content: space-evenly (not defined in the Flexbox specification)
  • +
+ +

In the live example below, the flex container has a height of 400 pixels, which is more than needed to display our items. The value of align-content is space-between, which means that the available space is shared out between the flex lines, which are placed flush with the start and end of the container on the cross axis.

+ +

Try out the other values to see how the align-content property works.

+ +

{{EmbedGHLiveSample("css-examples/flexbox/alignment/align-content.html", '100%', 850)}} 

+ +

Once again we can switch our flex-direction to column in order to see how this property behaves when we are working by column. As before, we need enough space in the cross axis to have some free space after displaying all of the items.

+ +

{{EmbedGHLiveSample("css-examples/flexbox/alignment/align-content-column.html", '100%', 860)}} 

+ +
+

Note: the value space-evenly is not defined in the flexbox specification and is a later addition to the Box Alignment specification. Browser support for this value is not as good as that of the values defined in the flexbox spec.

+
+ +

See the documentation for justify-content on MDN for more details on all of these values and browser support.

+ +

Aligning content on the main axis

+ +

Now that we have seen how alignment works on the cross axis, we can take a look at the main axis. Here we only have one property available to us — justify-content. This is because we are only dealing with items as a group on the main axis. With 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.

+ +
    +
  • justify-content: flex-start
  • +
  • justify-content: flex-end
  • +
  • justify-content: center
  • +
  • justify-content: space-between
  • +
  • justify-content: space-around
  • +
  • justify-content: stretch
  • +
  • justify-content: space-evenly (not defined in the Flexbox specification)
  • +
+ +

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

+ +

Alignment and Writing Modes

+ +

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

+ +

Alignment and 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 at 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

+ +

Using auto margins for main axis alignment

+ +

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 centering 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)}} 

+ +

Future alignment features for 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, and in Firefox 63 you will find the first browser implementation of the gap properties in flex layout.

+ +

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.

+ +

See Also

+ + diff --git a/files/pt-br/web/css/css_flexible_box_layout/conceitos_basicos_do_flexbox/index.html b/files/pt-br/web/css/css_flexible_box_layout/conceitos_basicos_do_flexbox/index.html new file mode 100644 index 0000000000..05318caa79 --- /dev/null +++ b/files/pt-br/web/css/css_flexible_box_layout/conceitos_basicos_do_flexbox/index.html @@ -0,0 +1,239 @@ +--- +title: Conceitos básicos de flexbox +slug: Web/CSS/CSS_Flexible_Box_Layout/Conceitos_Basicos_do_Flexbox +tags: + - CSS + - Flex + - Tutorial + - conceitos + - conteiner + - eixos + - flexbox +translation_of: Web/CSS/CSS_Flexible_Box_Layout/Basic_Concepts_of_Flexbox +--- +
{{CSSRef}}
+ +

Flexible Box Module, geralmente chamado de flexbox, foi projetado tanto como um modelo de layout unidimensional quanto como um método capaz de organizar espacialmente os elementos em uma interface, além de possuir capacidades avançadas de alinhamento. Este artigo fornece um resumo das principais funcionalidades do flexbox, as quais exploraremos com mais detalhes no restante deste guia.

+ +

Quando se descreve o flexbox como sendo unidimensional, enfatiza-se o fato de que ele lida com o layout em uma dimensão de cada vez - seja uma linha ou uma coluna. Isto pode ser comparado com o modelo bidimensional de CSS - Layout de Grade, que permite o controle simultâneo das colunas e linhas.

+ +

Os eixos do flexbox

+ +

Ao se utilizar o flexbox, é preciso ter em mente que todas as operações realizadas relacionam-se a dois eixos: o eixo principal e o eixo transversal. O eixo principal é definido através da propriedade flex-direction e o eixo transversal encontra-se na direção perpendicular a ele. Como esses eixos são as engrenagens fundamentais do flexbox é necessário compreender minuciosamente o seu funcionamento.

+ +

Eixo principal

+ +

Conforme descrito acima, a propriedade flex-direction define a direção do eixo principal e pode tem quatro valores possíveis:

+ +
    +
  • row
  • +
  • row-reverse
  • +
  • column
  • +
  • column-reverse
  • +
+ +

Se o valor escolhido for row (linha) ou row-reverse (linha reversa), seu eixo principal se moverá ao longo da linha — na direção inline.

+ +

If flex-direction is set to row the main axis runs along the row in the inline direction.

+ +

Se o valor escolhido for column (coluna) ou column-reverse (coluna reversa) e o eixo principal se moverá do topo até o fim da página — na direção block.

+ +

If flex-direction is set to column the main axis runs in the block direction.

+ +

Eixo transversal

+ +

O eixo transversal é perpendicular ao eixo principal, logo, se a propriedade flex-direction estiver definida nas linhas, como row ou row-reverse, o eixo transversal estará na direção das colunas, como column ou column-reverse.

+ +

If flex-direction is set to row then the cross axis runs in the block direction.

+ +

Se o eixo principal for definido nas colunas, como column ou column-reverse, então o eixo transversal estará na direção das linhas, como row ou row-reverse.

+ +

If flex-direction is set to column then the cross axis runs in the inline direction.

+ +

Compreender a diferença entre os eixos principal e perpendicular é o que importa quando começamos a observar o alinhamento ou justificação dos itens flexíveis (flex items); o flexbox possui propriedades que alinham e justificam o conteúdo ao longo de um eixo ou de outro.

+ +

Linhas de Início e Fim

+ +

Outra área crítica em termos de compreensão é como o Flexbox não faz nenhuma premissa sobre o modo de escrita do documento. No passado, o CSS utilizava fortemente os modos de escrita horizontal e da esquerda para a direita. Métodos modernos de layout abrangem uma variedade de modos de escrita e, portanto, não assumimos mais que uma linha de texto começará no canto superior esquerdo do documento e sigará para o lado direito, com novas linhas aparecendo uma após a as outra.

+ +

Essa discussão sobre a relação entre o flexbox e a especificação do modo de escrita será abordada um artigo posterior, contudo, a descrição a seguir explica brevemente porque não se fala sobre esquerda e direita/ acima e abaixo quando descreve-se a direção para a qual os elementos flex fluem.

+ +

Se o valor da propriedade flex-direction for row (linha), considerando o estilo de escrita ocidental, a borda inicial do eixo principal estará localizada à esquerda e a borda final, à direita.

+ +

Working in English the start edge is on the left.

+ +

Considerando um idioma como o Árabe, que possui um estilo de escrita oriental, teremos o inverso: a borda inicia do eixo principal estará localizada à direita e a borda final, à esquerda.

+ +

The start edge in a RTL language is on the right.

+ +

Em ambos os casos, a borda inicial do eixo transversal está na parte superior do contêiner flex e a borda final, na parte inferior, visto que ambos os idiomas têm um estilo de de escrita horizontal.

+ +

Após um tempo de prática, pensar em termos de início e final ao invés de esquerda e direita se tornará natural e será útil ao lidar com outros métodos de layout, como CSS Grid, que seguem os mesmos padrões.

+ +

Contêiner Flex

+ +

A área de um documento que faz uso do flexbox é chamada de contêiner flex. Para criar essa estrutura, define-se o valor da propriedade {{cssxref("display")}} do elemento representado pelo contêiner como flex ou inline-flex. Desse modo, os elementos-filhos desse contêiner tornar-se-ão do tipo flex. Como todas as propriedades no CSS possuem valores padrão, ao criar um contêiner flex, os elementos nele contidos apresentarão o seguinte comportamento:

+ +
    +
  • Exibição em linha (o padrão do flex-direction é row).
  • +
  • Alinhamento na  borda inicial do eixo principal.
  • +
  • Não há expansão no eixo principal, mas pode haver contração.
  • +
  • Haverá expansão vertical para preencher a altura do eixo transversal.
  • +
  • A propriedade {{cssxref("flex-basis")}} estará definida como auto.
  • +
  • A propriedade {{cssxref("flex-wrap")}} estará definida como nowrap.
  • +
+ +

O resultado final é que todos os elementos serão alinhados em uma linha, usando o tamanho do conteúdo como o tamanho no eixo principal. Se houver mais itens do que é possível caber no container, não haverá uma quebra de linha; ao invés disso, irão ultrapassar o limite horizontal da página. Se alguns elementos forem mais altos que outros, todos os itens se estenderão ao longo do eixo transversal para preencher seu tamanho total.

+ +

É possível conferir essas questões no exemplo prático abaixo. Tente editar ou adicionar mais itens para testar o comportamento inicial do Flexbox.

+ +

{{EmbedGHLiveSample("css-examples/flexbox/basics/the-flex-container.html", '100%', 480)}} 

+ +

Propriedade flex-direction

+ +

A propriedade {{cssxref("flex-direction")}} permite alterar a direção na qual os elementos flex serão exibidos ao longo do eixo principal. Definindo a propriedade flex-direction como row-reverse (linha reversa) ainda teremos os elementos dispostos em uma linha, entretanto, as linhas inicial e final serão trocadas.
+
+ Se mudarmos a flex-direction para a column (coluna), o eixo principal exibirá os elemento em uma coluna. Trocando o valor para column-reverse (coluna reversa) fará com que as linhas inicial e final sejam novamente trocadas.
+
+ No exemplo prático abaixo tem-se a propriedade flex-direction definida como row-reverse. Experimente os outros valores - row, column e column-reverse - para ver o que acontece com o conteúdo.
+
+ {{EmbedGHLiveSample("css-examples/flexbox/basics/flex-direction.html", '100%', 350)}}

+ +

Quebra de linha com "flex-wrap"

+ +

Embora o flexbox seja um modelo unidimensional, é possível fazer com que elementos flex sejam agrupados em múltiplas linhas. Ao fazer isso, considera-se cada linha como um novo contêiner flex. Qualquer distribuição espacial ocorrerá ao longo essa linha, sem referência às linhas de ambos os lados. Para gerar a quebra automática das linhas adicione a propriedade {{cssxref("flex-wrap")}} com o valor wrap. Assim, se elementos forem muito grandes para serem exibidos em uma única linha, eles serão agrupados em outras linhas.

+ +

O exemplo prático abaixo contém elementos flex aos quais foi dada uma determinada largura, cuja soma totaliza um valor grande demais para caber no container. Visto que a propriedade flex-wrap está definida como wrap, os itens serão reorganizados em mais de uma linha. Trocando-se para nowrap, que também é o valor inicial, eles encolherão para caber no contêiner, porque estão usando valores iniciais de flexbox que permitem que os itens encolham. O uso do nowrap causaria um vazamento se os itens não encolhessem ou não diminuíssem o suficiente para caber.

+ +

{{EmbedGHLiveSample("css-examples/flexbox/basics/flex-wrap.html", '100%', 400)}}

+ +

Saiba mais sobre o empacotamento de itens flexíveis no guia Masterização de Empacotamento de Itens Flexíveis (em Inglês).

+ +

Propriedade abreviada flex-flow

+ +

Pode-se combinar as propriedades flex-direction e flex-wrap de forma abreviada através da propriedade {{cssxref("flex-flow")}}. O primeiro valor especificado é o flex-direction e o segundo valor é o flex-wrap.

+ +

No exemplo prático abaixo, tente alterar o primeiro valor para um dos valores permitidos para a propriedade flex-direction - row, row-reverse, column ou column-reverse, e também altere o segundo para wrap e nowrap.

+ +

{{EmbedGHLiveSample("css-examples/flexbox/basics/flex-flow.html", '100%', 400)}}

+ +

Expansão, encolhimento e tamanho dos elementos flex

+ +

Para ter mais controle sobre os elementos flex é possível alterá-los diretamente utilizando as três propriedades abaixo:

+ +
    +
  • {{cssxref("flex-grow")}}
  • +
  • {{cssxref("flex-shrink")}}
  • +
  • {{cssxref("flex-basis")}}
  • +
+ +

Na presente seção, examinar-se-á brevemente tais propriedades. Para se aprofundar neste conteúdo sugete-se o tutorial Taxas de Controle de Elementos Flex ao Longo do Eixo Principal (em inglês).

+ +

Antes que essas propriedades possam fazer sentido, é preciso compreender o conceito de espaço disponível. Quando se modifica o valor das propriedades  acima, altera-se a forma que o espaço disponível é distribuído entre os elementos. Tal conceito de espaço disponível também é relevante quando se trata do alinhamento.

+ +

Conforme o exemplo abaixo, se houver três elementos com 100 pixels de comprimento em um contêiner de 500 pixels, então o espaço total necessário para acomodá-los será de 300 pixels. Desse modo, sobrarão 200 pixels de espaço útil. Se os valores iniciais não forem modificados, então o flexbox posicionará esse espaço após o último item.

+ +

This flex container has available space after laying out the items.

+ +

Se for necessário que os elementos cresçam proprocionamente ou não e preencham o espaço disponível, deverá haver método que faça essa distribuição espacial entre eles, conforme será visto nas seções subsequentes.

+ +

Propriedade flex-basis

+ +

A propriedade flex-basis define o tamanho inicial dos elementos, em unidades de pixel, antes que o espaço remanescente seja redistribuído. O valor inicial desta propriedade é auto — neste caso o navegador observa se os itens possuem o mesmo tamanho. No exemplo acima, todos os itens têm uma largura de 100 pixels, que é utilizada como padrão na propriedade flex-basis.

+ +

Se os elementos não possuírem um tamanho padrão, então as dimensões dos seus conteúdos (imagem, texto, etc) serão passadas como parâmetro para propriedade flex-basis. É por isso que quando escreve-se display: flex no elemento-pai para criar o contêiner, todos os elementos-filhos se organizam em linha e ocupam apenas o espaço necessário para exibir seu conteúdo.

+ +

Propriedade flex-grow

+ +

Com a propriedade flex-grow definida como um inteiro positivo, os elementos flex podem crescer ao longo do eixo principal, a partir do valor mínimo estabelecido no flex-basis. Isto fará com que o elemento se estique e ocupe qualquer espaço disponível nesse eixo ou uma proporção dele, caso outros elementos-irmãos também possam crescer.

+ +

Atribuir o valor 1 à propriedade flex-grow fará com que o espaço disponível no contêiner flex seja igualmente distribuído entre todos os elementos do exemplo acima. Logo, os elementos-filhos irão se expandir para preencher o contêiner no sentido do eixo principal.

+ +

Como visto no parágrafo anterior, a propriedade flex-grow pode ser empregada para distribuir o espaço proporcionalmente entre os elementos de um contêiner, contudo, se atribuirmos ao primeiro elemento o valor 2 parae 1 aos elementos restantes, duas partes serão dadas ao primeiro elemento (100px de 200px totais) e uma parte para cada um dos outros dois elementos (50px de 200px totais).

+ +

Propriedade flex-shrink

+ +

Enquanto a propriedade flex-grow permite aumentar a largura dos elementos dentro do contêiner para completar o espaço disponível no eixo principal, a propriedade flex-shrink faz o oposto, controlando a redução dos mesmos. Caso não haja espaço suficiente para acomodar todos os elementos e o valor da propriedade flex-shrink seja um inteiro positivo, a largura pode ser reduzida a um valor menor do que a definida na propriedade flex-basis. Assim como na propriedade flex-grow, diferentes valores podem ser atribuídos a um elemento de modo que ele encolha mais do que os outros - um elemento cuja propriedade flex-shrink receba um valor inteiro maior irá diminuir mais do que os seus irmão que tenham valores menores.

+ +

O tamanho mínimo do elemento será levado em consideração ao se calcular a quantidade real de encolhimento que ocorrerá, o que significa que a propriedade flex-shrink se comporta de modo potencialmente menos consistente do que a propriedade flex-grow. Examinar-se-á mais detalhadamente o funcionamento desse algoritmo no artigo Taxas de Controle de Elementos Flex ao Longo do Eixo Principal.

+ +
+

Note que os valores para as propriedades flex-grow e flex-shrink são proporcionais.  Particularmente, se tivermos todos os nossos elementos definidos como flex: 1 1 200px e então quisermos que um deles cresça o dobro, temos de definir o elemento como flex: 2 1 200px. Entretanto, podemos escrever flex: 10 1 200px e flex: 20 1 200px se quisermos.

+
+ +

Abreviatura para os valores das propriedades flex

+ +

As propriedades flex-grow, flex-shrink, and flex-basis raramente são empregas de forma individual. Usualmente, elas são combinadas através da propriedade de abreviação {{cssxref("flex")}}. A abreviatura flex permite definir os três valores na seguinte ordem: flex-grow, flex-shrink, flex-basis.

+ +

O exemplo prático abaixo permite que sejam testados diferentes valores com a propriedade de abreviação flex; lembre-se que o primeiro campo corresponde à propriedade flex-grow, onde um valor inteiro e positivo faz-se o elemento crescer. O segundo campo é a propriedade flex-shrink e, ao contrário do anterior, um valor inteiro e positivo pode fazer os elementos encolherem, mas  somente se o seu comprimento total ultrapassar o limite horizontal do contêiner, no sentido do eixo principal. O último campo contém a propriedade flex-basis, que define o valor base, em unidades de pixel, para aumentar e diminuir o elemento quando da aplicação das propriedades anteriores.

+ +

{{EmbedGHLiveSample("css-examples/flexbox/basics/flex-properties.html", '100%', 510)}}

+ +

Há ainda alguns valores de abreviação predefinidos, que cobrem a maioria dos casos de uso. São aplicados com frequência em turoriais e, normalmente, suprem todas as necessidades práticas. Os valores predefinidos podem ser vistos abaixo:

+ +
    +
  • flex: initial
  • +
  • flex: auto
  • +
  • flex: none
  • +
  • flex: <positive-number>
  • +
+ +

Definir flex: initial reseta os elementos para valores-padrão do Flexbox, sendo equivale a flex: 0 1 auto. Neste ultimo caso, o valor da propriedade flex-grow é 0, então os elementos não irão crescer mais do que o tamanho-base definido na propriedade flex-basis. o valor da propriedade flex-shrink é 1, indicando que o elemento pode ser reduzido caso seja necessário, para evitar que o limite do contêiner seja ultrapassado. Por fim, o valor da propriedade flex-basis é auto e assim será usad o tamanho mínimo necessário para preencher a dimensão do eixo principal.

+ +

Definir flex: auto é equivalente a flex: 1 1 auto. Essa configuração é semelhante a flex:initial, mas nesse caso os elementos podem aumentar para preencher o contêiner ou diminuir se necessário, para evitar o transbordamento lateral da tela.

+ +

Definir flex: none irá criar um elemento flex totalmente inflexível, sendo o equivalente a escrever flex: 0 0 auto. O elementos não poderão crescer ou diminuir, mas serão criados usando o flexbox com a propriedade flex-basis com o valor auto.

+ +

Outra abreviação normalmente vista em tutoriais é flex: 1 ou flex: 2 e assim por diante, o que equipara-se a flex: 1 1 0. Os elementos podem crescer ou diminuir a partir da propriedade flex-basis com valor nulo.

+ +

Teste essas formas abreviadas no exemplo prático abaixo:

+ +

{{EmbedGHLiveSample("css-examples/flexbox/basics/flex-shorthands.html", '100%', 510)}}

+ +

Alinhamento, justificação e distribuição de espaço livre   entre os elementos

+ +

Um atributo chave do flexbox é a capacidade de alinhar e justificar os elementos  flex nos eixos principal e transversal e distribuir o espaço entre eles.

+ +

Propriedade align-items

+ +

A propriedade {{cssxref("align-items")}} irá alinhar os elementos no eixo transversal.

+ +

O valor inicial desta propriedade é stretch e é por essa razão que, por padrão, os elementos flex se estendem até a maior altura. De fato, eles se esticam para preencher o contêiner flex - o item mais alto define a altura deste.

+ +

Pode-se definir a propriedade align-items como flex-start, de modo que os elementos fiquem alinhados com topo do contêiner, flex-end para alinhá-los a partir da base ou center, para que o alinhamento seja centralizado.

+ +

Teste essa propriedade e seus possíveis valores no exemplo prático abaixo — colocou-se uma determinada  altura no contêiner flex, de modo que se perceba como os elementos podem ser movidos no interior do mesmo. Veja o que acontece ao definir cada um dos possíveis valores da propriedade align-items:

+ +
    +
  • stretch
  • +
  • flex-start
  • +
  • flex-end
  • +
  • center
  • +
+ +

{{EmbedGHLiveSample("css-examples/flexbox/basics/align-items.html", '100%', 520)}}

+ +

Propriedade justify-content

+ +

A propriedade {{cssxref("justify-content")}} é empregada para alinhar os elementos ao longo do eixo principal, cuja direção (row ou column) é definida a partir da propriedade flex-direction. O valor inicial é flex-start, que alinha os elementos rente à borda esquerda do contêiner, mas também pode ser definido como flex-end, que resulta em um alinhamento oposto, rente à borda direita do contêiner, ou center, para alinhá-los ao centro.

+ +

O valor space-between pode ser usado pode ser usado para ocupar todo o espaço livre após a disposição dos itens e dividí-lo igualmente entre os itens, para que haja a mesma quantidade de espaço entre cada elemento. Para gerar uma quantidade igual de espaço à direita e à esquerda, usa-se o valor space-around.

+ +

Tente os seguintes valores da propriedada justify-content no exemplo prático abaixo:

+ +
    +
  • stretch
  • +
  • flex-start
  • +
  • flex-end
  • +
  • center
  • +
  • space-around
  • +
  • space-between
  • +
+ +

{{EmbedGHLiveSample("css-examples/flexbox/basics/justify-content.html", '100%', 380)}}

+ +

No artigo Alinhando Elementos em um Contêiner Flex (em inglês) tais propriedades serão abordadas mais detalhadamente, de modo a compreender melhor o seu funcionamento. Contudo, os exemplos simples abordados aqui serão úteis na maioria dos casos.

+ +

Próximos passos

+ +

Após ler este artigo, você deve ser capaz de compreender as características básicas do Flexbox. No próximo artigo, iremos examinar como essa especificação se relaciona com outras partes do CSS (em inglês). 

diff --git a/files/pt-br/web/css/css_flexible_box_layout/index.html b/files/pt-br/web/css/css_flexible_box_layout/index.html new file mode 100644 index 0000000000..7bf920f341 --- /dev/null +++ b/files/pt-br/web/css/css_flexible_box_layout/index.html @@ -0,0 +1,111 @@ +--- +title: CSS Flexible Box Layout +slug: Web/CSS/CSS_Flexible_Box_Layout +translation_of: Web/CSS/CSS_Flexible_Box_Layout +--- +

{{CSSRef}}

+ +

CSS Flexible is a module of CSS that defines a multi-column layout, allowing to express how content should flows between columns, and how gaps and rules are handled.

+ +

Reference

+ +

CSS Properties

+ +
+
    +
  • {{cssxref("align-content")}}
  • +
  • {{cssxref("align-items")}}
  • +
  • {{cssxref("align-self")}}
  • +
  • {{cssxref("flex")}}
  • +
  • {{cssxref("flex-basis")}}
  • +
  • {{cssxref("flex-direction")}}
  • +
  • {{cssxref("flex-flow")}}
  • +
  • {{cssxref("flex-grow")}}
  • +
  • {{cssxref("flex-shrink")}}
  • +
  • {{cssxref("flex-wrap")}}
  • +
  • {{cssxref("justify-content")}}
  • +
  • {{cssxref("order")}}
  • +
+
+ +

Guia

+ +
+
Usando CSS flexBox
+
tutorial passo-à-passo de como construir layouts com o FlexBox
+
Usando flexBox na organização de aplicações web
+
Tutorial ensinando como usar o flexBox no contexto de aplicações web
+
+ +

Especificação

+ + + + + + + + + + + + + + + + +
especificaçãoStatusComentario
{{ SpecName('CSS3 Flexbox') }}{{ Spec2('CSS3 Flexbox') }}Initial definition.
+ +

Compatibilidade Do Browser

+ +

{{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-br/web/css/css_flexible_box_layout/ordering_flex_items/index.html b/files/pt-br/web/css/css_flexible_box_layout/ordering_flex_items/index.html new file mode 100644 index 0000000000..953f5598d6 --- /dev/null +++ b/files/pt-br/web/css/css_flexible_box_layout/ordering_flex_items/index.html @@ -0,0 +1,131 @@ +--- +title: Ordering Flex Items +slug: Web/CSS/CSS_Flexible_Box_Layout/Ordering_Flex_Items +translation_of: Web/CSS/CSS_Flexible_Box_Layout/Ordering_Flex_Items +--- +

{{CSSRef}}

+ +

Os novos métodos de layout, como Flexbox e Grid, trazem a possibilidade de controlar a ordem do conteúdo. Neste artigo, veremos como você pode alterar a ordem visual do seu conteúdo ao usar o Flexbox. Também consideraremos as implicações de reordenar itens do ponto de vista da acessibilidade..

+ +

Reverse the display of the items

+ +

the {{cssxref("flex-direction")}} property can take one of four values:

+ +
    +
  • row
  • +
  • column
  • +
  • row-reverse
  • +
  • column-reverse
  • +
+ +

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 are 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:

+ +
+

“Note: 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.”

+
+ +
+

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

+ +

The order property

+ +

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:

+ +
    +
  • Source item 1: order: 2
  • +
  • Source item 2: order: 3
  • +
  • Source item 3: order: 1
  • +
  • Source item 4: order: 3
  • +
  • Source item 5: order: 1
  • +
+ +

These items would be displayed on the page in the following order:

+ +
    +
  • Source item 3: order: 1
  • +
  • Source item 5: order: 1
  • +
  • Source item 1: order: 2
  • +
  • Source item 2: order: 3
  • +
  • Source item 4: order: 3
  • +
+ +

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.

+ +

The order property and accessibility

+ +

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.

+ + + +

Use cases for 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-br/web/css/css_flexible_box_layout/typical_use_cases_of_flexbox/index.html b/files/pt-br/web/css/css_flexible_box_layout/typical_use_cases_of_flexbox/index.html new file mode 100644 index 0000000000..ec50aab3fe --- /dev/null +++ b/files/pt-br/web/css/css_flexible_box_layout/typical_use_cases_of_flexbox/index.html @@ -0,0 +1,135 @@ +--- +title: Casos típicos de uso do Flexbox +slug: Web/CSS/CSS_Flexible_Box_Layout/Typical_Use_Cases_of_Flexbox +translation_of: Web/CSS/CSS_Flexible_Box_Layout/Typical_Use_Cases_of_Flexbox +--- +

{{CSSRef}}

+ +

In this guide we will take a look at some of the common use cases for flexbox — those places where it makes more sense than another layout method.

+ +

Por que 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.

+ +

Space distributed outside the items

+ +

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

+ +

Space distributed within the items

+ +

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

+ +

Split navigation

+ +

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

+ +

Center 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 0 — the item can grow and shrink from a flex basis of 0. 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)}}

+ +

Media objects

+ +

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 0 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)}}

+ +

Form controls

+ +

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

+ +

Conclusion

+ +

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-br/web/css/css_grid_layout/basic_concepts_of_grid_layout/index.html b/files/pt-br/web/css/css_grid_layout/basic_concepts_of_grid_layout/index.html new file mode 100644 index 0000000000..1078b0dbae --- /dev/null +++ b/files/pt-br/web/css/css_grid_layout/basic_concepts_of_grid_layout/index.html @@ -0,0 +1,728 @@ +--- +title: Conceitos básicos de Grid Layout +slug: Web/CSS/CSS_Grid_Layout/Basic_Concepts_of_Grid_Layout +tags: + - CSS + - CSS Grids + - Guias(2) + - Layout +translation_of: Web/CSS/CSS_Grid_Layout/Basic_Concepts_of_Grid_Layout +--- +

CSS Grid Layout introduz um sistema bi-dimensional de grid (literalmente "grades") para CSS. Grids podem ser usados para o design de layouts de grandes seções de uma webpage, assim como de pequenos elementos de interface. Esse artigo apresenta o CSS Grid Layout e a terminologia que é parte da especificação  CSS Grid Layout Level 1. As funcionalidades demonstradas neste resumo serão posteriormente explicadas em maiores detalhes nas demais seções desse guia.

+ +

O que é grid?

+ +

Grid é uma malha formada pela interseção de um conjunto de linhas horizontais e um conjunto de linhas verticais – um dos conjuntos define colunas e outro linhas. Dentro de um  grid, respeitando-se a configuração criada pelas suas linhas, pode-se inserir elementos da marcação. As CSS grid layout preveem as seguintes funcionalidades:

+ +

Dimensões fixas ou flexíveis

+ +

Você pode criar grids com dimensões fixas – por exemplo: definindo dimensões em pixels. Ou criar grids com dimensões flexíveis definindo-as com uso de porcentagem ou da nova unidade CSS fr criada para esse propósito.

+ +

Posicionamento de itens

+ +

Você pode posicionar com precisão itens de uma página usando o número que define uma linha do grid, usando nomes ou ainda fazendo referência a uma determinada região do grid. Existe ainda um algorítmo de controle do posicionamento de itens da página que não possuem uma posição capaz de ser explícitamente definida no grid.

+ +

Criação de grids adicionais

+ +

Além da possibilidade de se criar um grid inicial para o layout a Especificação prevê também a possibilidade de se adicionar linhas e colunas para layoutar conteúdos adicionados fora do grid inicial. Funcionalidades tal como adicionar "tantas colunas quanto necessárias em um grid container existente" são previstas nas Especificações.

+ +

Alinhamento

+ +

Estão previstas funcionalidades de alinhamento que possibilitam controlar o alinhamento dos itens de uma página posicionados no grid e também o alinhamento do próprio grid como um todo.

+ +

Controle sobre conteúdos sobrepostos

+ +

Em uma célula do grid podem ser posicionados mais de um item da página e também é possível que se defina sobreposição parcial de áreas. Esse controle de layers é feito com uso de {{cssxref("z-index")}}.

+ +

CSS Grid Layout é uma poderosa especificação que se for combinada com outras partes do CSS, tal como flexbox, possibilita a criação de layouts que até então eram impossíveis de serem criados com CSS. Tudo começa com a criação de um grid dentro de um grid container.

+ +

Grid container

+ +

Cria-se um grid container com as declarações CSS display: grid ou display: inline-grid para um elemento da marcação. Assim declarando, todos os elementos filhos diretos daquele container se transformam em grid items.

+ +

No exemplo mostrado a seguir um elemento div container ao qual foi atribuída a classe wrapper contém cinco elementos filhos.

+ +
<div class="wrapper">
+   <div>One</div>
+   <div>Two</div>
+   <div>Three</div>
+   <div>Four</div>
+   <div>Five</div>
+</div>
+
+ +

Façamos de .wrapper um grid container.

+ +
.wrapper {
+  display: grid;
+}
+
+ + + +

{{ EmbedLiveSample('The_Grid_container', '200', '330') }}

+ +

Todos os elementos filhos diretos agora são grid items. Observando a renderização em um navegador web você não notará nenhuma diferença em relação a renderização já conhecida de um elemento container com seus cinco elementos filhos, pois no exemplo foi criado um grid constítuido de uma única coluna para acomodar os elementos filhos. A partir desse ponto você pode achar mais útil trabalhar no Firefox Developer Edition, que possui o Grid Inspector disponÍvel como parte das Ferramentas do desenvolvedor. Se você ver este exemplo no Firefox e inspecionar o Grid, você verá um pequeno ícone ao lado do valor Grid (na propiedade display do elemento container). Clique nele e o Grid neste elemento será sobreposto na janela do navegador. 

+ +

Using the Grid Highlighter in DevTools to view a grid

+ +

À medida que você aprende e depois trabalha com CSS Grid Layout, esta ferramenta lhe dará uma idéia melhor do que está acontecendo com suas Grids visualmente.

+ +

Se nós queremos começar a fazer isso parecer mais com os Grids layouts , nós precisamos adicionar collumn tracks.

+ +

Grid Tracks

+ +

Nós definimos linhas e colunas no nosso grid com as propriedades {{cssxref("grid-template-columns")}} e {{cssxref("grid-template-rows")}}. Isso define o grid tracks. Um grid track é o espaço entre duas linhas em um grid. Na imagem abaixo você pode ver um track highlighter – o track na primeira linha do nosso grid.

+ +

+ +

Posso adicionar ao exemplo anterior a propriedade grid-template-columns, depois definir o tamanho da column tracks.

+ +

Agora criei um grid com três colunas fixas de 200px. Os itens filhos serão dispostos nessa grade, um em cada célula da grade.

+ +
+
<div class="wrapper">
+   <div>One</div>
+   <div>Two</div>
+   <div>Three</div>
+   <div>Four</div>
+   <div>Five</div>
+</div>
+
+ +
.wrapper {
+  display: grid;
+  grid-template-columns: 200px 200px 200px;
+}
+
+ + + +

{{ EmbedLiveSample('grid_first', '610', '140') }}

+
+ +

A unidade fr

+ +

Nas propriedades de grid podem ser utilizadas quaisquer unidades de medida. Para nos ajudar a criar layouts flexíveis utilizando o grid, foi criada uma unidade nova. A unidade fr representa uma fração do espaço disponível no container do grid. A próxima definição de grid cria três espaços com tamanhos iguais que aumentam e diminuem de acordo com o espaço disponível. 

+ +
+
<div class="wrapper">
+   <div>One</div>
+   <div>Two</div>
+   <div>Three</div>
+   <div>Four</div>
+   <div>Five</div>
+</div>
+
+ +
.wrapper {
+  display: grid;
+  grid-template-columns: 1fr 1fr 1fr;
+}
+
+ + + +

{{ EmbedLiveSample('fr_unit_ls', '220', '180') }}

+
+ +

No próximo exemplo, criamos um container .wrapper com uma coluna de 2fr e duas colunas de 1fr. Portanto, o espaço disponível será dividido em quatro partes. Duas partes serão para a primeira coluna e uma parte para cada um das próximas duas colunas. 

+ +
.wrapper {
+  display: grid;
+  grid-template-columns: 2fr 1fr 1fr;
+}
+
+ +

Nesse exemplo final, nós misturamos unidades de medida fixa com as de fração. A primeira coluna tem 500px, que será fixa. O espaço disponível restante será dividido em três partes, sendo uma parte para a segunda coluna e mais duas partes para a terceira coluna.

+ +
.wrapper {
+  display: grid;
+  grid-template-columns: 500px 1fr 2fr;
+}
+
+ +

Track listings com a notação repeat()

+ +

Grids grandes, com muitas tracks podem usar a notação repeat() para repetir todas ou uma seção de track listing. Por exemplo a definição de grid a seguir:

+ +
.wrapper {
+  display: grid;
+  grid-template-columns: 1fr 1fr 1fr;
+}
+
+ +

Também pode ser escrita como:

+ +
.wrapper {
+  display: grid;
+  grid-template-columns: repeat(3, 1fr);
+}
+
+ +

A notação repeat ( ) pode ser usada apenas para uma parte da track listing. No próximo exemplo estou criando um grid com uma coluna inicial de 20-pixels, repetindo uma sessão de 6 colunas de 1fr, e por fim uma coluna de 20-pixels.

+ +
.wrapper {
+  display: grid;
+  grid-template-columns: 20px repeat(6, 1fr) 20px;
+}
+
+ +

A notação Repeat tem como parâmetro um track listing, sendo assim você pode usá-lo para criar um padrão de repetição de tracks. Neste exemplo meu grid terá 10 tracks, uma trilha de 1fr seguida por uma trilha de 2fr , repetida cinco vezes.

+ +
.wrapper {
+  display: grid;
+  grid-template-columns: repeat(5, 1fr 2fr);
+}
+
+ +

O grid implícito e explícito

+ +

Ao criar nosso grid de exempo definimos nossa coluna de trilhas com a propriedade {{cssxref("grid-template-columns")}}, mas adicionalmente deixamos o grid criar as linhas necessárias para qualquer outro conteúdo. Estas linhas são criadas no grid implícito. O grid explícito é constituído por linhas e colunas que você define com {{cssxref("grid-template-columns")}} e {{cssxref("grid-template-rows")}}. Se você posicionar algo fora do grid definido, ou caso devido à quantidado de conteúdo mais trilhas de grid sejam necessárias, o grid então cria linhas e colunas no grid implícito. Estas trilhas serão seu tamanho definido automaticamente por padrão, resultando em seu tamanho ser basedo no conteúdo que elas contém.

+ +

Você também pode definir o tamanho do conjunto para trilhas criadas na grid implícita com as propriedades  {{cssxref("grid-auto-rows")}} e {{cssxref("grid-auto-columns")}}.

+ +

No exemplo abaixo usamos grid-auto-rows para garantir que as trilhas criadas na grid implícita tem 200 pixels de altura.

+ +
<div class="wrapper">
+   <div>One</div>
+   <div>Two</div>
+   <div>Three</div>
+   <div>Four</div>
+   <div>Five</div>
+</div>
+
+ +
.wrapper {
+  display: grid;
+  grid-template-columns: repeat(3, 1fr);
+  grid-auto-rows: 200px;
+}
+
+ + + +

{{ EmbedLiveSample('The_implicit_and_explicit_grid', '210', '410') }}

+ +

Track sizing and minmax()

+ +

Quando criando um grid explícito ou definindo o tamanho para as colunas e linha serem criadas automáticamente podemos querer dar um tamanho minimo para os tracks, mas assegure que eles expandam para o tamanho necessário do conteúdo adicionado. Por exemplo eu gostaria que as minhas linhas nunca colapsem para um tamanho menor que 100 pixels, mas se o meu conteúdo aumentar até 300 pixels de altura eu gostaria que a linha aumentasse para essa mesma altura.

+ +

Grid tem uma solução para isso com a função {{cssxref("minmax", "minmax()")}}. No próximo exemplo estou usando minmax() no valor de {{cssxref("grid-auto-rows")}}. Automaticamente as linhas criadas terão uma altura mínima de 100 pixels, e a máxima de auto. Usar auto significa que o tamanho vai olhar para o conteúdo e, assim, esticar para que a linha tenha o espaço necessário.

+ +
.wrapper {
+  display: grid;
+  grid-template-columns: repeat(3, 1fr);
+  grid-auto-rows: minmax(100px, auto);
+}
+
+ + + +
<div class="wrapper">
+   <div>One</div>
+   <div>Two
+   <p>I have some more content in.</p>
+
+<p>This makes me taller than 100 pixels.</p>
+</div>
+   <div>Three</div>
+   <div>Four</div>
+   <div>Five</div>
+</div>
+
+ +

{{ EmbedLiveSample('Track_sizing_and_minmax()', '230', '490') }}

+ +

Linhas de grid

+ +

Devemos observar que quando definimos um grid definimos as trilhas do grid, não as linhas. O grid então nos devolve linhas numeradas para usarmos ao posicionar itens. Em nossa grid de 3 colunas por duas linhas, temos quatro linhas de colunas.

+ +

Diagram showing numbered grid lines.

+ +

Linhas são numeradas de acordo a forma de escrita do documento. Em uma linguagem da esquerda para a direita, a linha 1 está à esquerda do grid. Em uma linguagem da direita para a esquerda, ela está no lado direito do grid. Linhas também podem ser nomeadas, e veremos como fazer isso em um guia posterior nessa série.

+ +

Posicionando itens contra linhas

+ +

Exploraremos posicionamento de itens baseado em linhas em um artigo posterior. O exemplo a seguir mostra como fazer isso de forma simples. Quando posicionar um item, focamos a linha - ao invés do rastro.

+ +

Nesse exemplo eu estou posicionando os primeiros dois itens do nosso grid de três colunas, usando as propriedades {{cssxref("grid-column-start")}}, {{cssxref("grid-column-end")}}, {{cssxref("grid-row-start")}} e {{cssxref("grid-row-end")}}. Da esquerda para a direita, o primeiro item é posicionado contra a linha da coluna 1, e vai até a linha da coluna 4, que no nosso caso é a linha do extremo direito do grid. Começa na linha 1 e termina na linha 3, tendo uma expansão de duas linhas.

+ +

O segundo item inicia na linha da coluna 1, e expande uma linha. Esse é o padrão, então não preciso especificar a linha final. Também vai da linha 3 a linha 5. Os outros itens serão posicionados de acordo com espaço disponível no grid.

+ +
<div class="wrapper">
+   <div class="box1">One</div>
+   <div class="box2">Two</div>
+   <div class="box3">Three</div>
+   <div class="box4">Four</div>
+   <div class="box5">Five</div>
+</div>
+
+ +
.wrapper {
+    display: grid;
+    grid-template-columns: repeat(3, 1fr);
+    grid-auto-rows: 100px;
+}
+.box1 {
+    grid-column-start: 1;
+    grid-column-end: 4;
+    grid-row-start: 1;
+    grid-row-end: 3;
+}
+.box2 {
+    grid-column-start: 1;
+    grid-row-start: 3;
+    grid-row-end: 5;
+}
+
+ + + +

{{ EmbedLiveSample('Positioning_items_against_lines', '220', '410') }}

+ +

Não esqueça que o Grid Inspector pode ser usado no Firefox Developer Tools para ver como os itens estão posicionados no grid.

+ +

Células do grid

+ +

Uma célula de grid é a menor unidade em um grid. Conceitualmente é como se fosse uma célula de tabela. Como vimos em nossos exemplos anteriores, uma vez que o grid é definido como o pai os itens filhos serão organizados cada um em uma célula do grid definido. Na imagem abaixo, temos destacado a primeira célula do grid.

+ +

The first cell of the grid highlighted

+ +

Áreas do grid

+ +

Itens podem se espalhar por uma ou mais células ambas entre linhas ou colunas, e isto cria uma área de grid. Áreas de grid devem ser retangulares – não é possível criar uma área em L por exemplo. A área destacada se espalha por duas trilhas de linhas e duas trilhas de colunas.

+ +

A grid area

+ +

Gutters

+ +

Gutters ou alleys (espaçamentos ou separadores) entre células do grid podem ser criadas usando a propriedade {{cssxref("grid-column-gap")}} e {{cssxref("grid-row-gap")}} ou de forma resumida {{cssxref("grid-gap")}}. No exemplo abaixo, criamos um espaço vazio de 10 pixels entre colunas e um espaço vazio de 1em entre linhas.

+ +
.wrapper {
+   display: grid;
+   grid-template-columns: repeat(3, 1fr);
+   grid-column-gap: 10px;
+   grid-row-gap: 1em;
+}
+
+ +
<div class="wrapper">
+   <div>One</div>
+   <div>Two</div>
+   <div>Three</div>
+   <div>Four</div>
+   <div>Five</div>
+</div>
+
+ + + +

{{ EmbedLiveSample('Gutters') }}

+ +

Qualquer espaço utilizado entre espaços vazios ou gaps deverá ser considerado antes do espaço ser designado para as trilhas de tamanho flexível fr , e gaps agem para propósitos de tamanho como uma trilha de grid normal, entretanto você não pode colocar coisa alguma em um gap Em termos de posicionamento baseado em linhas, o gap age como uma linha preenchida (fat line).

+ +

Aninhando grids

+ +

Um item de grid pode se tornar um container de grid. No exemplo a seguir, temos o grid de três colunas criadas anteriormente, com nossos dois itens posicionados. Neste caso o primeiro item possui dois sub itens. Como estes itens não são filhos diretos do grid eles não participam no layout do grid e dessa forma são exibidos no fluxo normal do documento.

+ +
+
<div class="wrapper">
+   <div class="box box1">
+       <div class="nested">a</div>
+       <div class="nested">b</div>
+        <div class="nested">c</div>
+    </div>
+    <div class="box box2">Two</div>
+    <div class="box box3">Three</div>
+    <div class="box box4">Four</div>
+    <div class="box box5">Five</div>
+</div>
+
+ +

Nested grid in flow

+ +

Se definimos box1 como display: grid  podemos dar uma definição de tracks e ela também se tornará uma grid. Os itens então são dispostos nesse novo grid.

+ +
.box1 {
+   grid-column-start: 1;
+   grid-column-end: 4;
+   grid-row-start: 1;
+   grid-row-end: 3;
+   display: grid;
+   grid-template-columns: repeat(3, 1fr);
+}
+
+ + +
+ +

{{ EmbedLiveSample('nesting', '600', '410') }}

+ +

Nesse caso o grid aninhado não possui relação com o pai. Como é possível perceber no exemplo ele não herdou o {{cssxref("grid-gap")}} do pai e as linhas no grid aninhado não estão alinhadas com as linhas do grid pai.

+ +

Subgrid

+ +

No nível das especificações do grid tem uma feature chamada subgrid que nos permitiria criar grids aninhados que usa aquilo que foi definido no grid pai.

+ +
+

Subgrids ainda não foram implementados em nenhum browser, e as especificações são sujeitas a mudanças.

+
+ +

Na especificação atual, no exemplo acima editaríamos o grid aninhado usando display: subgrid ao invés de display: grid, e remover o que havia sido definido. O grid aninhado vai usar as propriedades definidas no pai para dispor os itens.

+ +

Note que o grid aninhado está nas duas dimensões — linhas e colunas. Não há garantia de que o grid implícito funcione com subgrid. Por isso é necessário que haja certeza de que o grid pai tem linhas e colunas suficientes para todos os sub itens.

+ +
.box1 {
+   grid-column-start: 1;
+   grid-column-end: 4;
+   grid-row-start: 1;
+   grid-row-end: 3;
+   display: subgrid;
+}
+
+ +

Sobrepondo itens com z-index

+ +

Itens de uma mesma grade podem ocupar uma mesma célula. Se retornarmos ao nosso exemplo com itens dispostos pela linha, podemos fazer com que dois se sobreponham.

+ +
+
<div class="wrapper">
+   <div class="box box1">One</div>
+   <div class="box box2">Two</div>
+   <div class="box box3">Three</div>
+   <div class="box box4">Four</div>
+   <div class="box box5">Five</div>
+</div>
+
+ +
.wrapper {
+   display: grid;
+   grid-template-columns: repeat(3, 1fr);
+   grid-auto-rows: 100px;
+}
+.box1 {
+   grid-column-start: 1;
+   grid-column-end: 4;
+   grid-row-start: 1;
+   grid-row-end: 3;
+}
+.box2 {
+   grid-column-start: 1;
+   grid-row-start: 2;
+   grid-row-end: 4;
+}
+
+ + +
+ +

{{ EmbedLiveSample('l_ex', '210', '410') }}

+ +

O container box2 está sobrepondo box1, é renderizado acima pois vem depois na ordem.

+ +

Manipulando a ordem

+ +

Podemos controlar a ordem na qual os itens irão empilhar-se usando a propriedade z-index. Se box2 recebe um z-index menor que box1 será mostrado abaixo de box1.

+ +
.wrapper {
+   display: grid;
+   grid-template-columns: repeat(3, 1fr);
+   grid-auto-rows: 100px;
+}
+.box1 {
+   grid-column-start: 1;
+   grid-column-end: 4;
+   grid-row-start: 1;
+   grid-row-end: 3;
+   z-index: 2;
+}
+.box2 {
+   grid-column-start: 1;
+   grid-row-start: 2;
+   grid-row-end: 4;
+   z-index: 1;
+}
+
+ + + +

{{ EmbedLiveSample('Controlling_the_order', '210', '410') }}

+ +

Próximos Passos

+ +

Nesse artigo abordamos um pouco da especificação do Grid Layout. Pratique com os exemplos propostos, depois disso passe para a próxima parte onde estudaremos mais a fundo o CSS Grid Layout.

+ + diff --git a/files/pt-br/web/css/css_grid_layout/index.html b/files/pt-br/web/css/css_grid_layout/index.html new file mode 100644 index 0000000000..28ebe9c2d6 --- /dev/null +++ b/files/pt-br/web/css/css_grid_layout/index.html @@ -0,0 +1,191 @@ +--- +title: CSS Grid Layout +slug: Web/CSS/CSS_Grid_Layout +tags: + - CSS + - Grid Layout + - Grids + - Layout + - Referências +translation_of: Web/CSS/CSS_Grid_Layout +--- +
+

CSS Grid será suportado por vários navegadores até meados de 2017. O suporte em navegadores antigos pode ser obtido habilitando-se uma flag que permite o uso da API. Nesse caso não se esqueça de consultar e fazer referência a cada propriedade e funcionalidade da especificação para certificar-se da sua compatibilidade, bem como para obter maiores informações.

+
+ +

CSS Grid layout é uma especificação do W3C projetada para proporcionar um método bi-dimensional para criação de layout CSS que oferece a possibilidade de "layoutar" itens da página com uso de linhas e colunas. CSS grid poderá ser usado para obter uma infinidade de diferentes layouts. O diferencial desse método de criação de layouts reside na possibilidade de se dividir uma página em grandes regiões e de se definir o relacionamento em termos de medidas, posicionamento e camadas entre os diferentes componentes da marcação HTML.

+ +

Tal como as tabelas, grid layout permite ao autor alinhar os componentes da página fazendo uso de linhas e colunas. Contudo ao contrário das tabelas, grid layout não se baseia em estruturação de conteúdos, possibilitando uma enorme variedade de layouts, o que não é possível de se obter com uso de tabelas. Por exemplo:  elementos filhos de um grid container podem ser posicionados à vontade se sobrepondo ou mudando de layer, de modo idêntico como se faz com uso das funcionalidades do nosso já conhecido posicionamento CSS.

+ +

Exemplo básico

+ +

HTML

+ +
<div class="wrapper">
+  <div class="box a">a</div>
+  <div class="box b">b</div>
+  <div class="box c">c</div>
+  <div class="box d">d</div>
+  <div class="box e">e</div>
+  <div class="box f">f</div>
+</div>
+ +

CSS

+ +
.wrapper {
+  display: grid;
+  grid-template-columns: 100px 100px 100px;
+  grid-gap: 10px;
+  background-color: #fff;
+  color: #444;
+}
+
+.box {
+  background-color: #444;
+  color: #fff;
+  border-radius: 5px;
+  padding: 20px;
+  font-size: 150%;
+}
+ +

Referência

+ +

Propriedades CSS

+ +
+
    +
  • {{cssxref("grid-template-columns")}}
  • +
  • {{cssxref("grid-template-rows")}}
  • +
  • {{cssxref("grid-template-areas")}}
  • +
  • {{cssxref("grid-template")}}
  • +
  • {{cssxref("grid-auto-columns")}}
  • +
  • {{cssxref("grid-auto-rows")}}
  • +
  • {{cssxref("grid-auto-flow")}}
  • +
  • {{cssxref("grid")}}
  • +
  • {{cssxref("grid-row-start")}}
  • +
  • {{cssxref("grid-column-start")}}
  • +
  • {{cssxref("grid-row-end")}}
  • +
  • {{cssxref("grid-column-end")}}
  • +
  • {{cssxref("grid-row")}}
  • +
  • {{cssxref("grid-column")}}
  • +
  • {{cssxref("grid-area")}}
  • +
  • {{cssxref("grid-row-gap")}}
  • +
  • {{cssxref("grid-column-gap")}}
  • +
  • {{cssxref("grid-gap")}}
  • +
+
+ +

Funções CSS

+ +
+
    +
  • {{cssxref("repeat", "repeat()")}}
  • +
  • {{cssxref("minmax", "minmax()")}}
  • +
+
+ +

Glossário

+ + + +

Guias

+ + + +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentários
{{ SpecName('CSS3 Grid') }}{{ Spec2('CSS3 Grid') }}Definição inicial.
+ + diff --git a/files/pt-br/web/css/css_grid_layout/relationship_of_grid_layout/index.html b/files/pt-br/web/css/css_grid_layout/relationship_of_grid_layout/index.html new file mode 100644 index 0000000000..358ada6d07 --- /dev/null +++ b/files/pt-br/web/css/css_grid_layout/relationship_of_grid_layout/index.html @@ -0,0 +1,640 @@ +--- +title: Relationship of grid layout to other layout methods +slug: Web/CSS/CSS_Grid_Layout/Relationship_of_Grid_Layout +translation_of: Web/CSS/CSS_Grid_Layout/Relationship_of_Grid_Layout +--- +

 

+ +

O CSS Grid Layout foi projetado para funcionar junto com outras partes do CSS, como parte de um sistema completo para fazer o layout. Neste guia, explicarei como uma grade se encaixa com outras técnicas que você já pode estar usando.

+ +

Grid e flexbox

+ +

A diferença básica entre CSS Grid Layout e CSS Flexbox Layout é que o flexbox foi projetado para layout em uma dimensão - uma linha ou uma coluna. A grade foi projetada para layout bidimensional - linhas e colunas ao mesmo tempo. As duas especificações compartilham alguns recursos comuns, e se você já aprendeu a usar o flexbox, as semelhanças devem ajudá-lo a se familiarizar com o Grid.

+ +

Layout unidimensional versus bidimensional

+ +

Um exemplo simples pode demonstrar a diferença entre layouts unidimensionais e bidimensionais.

+ +

Neste primeiro exemplo, estou usando o flexbox para criar um conjunto de caixas. Eu tenho cinco itens filhos no meu contêiner e dei valores de propriedades flexíveis para que eles possam crescer e encolher de uma base flexível de 200 pixels.

+ +

Eu também defini a propriedade {{cssxref ("flex-wrap")}} para agrupar, de modo que, se o espaço no contêiner ficar muito estreito para manter a base flexível, os itens serão agrupados em uma nova linha.

+ +

 

+ +
+ + +
<div class="wrapper">
+  <div>One</div>
+  <div>Two</div>
+  <div>Three</div>
+  <div>Four</div>
+  <div>Five</div>
+</div>
+
+ +
.wrapper {
+  display: flex;
+  flex-wrap: wrap;
+}
+.wrapper > div {
+  flex: 1 1 200px;
+}
+
+
+ +

{{ EmbedLiveSample('onedtwod', '500', '230') }}

+ +

 

+ +

Na imagem, você pode ver que dois itens foram envolvidos em uma nova linha. Esses itens estão compartilhando o espaço disponível e não se alinhando abaixo dos itens acima. Isso ocorre porque quando você envolve itens flexíveis, cada nova linha (ou coluna ao trabalhar por coluna) se torna um novo contêiner flexível. Distribuição de espaço acontece em toda a linha.

+ +

Uma questão comum, então, é como alinhar esses itens. É aqui que você deseja um método de layout bidimensional: Você quer controlar o alinhamento por linha e coluna, e é aí que a grade entra.

+ +

 

+ +

The same layout with CSS grids

+ +

Neste próximo exemplo, eu crio o mesmo layout usando Grid. Desta vez, temos três faixas de coluna 1fr. Não precisamos definir nada nos itens em si; eles se estabelecerão em cada célula da grade criada. Como você pode ver, eles ficam em uma grade rígida, alinhando-se em linhas e colunas. Com cinco itens, temos uma lacuna no final da segunda linha.

+ +

 

+ +

 

+ +
+ + +
<div class="wrapper">
+  <div>One</div>
+  <div>Two</div>
+  <div>Three</div>
+  <div>Four</div>
+  <div>Five</div>
+</div>
+
+ +
.wrapper {
+  display: grid;
+  grid-template-columns: repeat(3, 1fr);
+}
+
+ +

{{ EmbedLiveSample('Two_Dimensional_With_Grid', '300', '170') }}

+
+ +

A simple question to ask yourself when deciding between grid or flexbox is:

+ +
    +
  • do I only need to control the layout by row or column – use a flexbox
  • +
  • do I need to control the layout by row and column – use a grid
  • +
+ +

Content out or layout in?

+ +

In addition to the one-dimensional versus two-dimensional distinction, there is another way to decide if you should use flexbox or grid for a layout. Flexbox works from the content out. An ideal use case for flexbox is when you have a set of items and want to space them out evenly in a container. You let the size of the content decide how much individual space each item takes up. If the items wrap onto a new line, they will work out their spacing based on their size and the available space on that line.

+ +

Grid works from the layout in. When you use CSS Grid Layout you create a layout and then you place items into it, or you allow the auto-placement rules to place the items into the grid cells according to that strict grid. It is possible to create tracks that respond to the size of the content, however, they will also change the entire track.

+ +

If you are using flexbox and find yourself disabling some of the flexibility, you probably need to use CSS Grid Layout. An example would be if you are setting a percentage width on a flex item to make it line up with other items in a row above. In that case, a grid is likely to be a better choice.

+ +

Box alignment

+ +

The feature of flexbox that was most exciting to many of us was that it gave us proper alignment control for the first time. It made it easy to center a box on the page. Flex items can stretch to the height of the flex container, meaning that equal height columns were possible. These were things we have wanted to do for a very long time, and have come up with all kinds of hacks to at least create the visual effect of.

+ +

The alignment properties from the flexbox specification have been added to a new specification called Box Alignment Level 3. This means that they can be used in other specifications, including Grid Layout. In the future, they may well apply to other layout methods as well.

+ +

In a later guide in this series, I’ll be taking a proper look at Box Alignment and how it works in Grid Layout. For now, here is a comparison between simple examples of flexbox and grid.

+ +

In the first example, which uses flexbox, I have a container with three items inside. The wrapper {{cssxref("min-height")}} is set, so it defines the height of the flex container. I have set {{cssxref("align-items")}} on the flex container to flex-end so the items will line up at the end of the flex container. I have also set the {{cssxref("align-self")}} property on box1 so it will override the default and stretch to the height of the container and on box2 so it aligns to the start of the flex container.

+ + + +
<div class="wrapper">
+  <div class="box1">One</div>
+  <div class="box2">Two</div>
+  <div class="box3">Three</div>
+</div>
+
+ +
.wrapper {
+  display: flex;
+  align-items: flex-end;
+  min-height: 200px;
+}
+.box1 {
+  align-self: stretch;
+}
+.box2 {
+  align-self: flex-start;
+}
+
+ +

{{ EmbedLiveSample('Box_alignment', '300', '230') }}

+ +

Alignment in CSS Grids

+ +

This second example uses a grid to create the same layout. This time we are using the box alignment properties as they apply to a grid layout. So we align to start and end rather than flex-start and flex-end. In the case of a grid layout, we are aligning the items inside their grid area. In this case that is a single grid cell, but it could be an area made up of several grid cells.

+ + + +
<div class="wrapper">
+  <div class="box1">One</div>
+  <div class="box2">Two</div>
+  <div class="box3">Three</div>
+</div>
+
+ +
.wrapper {
+  display: grid;
+  grid-template-columns: repeat(3,1fr);
+  align-items: end;
+  grid-auto-rows: 200px;
+}
+.box1 {
+  align-self: stretch;
+}
+.box2 {
+  align-self: start;
+}
+
+ +

{{ EmbedLiveSample('Alignment_in_CSS_Grids', '200', '310') }}

+ +

The fr unit and flex-basis

+ +

We have already seen how the fr unit works to assign a proportion of available space in the grid container to our grid tracks. The fr unit, when combined with the {{cssxref("minmax", "minmax()")}} function can give us very similar behavior to the flex properties in flexbox while still enabling the creation of a layout in two dimensions.

+ +

If we look back at the example where I demonstrated the difference between one and two-dimensional layouts, you can see there is a difference between the way of the two layouts work responsively. With the flex layout, if we drag our window wider and smaller, the flexbox does a nice job of adjusting the number of items in each row according to the available space. If we have a lot of space all five items can fit on one row. If we have a very narrow container we may only have space for one.

+ +

In comparison, the grid version always has three column tracks. The tracks themselves will grow and shrink, but there are always three since we asked for three when defining our grid.

+ +

Auto-filling grid tracks

+ +

We can create a similar effect to flexbox, while still keeping the content arranged in strict rows and columns, by creating our track listing using repeat notation and the auto-fill and auto-fit properties.

+ +

In this next example, I have used the auto-fill keyword in place of an integer in the repeat notation and set the track listing to 200 pixels. This means that grid will create as many 200 pixels column tracks as will fit in the container.

+ + + +
<div class="wrapper">
+  <div>One</div>
+  <div>Two</div>
+  <div>Three</div>
+</div>
+
+ +
.wrapper {
+  display: grid;
+  grid-template-columns: repeat(auto-fill, 200px);
+}
+
+ +

{{ EmbedLiveSample('Auto-filling_grid_tracks', '500', '170') }}

+ +

A flexible number of tracks

+ +

This isn’t quite the same as flexbox. In the flexbox example, the items are larger than the 200 pixel basis before wrapping. We can achieve the same in grid by combining auto-fill and the {{cssxref("minmax", "minmax()")}} function. In this next example, I create auto filled tracks with minmax. I want my tracks to be a minimum of 200 pixels, so I set the maximum to be 1fr. Once the browser has worked out how many times 200 pixels will fit into the container–also taking account of grid gaps–it will treat the 1fr maximum as an instruction to share out the remaining space between the items.

+ + + +
<div class="wrapper">
+  <div>One</div>
+  <div>Two</div>
+  <div>Three</div>
+</div>
+
+ +
.wrapper {
+  display: grid;
+  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
+}
+
+ +

{{ EmbedLiveSample('A_flexible_number_of_tracks', '500', '170') }}

+ +

We now have the ability to create a grid with a flexible number of flexible tracks, but see items laid out on the grid aligned by rows and columns at the same time.

+ +

Grid and absolutely positioned elements

+ +

Grid interacts with absolutely positioned elements, which can be useful if you want to position an item inside a grid or grid area. The specification defines the behavior when a grid container is a containing block and a parent of the absolutely positioned item.

+ +

A grid container as containing block

+ +

To make the grid container a containing block you need to add the position property to the container with a value of relative, just as you would make a containing block for any other absolutely positioned items. Once you have done this, if you give a grid item position: absolute it will take as its containing block the grid container or, if the item also has a grid position, the area of the grid it is placed into.

+ +

In the below example I have a wrapper containing four child items. Item three is absolutely positioned and also placed on the grid using line-based placement. The grid container has position: relative and so becomes the positioning context of this item.

+ + + +
<div class="wrapper">
+  <div class="box1">One</div>
+  <div class="box2">Two</div>
+  <div class="box3">
+   This block is absolutely positioned. In this example the grid container is the containing block and so the absolute positioning offset values are calculated in from the outer edges of the area it has been placed into.
+  </div>
+  <div class="box4">Four</div>
+</div>
+
+ +
.wrapper {
+  display: grid;
+  grid-template-columns: repeat(4,1fr);
+  grid-auto-rows: 200px;
+  grid-gap: 20px;
+  position: relative;
+}
+.box3 {
+  grid-column-start: 2;
+  grid-column-end: 4;
+  grid-row-start: 1;
+  grid-row-end: 3;
+  position: absolute;
+  top: 40px;
+  left: 40px;
+}
+
+ +

{{ EmbedLiveSample('A_grid_container_as_containing_block', '500', '330') }}

+ +

You can see that the item is taking the area from grid row line 2 to 4, and starting after line 1. Then it is offset in that area using the top and left properties. However, it has been taken out of flow as is usually for absolutely positioned items and so the auto-placement rules now place items into the same space. The item also doesn’t cause the additional row to be created to span to row line 3.

+ +

If we remove position: absolute from the rules for .box3 you can see how it would display without the positioning.

+ +

A grid container as parent

+ +

If the absolutely positioned child has a grid container as a parent but that container does not create a new positioning context, then it is taken out of flow as in the previous example. The positioning context will be whatever element creates a positioning context as is common to other layout methods. In our case, if we remove position: relative from the wrapper above, positioning context is from the viewport, as shown in this image.

+ +

Image of grid container as parent

+ +

Once again the item no longer participates in the grid layout in terms of sizing or when other items are auto-placed.

+ +

With a grid area as the parent

+ +

If the absolutely positioned item is nested inside a grid area then you can create a positioning context on that area. In the below example we have our grid as before but this time I have nested an item inside .box3 of the grid.

+ +

I have given .box3 position relative and then positioned the sub-item with the offset properties. In this case, the positioning context is the grid area.

+ + + +
<div class="wrapper">
+  <div class="box1">One</div>
+  <div class="box2">Two</div>
+  <div class="box3">Three
+    <div class="abspos">
+     This block is absolutely positioned. In this example the grid area is the containing block and so the absolute positioning offset values are calculated in from the outer edges of the grid area.
+    </div>
+  </div>
+  <div class="box4">Four</div>
+</div>
+
+ +
.wrapper {
+  display: grid;
+  grid-template-columns: repeat(4,1fr);
+  grid-auto-rows: 200px;
+  grid-gap: 20px;
+}
+.box3 {
+  grid-column-start: 2;
+  grid-column-end: 4;
+  grid-row-start: 1;
+  grid-row-end: 3;
+  position: relative;
+}
+.abspos {
+  position: absolute;
+  top: 40px;
+  left: 40px;
+  background-color: rgba(255,255,255,.5);
+  border: 1px solid rgba(0,0,0,0.5);
+  color: #000;
+  padding: 10px;
+}
+
+ +

{{ EmbedLiveSample('With_a_grid_area_as_the_parent', '500', '420') }}

+ +

Grid and display: contents

+ +

A final interaction with another layout specification that is worth noting is the interaction between CSS Grid Layout and display: contents. The contents value of the display property is a new value that is described in the Display specification 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.”

+
+ +

If you set an item to display: contents the box it would normally create disappears, and the boxes of the child elements appear as if they have risen up a level. This means that children of a grid item can become grid items. Sound odd? Here is a simple example. In the following markup, I have a grid and the first item on the grid is set to span all three column tracks. It contains three nested items. As these items are not direct children, they don’t become part of the grid layout and so display using regular block layout.

+ +
+ + +
<div class="wrapper">
+  <div class="box box1">
+    <div class="nested">a</div>
+    <div class="nested">b</div>
+    <div class="nested">c</div>
+  </div>
+  <div class="box box2">Two</div>
+  <div class="box box3">Three</div>
+  <div class="box box4">Four</div>
+  <div class="box box5">Five</div>
+</div>
+
+ +
.wrapper {
+  display: grid;
+  grid-template-columns: repeat(3, 1fr);
+  grid-auto-rows: minmax(100px, auto);
+}
+.box1 {
+  grid-column-start: 1;
+  grid-column-end: 4;
+}
+
+
+ +

{{ EmbedLiveSample('Display_Contents_Before', '400', '420') }}

+
+ +

If I now add display: contents to the rules for box1, the box for that item vanishes and the sub-items now become grid items and lay themselves out using the auto-placement rules.

+ +
+ + +
<div class="wrapper">
+  <div class="box box1">
+    <div class="nested">a</div>
+    <div class="nested">b</div>
+    <div class="nested">c</div>
+  </div>
+  <div class="box box2">Two</div>
+  <div class="box box3">Three</div>
+  <div class="box box4">Four</div>
+  <div class="box box5">Five</div>
+</div>
+
+ +
.wrapper {
+  display: grid;
+  grid-template-columns: repeat(3, 1fr);
+  grid-auto-rows: minmax(100px, auto);
+}
+.box1 {
+  grid-column-start: 1;
+  grid-column-end: 4;
+  display: contents;
+}
+
+ +

{{ EmbedLiveSample('Display_Contents_After', '400', '330') }}

+
+ +

This can be a way to get items nested into the grid to act as if they are part of the grid, and is a way around some of the issues that would be solved by subgrids once they are implemented. You can also use display: contents in a similar way with flexbox to enable nested items to become flex items.

+ +

As you can see from this guide, CSS Grid Layout is just one part of your toolkit. Don’t be afraid to mix it with other methods of doing layout to get the different effects you need.

+ +

See Also

+ + + + diff --git a/files/pt-br/web/css/css_images/implementando_sprites_de_imagens_em_css/index.html b/files/pt-br/web/css/css_images/implementando_sprites_de_imagens_em_css/index.html new file mode 100644 index 0000000000..e14ba15c2d --- /dev/null +++ b/files/pt-br/web/css/css_images/implementando_sprites_de_imagens_em_css/index.html @@ -0,0 +1,47 @@ +--- +title: Implementando sprites de imagens em CSS +slug: Web/CSS/CSS_Images/Implementando_sprites_de_imagens_em_CSS +translation_of: Web/CSS/CSS_Images/Implementing_image_sprites_in_CSS +--- +
{{cssRef}}
+ +

Sprites de imagens são utilizados em diversas aplicações web onde várias imagens são usadas. Ao invés de incluir cada arquivo de imagem separadamente, é mais amigável com a memória e largura de banda enviar tudo como uma única imagem, diminuindo o número de pedidos em HTTP.

+ +
+

Nota: Quando usando HTTP/2, é mais amigável com a largura de banda usar vários pequenos pedidos.

+
+ +

Implementação

+ +

Suponha que uma imagem é dada a cada item com a classe toolbtn:

+ +
.toolbtn {
+  background: url(myfile.png);
+  display: inline-block;
+  height: 20px;
+  width: 20px;
+}
+ +

A posição do plano de fundo pode ser adicionada tanto com dois valores x, y depois de {{cssxref("url()")}} em background , ou como {{cssxref("background-position")}} . Por exemplo:

+ +
#btn1 {
+  background-position: -20px 0px;
+}
+
+#btn2 {
+  background-position: -40px 0px;
+}
+ +

Isso vai mover o elemento com a ID 'btn1' 20 pixels para a esquerda e o elemento com a ID 'btn2' 40 pixels para a esquerda (presumindo que ambos tem a classe toolbtn atribuída e estão sendo afetados pela regra da imagem acima).

+ +

De forma similar, você pode criar um efeito de hover com:

+ +
#btn:hover {
+  background-position: <pixels para direita>px <pixels para baixo>px;
+}
+ +

Veja também

+ + diff --git a/files/pt-br/web/css/css_images/index.html b/files/pt-br/web/css/css_images/index.html new file mode 100644 index 0000000000..b3e23ab194 --- /dev/null +++ b/files/pt-br/web/css/css_images/index.html @@ -0,0 +1,152 @@ +--- +title: CSS Images +slug: Web/CSS/CSS_Images +tags: + - CSS + - CSS Images + - NeedsTranslation + - Overview + - Reference + - TopicStub +translation_of: Web/CSS/CSS_Images +--- +
{{CSSRef}}
+ +

CSS Images is a module of CSS that defines what types of images can be used (the {{cssxref("<image>")}} type, containing URLs, gradients and other types of images), how to resize them and how they, and other replaced content, interact with the different layout models.

+ +

Reference

+ +

Properties

+ +
+
    +
  • {{cssxref("image-orientation")}}
  • +
  • {{cssxref("image-rendering")}}
  • +
  • {{cssxref("object-fit")}}
  • +
  • {{cssxref("object-position")}}
  • +
+
+ +

Functions

+ +
+
    +
  • {{cssxref("linear-gradient", "linear-gradient()")}}
  • +
  • {{cssxref("radial-gradient", "radial-gradient()")}}
  • +
  • {{cssxref("repeating-linear-gradient", "repeating-linear-gradient()")}}
  • +
  • {{cssxref("repeating-radial-gradient", "repeating-radial-gradient()")}}
  • +
  • {{cssxref("element", "element()")}}
  • +
+
+ +

Data types

+ +
+
    +
  • {{cssxref("<gradient>")}}
  • +
  • {{cssxref("<image>")}}
  • +
+
+ +

Guides

+ +
+
Using CSS gradients
+
Presents a specific type of CSS images, gradients, and how to create and use these.
+
Implementing image sprites in CSS
+
Describes the common technique grouping several images in one single document to save download requests and speed up the availability of a page.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS4 Images')}}{{Spec2('CSS4 Images')}} 
{{SpecName('CSS3 Images')}}{{Spec2('CSS3 Images')}} 
{{SpecName('Compat', '#css-%3Cimage%3E-type', 'CSS Gradients')}}{{Spec2('Compat')}}Standardizes the -webkit prefixed gradient value functions
{{SpecName('CSS3 Values', '#urls', '<url>')}}{{Spec2('CSS3 Values')}} 
{{Specname('CSS2.1', 'syndata.html#uri', '<uri>')}}{{Spec2('CSS2.1')}} 
{{SpecName('CSS1', '#url', '<url>')}}{{Spec2('CSS1')}}Initial definition
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support1.0{{CompatGeckoDesktop("1")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support1.0{{CompatGeckoMobile("1")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
diff --git a/files/pt-br/web/css/css_lists_and_counters/index.html b/files/pt-br/web/css/css_lists_and_counters/index.html new file mode 100644 index 0000000000..6da7c24f6d --- /dev/null +++ b/files/pt-br/web/css/css_lists_and_counters/index.html @@ -0,0 +1,135 @@ +--- +title: CSS Lists and Counters +slug: Web/CSS/CSS_Lists_and_Counters +tags: + - CSS + - CSS Lists and Counters + - CSS Reference + - NeedsTranslation + - Overview + - TopicStub +translation_of: Web/CSS/CSS_Lists_and_Counters +--- +

{{CSSRef}}

+ +

CSS Lists and Counters is a module of CSS that defines how lists are layed out, how the list marker can be styled and how authors can create new counters.

+ +

Reference

+ +

CSS Properties

+ +
+
    +
  • {{cssxref("list-style-image")}}
  • +
  • {{cssxref("list-style-type")}}
  • +
  • {{cssxref("list-style-position")}}
  • +
  • {{cssxref("list-style")}}
  • +
  • {{cssxref("counter-reset")}}
  • +
  • {{cssxref("counter-increment")}}
  • +
  •  
  • +
+
+ +

At-rules

+ +
+
{{cssxref("@counter-style")}}
+
+
+
    +
  • {{cssxref("@counter-style/system","system")}}
  • +
  • {{cssxref("@counter-style/additive-symbols", "additive-symbols")}}
  • +
  • {{cssxref("@counter-style/negative", "negative")}}
  • +
  • {{cssxref("@counter-style/prefix", "prefix")}}
  • +
  • {{cssxref("@counter-style/suffix", "suffix")}}
  • +
  • {{cssxref("@counter-style/range", "range")}}
  • +
  • {{cssxref("@counter-style/pad", "pad")}}
  • +
  • {{cssxref("@counter-style/speak-as", "speak-as")}}
  • +
  • {{cssxref("@counter-style/fallback", "fallback")}}
  • +
+
+
+
+ +

Guides

+ +
+
Consistent list indentation
+
Explains how to reach a consistent indentation between different browsers.
+
Using CSS counters
+
Describes how to use counters to be able to use numbering outside of traditionnal list element, or to perform complex counting.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSS3 Lists')}}{{ Spec2('CSS3 Lists') }} 
{{ SpecName('CSS2.1', 'generate.html') }}{{ Spec2('CSS2.1') }} 
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support1.0{{ CompatGeckoDesktop("1") }}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support1.0{{ CompatGeckoMobile("1") }}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
diff --git a/files/pt-br/web/css/css_lists_and_counters/using_css_counters/index.html b/files/pt-br/web/css/css_lists_and_counters/using_css_counters/index.html new file mode 100644 index 0000000000..2fb2dac4bd --- /dev/null +++ b/files/pt-br/web/css/css_lists_and_counters/using_css_counters/index.html @@ -0,0 +1,115 @@ +--- +title: Using CSS counters +slug: Web/CSS/CSS_Lists_and_Counters/Using_CSS_counters +translation_of: Web/CSS/CSS_Lists_and_Counters/Using_CSS_counters +--- +

{{CSSRef}}

+ +

Contadores CSS são em essência, as variáveis mantidas pelo CSS cujos valores podem ser incrementado por regras do CSS para controlar quantas vezes eles são usados.Isso permite ajustar a aparência do conteúdo com base na sua colocação no documento. contadores CSS são uma implementação de Contadores automáticos e numeração em CSS 2.1.

+ +

O valor de um contador é manipulado através da utilização de  {{cssxref("counter-reset")}}. {{cssxref("counter-increment")}} pode ser exibido em uma página usando o counter() ou counters() função da propriedade de conteúdo.

+ +

Usando contadores

+ +

Para usar um contador, tem quer definir um valor para ele (ele é 0 default). Para adicionar o valor do contador em um elemento, use a função counter(). O CSS abaixo adiciona "Section [o valor do contador]:" no início de cada elemento h3.

+ +
body {
+  counter-reset: section;                   /* Set the section counter to 0 */
+}
+h3::before {
+  counter-increment: section;               /* Increment the section counter*/
+  content: "Section" counter(section) ": "; /* Display the counter */
+}
+
+ +

Exemplo:

+ +
<h3>Introduction</h3>
+<h3>Body</h3>
+<h3>Conclusion</h3>
+ +

{{ EmbedLiveSample('Using_counters', 300,200) }}

+ +

Nesting counters

+ +

Um contador CSS pode ser especialmente útil para fazer listas descritas porque uma nova instância de um contador CSS é criado automaticamente em elementos filho . Usando a função counters(), uma corda pode ser inserido entre diferentes níveis de contadores aninhados. Por exemplo, esta CSS :

+ +
ol {
+  counter-reset: section;                /* Creates a new instance of the
+                                            section counter with each ol
+                                            element */
+  list-style-type: none;
+}
+li::before {
+  counter-increment: section;            /* Increments only this instance
+                                            of the section counter */
+  content: counters(section,".") " ";    /* Adds the value of all instances
+                                            of the section counter separated
+                                            by a ".". */
+                                         /* if you need to support < IE8 then
+                                            make sure there is no space after
+                                            the ',' */
+}
+
+ +

Combinado com o seguinte HTML:

+ +
<ol>
+  <li>item</li>          <!-- 1     -->
+  <li>item               <!-- 2     -->
+    <ol>
+      <li>item</li>      <!-- 2.1   -->
+      <li>item</li>      <!-- 2.2   -->
+      <li>item           <!-- 2.3   -->
+        <ol>
+          <li>item</li>  <!-- 2.3.1 -->
+          <li>item</li>  <!-- 2.3.2 -->
+        </ol>
+        <ol>
+          <li>item</li>  <!-- 2.3.1 -->
+          <li>item</li>  <!-- 2.3.2 -->
+          <li>item</li>  <!-- 2.3.3 -->
+        </ol>
+      </li>
+      <li>item</li>      <!-- 2.4   -->
+    </ol>
+  </li>
+  <li>item</li>          <!-- 3     -->
+  <li>item</li>          <!-- 4     -->
+</ol>
+<ol>
+  <li>item</li>          <!-- 1     -->
+  <li>item</li>          <!-- 2     -->
+</ol>
+ +

Produz este resultado:

+ +

{{ EmbedLiveSample('Nesting_counters',400,'100%') }}

+ +

Especificações

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS2.1', 'generate.html#generate.html#counters', 'counter-reset')}}{{Spec2('CSS2.1')}}
+ +

Veja mais

+ + + +

There is an additional example available at http://www.mezzoblue.com/archives/20.../counter_intu/. This blog entry was posted on November 01, 2006, but appears to be accurate.

diff --git a/files/pt-br/web/css/css_positioning/index.html b/files/pt-br/web/css/css_positioning/index.html new file mode 100644 index 0000000000..b88e028585 --- /dev/null +++ b/files/pt-br/web/css/css_positioning/index.html @@ -0,0 +1,65 @@ +--- +title: CSS Positioning +slug: Web/CSS/CSS_Positioning +tags: + - CSS + - CSS Positioning + - CSS Reference + - NeedsTranslation + - Overview + - TopicStub +translation_of: Web/CSS/CSS_Positioning +--- +

{{CSSRef}}

+ +

CSS Positioning é um módulo do CSS que define como ficam a posição dos elementos relativos e absolutos da página.

+ +

Referências

+ +

CSS Properties

+ +
+
    +
  • {{cssxref("bottom")}}
  • +
  • {{cssxref("clear")}}
  • +
  • {{cssxref("display")}}
  • +
  • {{cssxref("float")}}
  • +
  • {{cssxref("left")}}
  • +
  • {{cssxref("position")}}
  • +
  • {{cssxref("right")}}
  • +
  • {{cssxref("top")}}
  • +
  • {{cssxref("visibility")}}
  • +
  • {{cssxref("z-index")}}
  • +
+
+ +

Roteiro

+ +
+
Entendendo o CSS z-index
+
Apresenta o conceito de contexto de empilhamento e explica como funciona o atributo z-index, com diversos exemplos.
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{ SpecName('CSS3 Positioning') }}{{ Spec2('CSS3 Positioning') }}
{{ SpecName('CSS2.1', 'visuren.html') }}{{ Spec2('CSS2.1') }}
diff --git a/files/pt-br/web/css/css_reference/index.html b/files/pt-br/web/css/css_reference/index.html new file mode 100644 index 0000000000..1afbf4890e --- /dev/null +++ b/files/pt-br/web/css/css_reference/index.html @@ -0,0 +1,75 @@ +--- +title: Referência de CSS +slug: Web/CSS/CSS_Reference +translation_of: Web/CSS/Reference +--- +{{CSSRef}} + +

Use esta referência de CSS para navegar por um índice alfabético das propriedades padrão do CSS, pseudo-classes, pseudo-elementos, tipos de dados e @-rules.

+ +

Esta referência lista não somente as propriedades do CSS1 e CSS2.1, mas também referências para qualquer propriedade, conceito padronizado ou estabilizado do CSS3.

+ +

Veja também Extensões CSS Mozilla para propriedades específicas do Gecko prefixadas com -moz e Extensões CSS do WebKit para propriedades específicas do WebKit. Veja Visão geral de propriedades CSS prefixadas por distribuidor por Peter Beverloo para todas as propriedades prefixadas.

+ +

{{ CSS_Ref() }}

+ +

Seletores

+ + + +

Miscelânea

+ + + +

Conceitos

+ + diff --git a/files/pt-br/web/css/css_tipos/index.html b/files/pt-br/web/css/css_tipos/index.html new file mode 100644 index 0000000000..79256061ae --- /dev/null +++ b/files/pt-br/web/css/css_tipos/index.html @@ -0,0 +1,64 @@ +--- +title: Tipos básicos de dados CSS +slug: Web/CSS/CSS_Tipos +tags: + - CSS + - CSS tipos de dados + - Referencia + - Visão Geral +translation_of: Web/CSS/CSS_Types +--- +
{{CssRef}}
+ +

Tipos básicos de dados CSS definem valores típicos (incluindo palavras chaves e unidades) aceitos pelas propriedades e funções do CSS. Eles são um tipo especial de tipo de valor do componente.
+
+ Na sintaxe formal, os tipos de dados são indicados pela palavra chave aplicada entre os sinais de desigualdade "<" e ">".

+ +

Referência

+ +
+
    +
  • {{cssxref("<angle>")}}
  • +
  • {{cssxref("<basic-shape>")}}
  • +
  • {{cssxref("<blend-mode>")}}
  • +
  • {{cssxref("<color>")}}
  • +
  • {{cssxref("<custom-ident>")}}
  • +
  • {{cssxref("<filter-function>")}}
  • +
  • {{cssxref("<flex>")}}
  • +
  • {{cssxref("<frequency>")}}
  • +
  • {{cssxref("<gradient>")}}
  • +
  • {{cssxref("<image>")}}
  • +
  • {{cssxref("<integer>")}}
  • +
  • {{cssxref("<length>")}}
  • +
  • {{cssxref("<number>")}}
  • +
  • {{cssxref("<percentage>")}}
  • +
  • {{cssxref("<position>")}}
  • +
  • {{cssxref("<ratio>")}}
  • +
  • {{cssxref("<resolution>")}}
  • +
  • {{cssxref("<shape-box>")}}
  • +
  • {{cssxref("<single-transition-timing-function>")}}
  • +
  • {{cssxref("<string>")}}
  • +
  • {{cssxref("<time>")}}
  • +
  • {{cssxref("<transform-function>")}}
  • +
  • {{cssxref("<url>")}}
  • +
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{ SpecName('CSS3 Values') }}{{ Spec2('CSS3 Values') }}Definição inicial.
diff --git a/files/pt-br/web/css/css_transforms/index.html b/files/pt-br/web/css/css_transforms/index.html new file mode 100644 index 0000000000..56f6df6745 --- /dev/null +++ b/files/pt-br/web/css/css_transforms/index.html @@ -0,0 +1,145 @@ +--- +title: CSS Transforms +slug: Web/CSS/CSS_Transforms +translation_of: Web/CSS/CSS_Transforms +--- +

{{CSSRef}}{{SeeCompatTable}}

+ +

CSS Transforms is a module of CSS that defines how elements styled with CSS can be transformed in two-dimensional or three-dimensional space.

+ +

Referencia

+ +

CSS Properties

+ +
+
    +
  • {{cssxref("backface-visibility")}}
  • +
  • {{cssxref("perspective")}}
  • +
  • {{cssxref("perspective-origin")}}
  • +
  • {{cssxref("transform")}}
  • +
  • {{cssxref("transform-box")}}
  • +
  • {{cssxref("transform-origin")}}
  • +
  • {{cssxref("transform-style")}}
  • +
+
+ +

Guides

+ +
+
Using CSS transforms
+
Step-by-step tutorial about how to transform elements styled with CSS.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSS3 Transforms') }}{{ Spec2('CSS3 Transforms') }}Initial definition.
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support +

{{CompatVersionUnknown}} {{property_prefix("-webkit")}}
+ 36

+
{{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")}}
3D Support12.0{{property_prefix("-webkit")}}
+ 36
10.0{{property_prefix("-moz")}}
+ {{CompatGeckoDesktop("16.0")}}
10.015.0{{property_prefix("-webkit")}}
+ 23
4.0{{property_prefix("-webkit")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatAndroid(2.1)}}{{property_prefix("-webkit")}}[4]{{CompatVersionUnknown}}{{property_prefix("-webkit")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+ 11.0{{property_prefix("-webkit")}}[5]
11.5{{property_prefix("-webkit")}}3.2 {{CompatVersionUnknown}}{{property_prefix("-webkit")}}
3D Support{{CompatAndroid(3.0)}}{{property_prefix("-webkit")}}{{CompatVersionUnknown}}{{ property_prefix("-webkit")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}22{{property_prefix("-webkit")}}3.2 {{CompatVersionUnknown}}{{property_prefix("-webkit")}}
+
+ +

[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>")}}.

+ +

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

+ +

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

+ +

 

diff --git a/files/pt-br/web/css/css_transforms/using_css_transforms/index.html b/files/pt-br/web/css/css_transforms/using_css_transforms/index.html new file mode 100644 index 0000000000..168cc81c3d --- /dev/null +++ b/files/pt-br/web/css/css_transforms/using_css_transforms/index.html @@ -0,0 +1,222 @@ +--- +title: Usando CSS transforms +slug: Web/CSS/CSS_Transforms/Using_CSS_transforms +translation_of: Web/CSS/CSS_Transforms/Using_CSS_transforms +--- +
{{CSSRef}}
+ +

Mudando coordenadas no espaço da tela o CSS transforms permite que a posição do conteúdo afetado seja alterada sem afetar o fluxo de informação da página. Elas são implementadas usando um conjunto de propriedades CSS que permitem alterações lineares em elementos HTML. Essas alterações incluem rotação, inclinações, alteração da escala e tradução tanto em 2D quanto em 3D.

+ +

Propriedades de CSS transforms

+ +

Duas propriedades principais são usadas para definir o CSS transforms: {{ cssxref("transform") }} and {{ cssxref("transform-origin") }}

+ +
+
{{ cssxref("transform-origin") }}
+
Define a posição de origem do elemento. Por padrão esta posição é o canto superior esquerdo do elemento e pode ser movido. É utilizado para muitas alterações, como rotação, alteração de escala e inclinação, que precisam de um ponto especifico como parâmetro.
+
{{ cssxref("transform") }}
+
Define qual alteração será feita no elemento. Pode-se usar mais de um efeito separado-os por um espaço. Tais efeitos serão aplicados um após o outro, na ordem determinada no código.
+
+ +

Exemplo: Rotação

+ +

Este exemplo cria um iframe que permite que a página inicial do Google seja utilizada com uma rotação de 90 graus a partir do canto inferior esquerdo

+ +

Veja um exemplo funcionando
+ Veja uma foto do exemplo

+ +
<div style="transform: rotate(90deg); transform-origin: bottom left;">
+  <iframe src="http://www.google.com/" width="500" height="600"></iframe>
+</div>
+
+ +

Example: Inclinando e Movendo

+ +

Este exemplo cria um iframe que permite que você use a página inicial do Google inclinada em 10 graus no eixo X.

+ +

Veja um exemplo funcionando
+ View uma foto do exemplo

+ +
<div style="transform: skewx(10deg) translatex(150px);
+            transform-origin: bottom left;">
+  <iframe src="http://www.google.com/" width="600" height="500"></iframe>
+</div>
+
+ +

Propriedades especificas 3D do CSS

+ +

Trabalhar com propriedades CSS em 3D é um pouco mais difícil. Você tem que começar configurando o espaço 3D dando perspectiva a ele, então você tem que configurar como os elementos 2D irão se comportar no espaço.

+ +

Configurando uma perspectiva

+ +

O primeiro elemento a ser configurado é a perspectiva. É ela a responsável pela sensação de 3D. Quanto mais longe o objeto estiver do usuário, menor ele é.

+ +

Quanto será a sensação de encolhimento é definida pela propriedade {{ cssxref("perspective") }}. Quanto menor o valor, mais profundidade terá o objeto.

+ +
+ + + + + + + + + + + + + + + +
perspective:0;perspective:150px;perspective:300px;perspective:600px;
+
+
+
   
+ +
1
+ +
2
+ +
3
+ +
4
+ +
5
+ +
6
+
+
+
+
+
+
   
+ +
1
+ +
2
+ +
3
+ +
4
+ +
5
+ +
6
+
+
+
+
+
+
   
+ +
1
+ +
2
+ +
3
+ +
4
+ +
5
+ +
6
+
+
+
+
+
+
   
+ +
1
+ +
2
+ +
3
+ +
4
+ +
5
+ +
6
+
+
+
+
+ +

O segundo elemento a ser configurado é a posição de visão, que será definida pela propriedade {{ cssxref("perspective-origin") }}. Por padrão a perspectiva é centralizada, o que nem sempre é o ideal.

+ +
+ + + + + + + + + + + + + +
perspective-origin:150px 150px;perspective-origin:50% 50%;perspective-origin:-50px -50px;
+
+
+
1
+ +
2
+ +
3
+ +
4
+ +
5
+ +
6
+
+
+
+
+
+
1
+ +
2
+ +
3
+ +
4
+ +
5
+ +
6
+
+
+
+
+
+
1
+ +
2
+ +
3
+ +
4
+ +
5
+ +
6
+
+
+
+
+ +

Feito isso, você pode trabalhar com elementos 3D.

+ +

Elementos 2D em espaço 3D

+ +

Veja também

+ + diff --git a/files/pt-br/web/css/css_transitions/index.html b/files/pt-br/web/css/css_transitions/index.html new file mode 100644 index 0000000000..de2b11a35c --- /dev/null +++ b/files/pt-br/web/css/css_transitions/index.html @@ -0,0 +1,61 @@ +--- +title: CSS Transitions +slug: Web/CSS/CSS_Transitions +tags: + - CSS + - CSS Transitions + - NeedsTranslation + - Overview + - Reference + - TopicStub +translation_of: Web/CSS/CSS_Transitions +--- +
{{CSSRef}}
+ +

CSS Transitions is a module of CSS that lets you create gradual transitions between the values of specific CSS properties. The behavior of these transitions can be controlled by specifying their timing function, duration, and other attributes.

+ +

Reference

+ +

Properties

+ +
+
    +
  • {{cssxref("transition")}}
  • +
  • {{cssxref("transition-delay")}}
  • +
  • {{cssxref("transition-duration")}}
  • +
  • {{cssxref("transition-property")}}
  • +
  • {{cssxref("transition-timing-function")}}
  • +
+
+ +

Guides

+ +
+
Using CSS transitions
+
Step-by-step tutorial about how to create transitions using CSS. This article describes each relevant CSS property and explains how they interact with each other.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Transitions')}}{{Spec2('CSS3 Transitions')}}Initial definition.
+ +

See also

+ +
    +
  • Related to CSS Transitions, CSS Animations provide finer control over animated properties.
  • +
diff --git a/files/pt-br/web/css/css_transitions/using_css_transitions/index.html b/files/pt-br/web/css/css_transitions/using_css_transitions/index.html new file mode 100644 index 0000000000..2e1b4e331f --- /dev/null +++ b/files/pt-br/web/css/css_transitions/using_css_transitions/index.html @@ -0,0 +1,1075 @@ +--- +title: Using CSS transitions +slug: Web/CSS/CSS_Transitions/Using_CSS_transitions +translation_of: Web/CSS/CSS_Transitions/Using_CSS_transitions +--- +

{{CSSref}}

+ +

CSS transitions provê uma forma de controlar a velocidade de uma animação quando há mudanças de propriedades CSS. Ao invés de uma propriedade entrar em vigor imediatamente, você pode fazer com que as mudanças em uma propriedade ocorram durante um periodo de tempo. Por exemplo, se você mudar a cor de um elemento de branco para preto, a alteração será instantanea. Utilizando transições CSS, as alterações acontecem em uma intervalo de tempo que seguem uma curva de aceleração, e todas podem ser personalizadas

+ +

Animações que envolvem transições entre dois estados geralmente são chamadas de transições implicitas, como os estados entre o começo e o fim são implicitamente definidos pelo browser

+ +

A CSS transition tells the browser to draw the intermediate states between the initial and final states, showing the user a smooth transitions.

+ +

Animações CSS permitem que você decida quais propriedades animar (listando-os explicitamente), quando a animação deve começar (definindo o delay), quão longa a transição será (definindo a duração), e como a transição irá ocorrer (definindo o tempo da função, linear ou rápido no início, lento no final).

+ +

Quais propriedade CSS podem transicionadas?

+ +

Você mesmo pode definir qual propriedade será transicionada e de qual maneira. E isso permite a criação de transições complexas. Como não faz sentido animar algumas propriedades, existe uma lista finita com propriedades que podem ser transicionadas.

+ +
Observação:  A lista de propriedades que podem ser animadas sofre alterações a medida que a especificação se desenvolve.
+ +

O valor automatico ,  geralmente é complexo.  A especificação recomenda não animar com valores automaticos. Alguns user agents, como aqueles baseados no Genko, implementam esse requisito, como aqueles baseados no WebKit, são menos rigosos. Animações CSS que utlizam o valor automatico, podem levar resultados imprevisiveis, dependendo do Browser e da versão, e isso pode ser evitado.

+ +

Definindo transições

+ +

Transições CSS são controladas usando a propriedade {{cssxref("transition")}}. Essa é a melhor maneira de configurar uma transição, assim evitamos parâmetros fora de sintonia, o que pode ser muito frustrante desperdiçar tanto tempo debuggando CSS.

+ +

Você pode controlar componentes individuais da transição com a seguinte sub propriedade:

+ +

(Observe que essas transições fazem um loop infinitamente apenas para o propósito de nossos exemplos; transitions apenas visualizam a mudança na propriedade de começo ao fim. Se você precisar de visualizações desse loop, procure na propriedade {{cssxref("animation")}}.)

+ +
+
{{cssxref("transition-property")}}
+
Especifica o nome ou nomes das propriedades CSS que as transições serão aplicadas. Somente as propriedades listadas aqui serão animadas durante a transição; alterações e todas outras propriedades ocorrem instantaneamente.
+
{{cssxref("transition-duration")}}
+
+
Especifica a duração em que as transições devem ocorrer. Você pode especificar uma única duração que se aplica a todas as propriedades durante a transição ou vários valores para permitir que cada propriedade faça a transição em um período de tempo diferente. +
+
+

transition-duration: 0.5s

+ +
+
 <div class="parent">
+  <div class="box">Lorem</div>
+</div>
+  
+ +
.parent { width: 250px; height:125px;}
+.box {
+    width: 100px;
+    height: 100px;
+    background-color: red;
+    font-size: 20px;
+    left: 0px;
+    top: 0px;
+    position:absolute;
+    -webkit-transition-property: width height background-color font-size left top transform -webkit-transform color;
+    -webkit-transition-duration: 0.5s;
+    -webkit-transition-timing-function: ease-in-out;
+    transition-property: width height background-color font-size left top transform -webkit-transform color;
+    transition-duration: 0.5s;
+    transition-timing-function: ease-in-out;
+}
+.box1{
+    transform: rotate(270deg);
+    -webkit-transform: rotate(270deg);
+    width: 50px;
+    height: 50px;
+    background-color: blue;
+    color: yellow;
+    font-size: 18px;
+    left: 150px;
+    top: 25px;
+    position: absolute;
+    -webkit-transition-property: width height background-color font-size left top transform -webkit-transform color;
+    -webkit-transition-duration: 0.5s;
+    -webkit-transition-timing-function: ease-in-out;
+    transition-property: width height background-color font-size left top transform -webkit-transformv color;
+    transition-duration: 0.5s;
+    transition-timing-function: ease-in-out;
+}
+
+ +
function updateTransition() {
+  var el = document.querySelector("div.box");
+
+  if (el) {
+    el.className = "box1";
+  } else {
+    el = document.querySelector("div.box1");
+    el.className = "box";
+  }
+
+  return el;
+}
+
+var intervalID = window.setInterval(updateTransition, 7000);
+
+
+ +
{{EmbedLiveSample("duration_0_5s", 275, 150)}}
+
+ +
+

transition-duration: 1s

+ +
+
 <div class="parent">
+  <div class="box">Lorem</div>
+</div>
+  
+ +
.parent { width: 250px; height:125px;}
+.box {
+    width: 100px;
+    height: 100px;
+    background-color: red;
+    font-size: 20px;
+    left: 0px;
+    top: 0px;
+    position: absolute;
+    -webkit-transition-property: width height background-color font-size left top -webkit-transform color;
+    -webkit-transition-duration: 1s;
+    -webkit-transition-timing-function: ease-in-out;
+    transition-property: width height background-color font-size left top transform color;
+    transition-duration: 1s;
+    transition-timing-function: ease-in-out;
+}
+.box1{
+    transform: rotate(270deg);
+    -webkit-transform: rotate(270deg);
+    width: 50px;
+    height: 50px;
+    background-color: blue;
+    color: yellow;
+    font-size: 18px;
+    left: 150px;
+    top: 25px;
+    position: absolute;
+    -webkit-transition-property: width height background-color font-size left top -webkit-transform transform color;
+    -webkit-transition-duration: 1s;
+    -webkit-transition-timing-function: ease-in-out;
+    transition-property: width height background-color font-size left top transform -webkit-transform color;
+    transition-duration: 1s;
+    transition-timing-function: ease-in-out;
+}
+
+ +
function updateTransition() {
+  var el = document.querySelector("div.box");
+
+  if (el) {
+    el.className = "box1";
+  } else {
+    el = document.querySelector("div.box1");
+    el.className = "box";
+  }
+
+  return el;
+}
+
+var intervalID = window.setInterval(updateTransition, 7000);
+
+
+ +
{{EmbedLiveSample("duration_1s",275,150)}}
+
+ +
+

transition-duration: 2s

+ +
+
 <div class="parent">
+  <div class="box">Lorem</div>
+</div>
+  
+ +
.parent { width: 250px; height:125px;}
+.box {
+    width: 100px;
+    height: 100px;
+    background-color: red;
+    font-size: 20px;
+    left: 0px;
+    top: 0px;
+    position: absolute;
+    -webkit-transition-property: width height background-color font-size left top transform -webkit-transform color;
+    -webkit-transition-duration: 2s;
+    -webkit-transition-timing-function: ease-in-out;
+    transition-property: width height background-color font-size left top transform -webkit-transform color;
+    transition-duration: 2s;
+    transition-timing-function: ease-in-out;
+}
+.box1{
+    transform: rotate(270deg);
+    -webkit-transform: rotate(270deg);
+    width: 50px;
+    height: 50px;
+    background-color: blue;
+    color: yellow;
+    font-size: 18px;
+    left: 150px;
+    top: 25px;
+    position: absolute;
+    -webkit-transition-property: width height background-color font-size left top transform -webkit-transform color;
+    -webkit-transition-duration: 2s;
+    -webkit-transition-timing-function: ease-in-out;
+    transition-property: width height background-color font-size left top transform -webkit-transform color;
+    transition-duration: 2s;
+    transition-timing-function: ease-in-out;
+}
+
+ +
function updateTransition() {
+  var el = document.querySelector("div.box");
+
+  if (el) {
+    el.className = "box1";
+  } else {
+    el = document.querySelector("div.box1");
+    el.className = "box";
+  }
+
+  return el;
+}
+
+var intervalID = window.setInterval(updateTransition, 7000);
+
+
+ +
{{EmbedLiveSample("duration_2s",275,150)}}
+
+ +
+

transition-duration: 4s

+ +
+
 <div class="parent">
+  <div class="box">Lorem</div>
+</div>
+  
+ +
.parent { width: 250px; height:125px;}
+.box {
+    width: 100px;
+    height: 100px;
+    background-color: red;
+    font-size: 20px;
+    left: 0px;
+    top: 0px;
+    position: absolute;
+    -webkit-transition-property: width height background-color font-size left top transform -webkit-transform color;
+    -webkit-transition-duration: 4s;
+    -webkit-transition-timing-function: ease-in-out;
+    transition-property: width height background-color font-size left top transform -webkit-transform color;
+    transition-duration: 4s;
+    transition-timing-function: ease-in-out;
+}
+.box1{
+    transform: rotate(270deg);
+    -webkit-transform: rotate(270deg);
+    width: 50px;
+    height: 50px;
+    background-color: blue;
+    color: yellow;
+    font-size: 18px;
+    left: 150px;
+    top: 25px;
+    position: absolute;
+    -webkit-transition-property: width height background-color font-size left top transform -webkit-transform color;
+    -webkit-transition-duration: 4s;
+    -webkit-transition-timing-function: ease-in-out;
+    transition-property: width height background-color font-size left top transform -webkit-transform color;
+    transition-duration: 4s;
+    transition-timing-function: ease-in-out;
+}
+
+ +
function updateTransition() {
+  var el = document.querySelector("div.box");
+
+  if (el) {
+    el.className = "box1";
+  } else {
+    el = document.querySelector("div.box1");
+    el.className = "box";
+  }
+
+  return el;
+}
+
+var intervalID = window.setInterval(updateTransition, 7000);
+
+
+ +
{{EmbedLiveSample("duration_4s",275,150)}}
+
+
+
+
{{cssxref("transition-timing-function")}}
+
+
 Especifica uma função para definir como os valores intermediários das propriedades são calculados. As timing functions determinam como os valores intermediários da transição são calculados. A maioria das funções de temporização pode ser especificada fornecendo o gráfico da função correspondente, conforme definido por quatro pontos definindo um bezier cúbico. Você também pode escolher o Easing Functions Cheat Sheet. +
+
+

transition-timing-function: ease

+ +
+
 <div class="parent">
+  <div class="box">Lorem</div>
+</div>
+  
+ +
.parent { width: 250px; height:125px;}
+.box {
+    width: 100px;
+    height: 100px;
+    background-color: red;
+    font-size: 20px;
+    left: 0px;
+    top: 0px;
+    position: absolute;
+    -webkit-transition-property: width height background-color font-size left top color;
+    -webkit-transition-duration: 2s;
+    -webkit-transition-timing-function: ease;
+    transition-property: width height background-color font-size left top color;
+    transition-duration: 2s;
+    transition-timing-function: ease;
+}
+.box1{
+    width: 50px;
+    height: 50px;
+    background-color: blue;
+    color: yellow;
+    font-size: 18px;
+    left: 150px;
+    top: 25px;
+    position:absolute;
+    -webkit-transition-property: width height background-color font-size left top color;
+    -webkit-transition-duration: 2s;
+    -webkit-transition-timing-function: ease;
+    transition-property: width height background-color font-size left top color;
+    transition-duration: 2s;
+    transition-timing-function: ease;
+}
+
+ +
function updateTransition() {
+  var el = document.querySelector("div.box");
+
+  if (el) {
+    el.className = "box1";
+  } else {
+    el = document.querySelector("div.box1");
+    el.className = "box";
+  }
+
+  return el;
+}
+
+var intervalID = window.setInterval(updateTransition, 7000);
+
+
+ +
{{EmbedLiveSample("ttf_ease",275,150)}}
+
+ +
+

transition-timing-function: linear

+ +
+
 <div class="parent">
+  <div class="box">Lorem</div>
+</div>
+  
+ +
.parent { width: 250px; height:125px;}
+.box {
+    width: 100px;
+    height: 100px;
+    background-color: red;
+    font-size: 20px;
+    left: 0px;
+    top: 0px;
+    position: absolute;
+    -webkit-transition-property: width height background-color font-size left top color;
+    -webkit-transition-duration: 2s;
+    -webkit-transition-timing-function: linear;
+    transition-property: width height background-color font-size left top color;
+    transition-duration: 2s;
+    transition-timing-function: linear;
+}
+.box1{
+    width: 50px;
+    height: 50px;
+    background-color: blue;
+    color: yellow;
+    font-size: 18px;
+    left: 150px;
+    top:25px;
+    position: absolute;
+    -webkit-transition-property: width height background-color font-size left top color;
+    -webkit-transition-duration: 2s;
+    -webkit-transition-timing-function: linear;
+    transition-property: width height background-color font-size left top color;
+    transition-duration: 2s;
+    transition-timing-function: linear;
+}
+
+ +
function updateTransition() {
+  var el = document.querySelector("div.box");
+
+  if (el) {
+    el.className = "box1";
+  } else {
+    el = document.querySelector("div.box1");
+    el.className = "box";
+  }
+
+  return el;
+}
+
+var intervalID = window.setInterval(updateTransition, 7000);
+
+
+ +
{{EmbedLiveSample("ttf_linear",275,150)}}
+
+ +
+

transition-timing-function: step-end

+ +
+
 <div class="parent">
+  <div class="box">Lorem</div>
+</div>
+  
+ +
.parent { width: 250px; height:125px;}
+.box {
+    width: 100px;
+    height: 100px;
+    background-color: red;
+    font-size: 20px;
+    left: 0px;
+    top: 0px;
+    position: absolute;
+    -webkit-transition-property: width height background-color font-size left top color;
+    -webkit-transition-duration: 2s;
+    -webkit-transition-timing-function: step-end;
+    transition-property: width height background-color font-size left top color;
+    transition-duration: 2s;
+    transition-timing-function: step-end;
+}
+.box1{
+    width: 50px;
+    height: 50px;
+    background-color: blue;
+    color: yellow;
+    font-size: 18px;
+    left: 150px;
+    top:25px;
+    position: absolute;
+    -webkit-transition-property: width height background-color font-size left top color;
+    -webkit-transition-duration: 2s;
+    -webkit-transition-timing-function: step-end;
+    transition-property: width height background-color font-size left top color;
+    transition-duration: 2s;
+    transition-timing-function: step-end;
+}
+
+ +
function updateTransition() {
+  var el = document.querySelector("div.box");
+
+  if (el) {
+    el.className = "box1";
+  } else {
+    el = document.querySelector("div.box1");
+    el.className = "box";
+  }
+
+  return el;
+}
+
+var intervalID = window.setInterval(updateTransition, 7000);
+
+
+ +
{{EmbedLiveSample("ttf_stepend",275,150)}}
+
+ +
+

transition-timing-function: steps(4, end)

+ +
+
 <div class="parent">
+  <div class="box">Lorem</div>
+</div>
+  
+ +
.parent { width: 250px; height:125px;}
+.box {
+    width: 100px;
+    height: 100px;
+    background-color: red;
+    font-size: 20px;
+    left: 0px;
+    top: 0px;
+    position: absolute;
+    -webkit-transition-property: width height background-color font-size left top color;
+    -webkit-transition-duration: 2s;
+    -webkit-transition-timing-function: steps(4, end);
+    transition-property: width height background-color font-size left top color;
+    transition-duration: 2s;
+    transition-timing-function: steps(4, end);
+}
+.box1{
+    width: 50px;
+    height: 50px;
+    background-color: blue;
+    color: yellow;
+    font-size: 18px;
+    left: 150px;
+    top: 25px;
+    position: absolute;
+    -webkit-transition-property: width height background-color font-size left top color;
+    -webkit-transition-duration: 2s;
+    -webkit-transition-timing-function: steps(4, end);
+    transition-property: width height background-color font-size left top color;
+    transition-duration: 2s;
+    transition-timing-function: steps(4, end);
+}
+
+ +
function updateTransition() {
+  var el = document.querySelector("div.box");
+
+  if (el) {
+    el.className = "box1";
+  } else {
+    el = document.querySelector("div.box1");
+    el.className = "box";
+  }
+
+  return el;
+}
+
+var intervalID = window.setInterval(updateTransition, 7000);
+
+
+ +
{{EmbedLiveSample("ttf_step4end",275,150)}}
+
+
+
+
{{cssxref("transition-delay")}}
+
Define quanto tempo esperar entre o momento que uma propriedade é alterada e a transição começa. +
+
+

transition-delay: 0.5s

+ +
+
 <div class="parent">
+  <div class="box">Lorem</div>
+</div>
+  
+ +
.parent {
+    width: 250px;
+    height: 125px;
+}
+
+.box {
+    width: 100px;
+    height: 100px;
+    background-color: red;
+    font-size: 20px;
+    left: 0px;
+    top: 0px;
+    position: absolute;
+    -webkit-transition-property: width height background-color font-size left top color;
+    -webkit-transition-duration: 2s;
+    -webkit-transition-delay: 0.5s;
+    -webkit-transition-timing-function: linear;
+    transition-property: width height background-color font-size left top color;
+    transition-duration: 2s;
+    transition-delay: 0.5s;
+    transition-timing-function: linear;
+}
+
+.box1 {
+    width: 50px;
+    height: 50px;
+    background-color: blue;
+    color: yellow;
+    font-size: 18px;
+    left: 150px;
+    top:25px;
+    position: absolute;
+     -webkit-transition-property: width height background-color font-size left top color;
+    -webkit-transition-duration: 2s;
+    -webkit-transition-delay: 0.5s;
+    -webkit-transition-timing-function: linear;
+    transition-property: width height background-color font-size left top color;
+    transition-duration: 2s;
+    transition-delay: 0.5s;
+    transition-timing-function: linear;
+}
+
+ +
function updateTransition() {
+  var el = document.querySelector("div.box");
+
+  if (el) {
+    el.className = "box1";
+  } else {
+    el = document.querySelector("div.box1");
+    el.className = "box";
+  }
+
+  return el;
+}
+
+var intervalID = window.setInterval(updateTransition, 7000);
+
+
+ +
{{EmbedLiveSample("delay_0_5s",275,150)}}
+
+ +
+

transition-delay: 1s

+ +
+
 <div class="parent">
+  <div class="box">Lorem</div>
+</div>
+  
+ +
.parent {
+    width: 250px;
+    height: 125px;
+}
+
+.box {
+    width: 100px;
+    height: 100px;
+    background-color: red;
+    font-size: 20px;
+    left: 0px;
+    top: 0px;
+    position: absolute;
+     -webkit-transition-property: width height background-color font-size left top color;
+    -webkit-transition-duration: 2s;
+    -webkit-transition-delay: 1s;
+    -webkit-transition-timing-function: linear;
+    transition-property: width height background-color font-size left top color;
+    transition-duration: 2s;
+    transition-delay: 1s;
+    transition-timing-function: linear;
+}
+
+.box1{
+    width: 50px;
+    height: 50px;
+    background-color: blue;
+    color: yellow;
+    font-size: 18px;
+    left: 150px;
+    top: 25px;
+    position: absolute;
+    -webkit-transition-property: width height background-color font-size left top color;
+    -webkit-transition-duration: 2s;
+    -webkit-transition-delay: 1s;
+    -webkit-transition-timing-function: linear;
+    transition-property: width height background-color font-size left top color;
+    transition-duration: 2s;
+    transition-delay: 1s;
+    transition-timing-function: linear;
+}
+
+ +
function updateTransition() {
+  var el = document.querySelector("div.box");
+
+  if (el) {
+    el.className = "box1";
+  } else {
+    el = document.querySelector("div.box1");
+    el.className = "box";
+  }
+
+  return el;
+}
+
+var intervalID = window.setInterval(updateTransition, 7000);
+
+
+ +
{{EmbedLiveSample("delay_1s",275,150)}}
+
+ +
+

transition-delay: 2s

+ +
+
 <div class="parent">
+  <div class="box">Lorem</div>
+</div>
+  
+ +
.parent {
+    width: 250px;
+    height: 125px;
+}
+
+.box {
+    width: 100px;
+    height: 100px;
+    background-color: red;
+    font-size: 20px;
+    left: 0px;
+    top: 0px;
+    position: absolute;
+    -webkit-transition-property: width height background-color font-size left top color;
+    -webkit-transition-duration: 2s;
+    -webkit-transition-delay: 2s;
+    -webkit-transition-timing-function: linear;
+    transition-property: width height background-color font-size left top color;
+    transition-duration: 2s;
+    transition-delay: 2s;
+    transition-timing-function: linear;
+}
+
+.box1 {
+    width: 50px;
+    height: 50px;
+    background-color: blue;
+    color: yellow;
+    font-size: 18px;
+    left: 150px;
+    top: 25px;
+    position: absolute;
+    -webkit-transition-property: width height background-color font-size left top color;
+    -webkit-transition-duration: 2s;
+    -webkit-transition-delay: 2s;
+    -webkit-transition-timing-function: linear;
+    transition-property: width height background-color font-size left top color;
+    transition-duration: 2s;
+    transition-delay: 2s;
+    transition-timing-function: linear;
+}
+
+ +
function updateTransition() {
+  var el = document.querySelector("div.box");
+
+  if (el) {
+    el.className = "box1";
+  } else {
+    el = document.querySelector("div.box1");
+    el.className = "box";
+  }
+
+  return el;
+}
+
+var intervalID = window.setInterval(updateTransition, 7000);
+
+
+ +
{{EmbedLiveSample("delay_2s",275,150)}}
+
+ +
+

transition-delay: 4s

+ +
+
 <div class="parent">
+  <div class="box">Lorem</div>
+</div>
+  
+ +
.parent {
+    width: 250px;
+    height: 125px;
+}
+
+.box {
+    width: 100px;
+    height: 100px;
+    background-color: red;
+    font-size: 20px;
+    left: 0px;
+    top: 0px;
+    position: absolute;
+    -webkit-transition-property: width height background-color font-size left top color;
+    -webkit-transition-duration: 2s;
+    -webkit-transition-delay: 4s;
+    -webkit-transition-timing-function: ease-in-out;
+    transition-property: width height background-color font-size left top color;
+    transition-duration: 2s;
+    transition-delay: 4s;
+    transition-timing-function: ease-in-out;
+}
+
+.box1 {
+    width: 50px;
+    height: 50px;
+    background-color: blue;
+    color: yellow;
+    font-size: 18px;
+    left: 150px;
+    top: 25px;
+    position: absolute;
+    -webkit-transition-property: width height background-color font-size left top color;
+    -webkit-transition-duration: 2s;
+    -webkit-transition-delay: 4s;
+    -webkit-transition-timing-function: ease-in-out;
+    transition-property: width height background-color font-size left top color;
+    transition-duration: 2s;
+    transition-delay: 4s;
+    transition-timing-function: ease-in-out;
+}
+
+ +
function updateTransition() {
+  var el = document.querySelector("div.box");
+
+  if (el) {
+    el.className = "box1";
+  } else {
+    el = document.querySelector("div.box1");
+    el.className = "box";
+  }
+
+  return el;
+}
+
+var intervalID = window.setInterval(updateTransition, 7000);
+
+
+ +
{{EmbedLiveSample("delay_4s",275,150)}}
+
+
+
+
+ +

A sintaxe do CSS é abreviada da seguinte forma:

+ +
div {
+    transition: <property> <duration> <timing-function> <delay>;
+}
+ +

Exemplos

+ +

Exemplo simples

+ +

Esse exemplo executa uma transição de com duração de 4 segundos de delay entre o tempo que o usuário passa o mouse sobre o elemento (evento mouseover), e o início do efeito da animação

+ +
#delay {
+  font-size: 14px;
+  transition-property: font-size;
+  transition-duration: 4s;
+  transition-delay: 2s;
+}
+
+#delay:hover {
+  font-size: 36px;
+}
+
+ +

Exemplo de multiplicas animações de propriedades 

+ + + +

Conteúdo CSS

+ +
.box {
+    border-style: solid;
+    border-width: 1px;
+    display: block;
+    width: 100px;
+    height: 100px;
+    background-color: #0000FF;
+    -webkit-transition: width 2s, height 2s, background-color 2s, -webkit-transform 2s;
+    transition: width 2s, height 2s, background-color 2s, transform 2s;
+}
+
+.box:hover {
+    background-color: #FFCCCC;
+    width: 200px;
+    height: 200px;
+    -webkit-transform: rotate(180deg);
+    transform: rotate(180deg);
+}
+
+ +

{{EmbedLiveSample('Multiple_animated_properties_example', 600, 300)}}

+ +

Quando os tamanhos dos valores das listas das propriedades são de tamanhos diferentes

+ +

Se alguma propriedade da lista de valores for menor que os outros, esse valor será repetido para que eles correspondam. Por exemplo:

+ +
div {
+  transition-property: opacity, left, top, height;
+  transition-duration: 3s, 5s;
+}
+
+ +

Isso é tratado como se fosse:

+ +
div {
+  transition-property: opacity, left, top, height;
+  transition-duration: 3s, 5s, 3s, 5s;
+}
+ +

Da mesma forma, se um valor da propriedade da lista, for maior que a {{cssxref("transition-property")}}, ela será truncada, então você terá o seguinte CSS:

+ +
div {
+  transition-property: opacity, left;
+  transition-duration: 3s, 5s, 2s, 1s;
+}
+ +

Isso pode ser interpretado como:

+ +
div {
+  transition-property: opacity, left;
+  transition-duration: 3s, 5s;
+}
+ +

Usando transições ao destacar menus

+ +

Um uso comum de css é para destacar os itens do menu, como hover quando o usúario passa o mouse sobre um elemento. É facíl fácil usar transições CSS para tornar o efeito mais atraente;

+ +

Antes de olharmos para os códigos, você poderia dar uma olhada nesse live demo (assumindo que seu browser suporte transições).

+ +

Primeiro, nós criamos o menu utilizando apenas HTML

+ +
<nav>
+  <a href="#">Home</a>
+  <a href="#">About</a>
+  <a href="#">Contact Us</a>
+  <a href="#">Links</a>
+</nav>
+ +

Em seguida, nós implementamos o CSS para implementar o visual e aparência do nosso menu. As partes relevantes são serão mostrada aqui:

+ +
a {
+  color: #fff;
+  background-color: #333;
+  transition: all 1s ease-out;
+}
+
+a:hover,
+a:focus {
+  color: #333;
+  background-color: #fff;
+}
+
+ +

Este CSS estabelece a aparência do menu, com as cores de fundo e texto mudando quando o o ocorre o evento de {{cssxref(":hover")}} e estado de {{cssxref(":focus")}}.

+ +

Exemplos JavaScript

+ +
+

Cuidados devem ser tomados ao usar uma transição imediatamente após:

+ +
    +
  • adding the element to the DOM using .appendChild()
  • +
  • removing an element's display: none; property.
  • +
+ +

This is treated as if the initial state had never occurred and the element was always in its final state. The easy way to overcome this limitation is to apply a window.setTimeout() of a handful of milliseconds before changing the CSS property you intend to transition to.

+
+ +

Using transitions to make JavaScript functionality smooth

+ +

Transitions are a great tool to make things look much smoother without having to do anything to your JavaScript functionality. Take the following example.

+ +
<p>Click anywhere to move the ball</p>
+<div id="foo"></div>
+
+ +

Using JavaScript you can make the effect of moving the ball to a certain position happen:

+ +
var f = document.getElementById('foo');
+document.addEventListener('click', function(ev){
+    f.style.transform = 'translateY('+(ev.clientY-25)+'px)';
+    f.style.transform += 'translateX('+(ev.clientX-25)+'px)';
+},false);
+
+ +

With CSS you can make it smooth without any extra effort. Simply add a transition to the element and any change will happen smoothly:

+ +
p {
+  padding-left: 60px;
+}
+
+#foo {
+  border-radius: 50px;
+  width: 50px;
+  height: 50px;
+  background: #c00;
+  position: absolute;
+  top: 0;
+  left: 0;
+  transition: transform 1s;
+}
+
+ +

Você pode brincar um pouco aqui: http://jsfiddle.net/9h261pzo/291/

+ +

Detectando o começo e a completude de uma transição

+ +

Você pode usar o evento {{event("transitionend")}} para detectar a uma animação que estava sendo executada chegou ao fim. Esse é o objeto {{domxref("TransitionEvent")}}, que possúi duas propriedades adicionadas além do objeto típico 

+ +
+
propertyName
+
A string indicando o nome da propriedade CSS cuja transição será completada
+
+ + + +
+
elapsedTime
+
A float indicating the number of seconds the transition had been running at the time the event fired. This value isn't affected by the value of {{cssxref("transition-delay")}}.
+
+ +

As usual, you can use the {{domxref("EventTarget.addEventListener", "addEventListener()")}} method to monitor for this event:

+ +
el.addEventListener("transitionend", updateTransition, true);
+
+ +

Você detecta o começo de uma transição usando {{event("transitionrun")}} (antes do delay) e {{event("transitionstart")}} (depois do delay):

+ +
el.addEventListener("transitionrun", signalStart, true);
+el.addEventListener("transitionstart", signalStart, true);
+ +
Observação: O evento transitionend não dispara se a transição é abortada antes de a transição ser concluída, porque o efeito é feito com {{cssxref("display")}}: none
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('CSS3 Transitions', '', '')}}{{Spec2('CSS3 Transitions')}}Definição Inícial
+ +

Veja Também

+ + diff --git a/files/pt-br/web/css/cursor/index.html b/files/pt-br/web/css/cursor/index.html new file mode 100644 index 0000000000..9a9c6af5af --- /dev/null +++ b/files/pt-br/web/css/cursor/index.html @@ -0,0 +1,529 @@ +--- +title: cursor +slug: Web/CSS/cursor +tags: + - CSS + - Cursor + - Referencia +translation_of: Web/CSS/cursor +--- +
{{CSSRef}}
+ +

Sumário

+ +

A propriedade CSS cursor especifica o cursor do mouse mostrado quando o ponteiro do mouse está sobre um elemento.

+ +

{{cssinfo}}

+ +

Sintaxe

+ +
/* Keywords */
+cursor: pointer;
+cursor: auto;
+
+/* Usando URL e cordenadas */
+cursor:  url(cursor1.png) 4 12, auto;
+cursor:  url(cursor2.png) 2 2, pointer;
+
+/* Valores globais */
+cursor: inherit;
+cursor: initial;
+cursor: unset;
+
+ +

Valores

+ +
+
<uri>
+
Uma url(...) ou uma lista de url(...) separada por vírgula, apontando para uma arquivo de imagem. Mais que uma {{cssxref("<uri>")}} pode ser fornecida como fallback, em caso de alguns tipos de imagem não ser suportado. Um fallback não-URL (um ou mais dos outros valores) deve estar no final da lista de fallbacks. Veja Usando valores URL para a propriedade cursor para mais detalhes.
+
<x> <y> {{experimental_inline}}
+
Coordenadas x e y opcionais. Dois números não-negativos, sem unidade e menores que 32.
+
Keyword values
+
+

Mova o mouse sobre os valores para testar:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CategoriaValor CSSActualDescrição
Generalauto O brower determina o cursor para ser exibido baseado no contexto atual.
defaultdefault.gifCursor padrão, tipicamente uma seta.
none Nenhum cursor é mostrado.
Links & statuscontext-menucontext-menu.pngUm menu de contexto está disponível sob o cursor.
+ Somente IE 10 e superior implementou esta propriedade no Windows: {{Bug("258960")}}.
helphelp.gifIndicando que ajuda está disponível.
pointerpointer.gifE.g. Usado quando pairando o cursor sobre links, tipicamente uma mão.
progressprogress.gifO programa está processando em segundo plano. mas o o usuário ainda pode interagir com a interface (diferente de wait).
waitwait.gifO programa está ocupado (às vezes uma ampulheta ou relógio).
Selectioncellcell.gifIndica que a célula pode ser selecionada.
crosshaircrosshair.gifCursor de cruz, normalmente usado para indicar seleção em uma imagem bitmap.
texttext.gifIndica que o texto pode ser selecionado, normalmente um I maiúsculo.
vertical-textvertical-text.gifIndica que o texto vertical text can be selected, normalmente um I maiúsculo virado de lado.
Drag and dropaliasalias.gifIndicating an alias or shortcut is to be created.
copycopy.gifIndica que algo será copiado.
movemove.gifO item sob o mouse pode ser movido.
no-dropno-drop.gifCursor showing that a drop is not allowed at the current location.
+ {{bug("275173")}} on Windows and Mac OS X, "no-drop is the same as not-allowed".
not-allowednot-allowed.gifCursor showing that something cannot be done.
Resize & scrollingall-scrollall-scroll.gifCursor showing that something can be scrolled in any direction (panned).
+ {{bug("275174")}} on Windows, "all-scroll is the same as move".
col-resizecol-resize.gifThe item/column can be resized horizontally. Often rendered as arrows pointing left and right with a vertical bar separating.
row-resizerow-resize.gifThe item/row can be resized vertically. Often rendered as arrows pointing up and down with a horizontal bar separating them.
n-resizeExample of a resize towards the top cursorSome edge is to be moved. For example, the se-resize cursor is used when the movement starts from the south-east corner of the box.
e-resizeExample of a resize towards the right cursor
s-resizeExample of a resize towards the bottom cursor
w-resizeExample of a resize towards the left cursor
ne-resizeExample of a resize towards the top-right corner cursor
nw-resizeExample of a resize towards the top-left corner cursor
se-resizeExample of a resize towards the bottom-right corner cursor
sw-resizeExample of a resize towards the bottom-left corner cursor
ew-resize3-resize.gifIndicates a bidirectional resize cursor.
ns-resize6-resize.gif
nesw-resize1-resize.gif
nwse-resize4-resize.gif
Zoomzoom-inzoom-in.gif +

Indicates that something can be zoomed (magnified) in or out.

+
zoom-outzoom-out.gif
Grabgrabgrab.gif +

Indicates that something can be grabbed (dragged to be moved).

+
grabbinggrabbing.gif
+
+
+ +

Sintaxe formal

+ +
{{csssyntax}}
+
+ +

Exemplos

+ +
.foo {
+  cursor: crosshair;
+}
+
+/* use velor prefixado se "zoom-in" não for suportado */
+.bar {
+  cursor: -webkit-zoom-in;
+  cursor: zoom-in;
+}
+
+/* valor padrão como fallback para url() deve ser fornecido (não funciona sem) */
+.baz {
+  cursor: url(hyper.cur), auto;
+}
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('CSS3 Basic UI', '#cursor', 'cursor')}}{{Spec2('CSS3 Basic UI')}}Adição de várias keywords e sintaxe de posicionamento para url().
{{SpecName('CSS2.1', 'ui.html#cursor-props', 'cursor')}}{{Spec2('CSS2.1')}}Definição inicial
+ +

Compatibilidade

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
auto, crosshair, default, move, text, wait, help,
+ n-resize, e-resize, s-resize, w-resize,
+ ne-resize, nw-resize, se-resize, sw-resize
1.01.04.0[1]7.01.2
pointer, progress1.01.06.07.01.2
url()1.01.5
+ 4.0[2]
6.0{{CompatUnknown}}3.0
Positioning syntax for url() values {{experimental_inline}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatVersionUnknown}}
not-allowed, no-drop, vertical-text, all-scroll,
+ col-resize, row-resize
1.01.56.010.63.0
alias, cell, copy,
+ ew-resize, ns-resize, nesw-resize, nwse-resize
1.01.510.010.63.0
context-menu1.0[3]1.5[3]10.010.63.0
none5.03.09.015.05.0
inherit1.01.08.09.01.2
zoom-in, zoom-out +

1.0 {{property_prefix("-webkit-")}}
+ 37

+
1.0 {{property_prefix("-moz-")}}
+ 24.0
{{CompatNo}}11.6
+ 15-23 {{property_prefix("-webkit-")}}
+ 24
3.0 {{property_prefix("-webkit-")}}
+ 9
grab, grabbing1.0 {{property_prefix("-webkit-")}}
+ 22.0 {{property_prefix("-webkit-")}}[4]
1.5 {{property_prefix("-moz-")}}
+ 27.0
{{CompatNo}}{{CompatVersionUnknown}}4.0 {{property_prefix("-webkit-")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
auto, crosshair, default, move, text, wait, help,
+ n-resize, e-resize, s-resize, w-resize,
+ ne-resize, nw-resize, se-resize, sw-resize
{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
pointer, progress{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
url(){{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Positioning syntax for url() values {{experimental_inline}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
not-allowed, no-drop, vertical-text, all-scroll,
+ col-resize, row-resize
{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
alias, cell, copy,
+ ew-resize, ns-resize, nesw-resize, nwse-resize
{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
context-menu{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
none{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
inherit{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
zoom-in, zoom-out{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
grab, grabbing{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] No IE11, quando cursor é aplicado em um elemento e este elemento está por baixo de um menu {{HTMLElement("select")}} aberto e o usuário paira sobre um item do menu {{HTMLElement("select")}} que está no sobre o elemento em questão, o cursor deste elemento será mostrado em vez do cursor do {{HTMLElement("select")}}. Veja IE bug 963961.

+ +

[2] Suporte para este foi adicionado no Mac OS X.

+ +

[3] Apenas suportado no Mac OS X e Linux.

+ +

[4] Suporte para isto foi adicionado no Windows.

+ +

Veja também

+ + diff --git a/files/pt-br/web/css/descendant_combinator/index.html b/files/pt-br/web/css/descendant_combinator/index.html new file mode 100644 index 0000000000..f77d910101 --- /dev/null +++ b/files/pt-br/web/css/descendant_combinator/index.html @@ -0,0 +1,108 @@ +--- +title: Descendant combinator +slug: Web/CSS/Descendant_combinator +tags: + - CSS + - Reference + - Selectors +translation_of: Web/CSS/Descendant_combinator +--- +
{{CSSRef("Selectors")}}
+ +

O combinador descendente - normalmente representado por um caractere de espaço simples ( ) - combina dois seletores para que os elementos correspondidos pelo segundo seletor sejam selecionados se eles tiverem um elemento ancestral (pai, pai ou mãe, pai ou mãe, etc.) correspondente ao primeiro seletor. Os seletores que utilizam um combinador descendente são chamados de seletores descendentes.

+ +
/* Listar itens descendentes da lista "my-things" */
+ul.my-things li {
+  margin: 2em;
+}
+ +

O combinador descendente é tecnicamente um ou mais caracteres de espaço em branco do {{Glossary ("CSS")}} - o caractere de espaço e/ou um dos quatro caracteres de controle:  retorno de carro (carriage return), Quebra de página ( form feed), nova linha e caracteres de tabulação entre dois seletores na ausência de outro combinador.  Além disso, os caracteres de espaço em branco dos quais o combinador é composto podem conter qualquer número de comentários CSS.

+ +

Sintaxe

+ +
selector1 selector2 {
+  /*  declarações de propriedade  */
+}
+ +

Exemplo

+ +

CSS

+ +
li {
+  list-style-type: disc;
+}
+
+li li {
+  list-style-type: circle;
+}
+
+ +

HTML

+ +
<ul>
+  <li>
+    <div>Item 1</div>
+    <ul>
+      <li>Subitem A</li>
+      <li>Subitem B</li>
+    </ul>
+  </li>
+  <li>
+    <div>Item 2</div>
+    <ul>
+      <li>Subitem A</li>
+      <li>Subitem B</li>
+    </ul>
+  </li>
+</ul>
+
+ +

Resultado

+ +

{{EmbedLiveSample("Example", "100%", 160)}}

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComment
{{SpecName("CSS4 Selectors", "#descendant-combinators", "descendant combinator")}}{{Spec2("CSS4 Selectors")}}
{{SpecName("CSS3 Selectors", "#descendant-combinators", "descendant combinator")}}{{Spec2("CSS3 Selectors")}}
{{SpecName("CSS2.1", "selector.html#descendant-selectors", "descendant selectors")}}{{Spec2("CSS2.1")}}
{{SpecName("CSS1", "#contextual-selectors", "contextual selectors")}}{{Spec2("CSS1")}}Initial definition
+ +

Compatibilidade dos Browser

+ + + +

{{Compat("css.selectors.descendant")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/css/display-box/index.html b/files/pt-br/web/css/display-box/index.html new file mode 100644 index 0000000000..7aec5790c6 --- /dev/null +++ b/files/pt-br/web/css/display-box/index.html @@ -0,0 +1,112 @@ +--- +title: +slug: Web/CSS/display-box +translation_of: Web/CSS/display-box +--- +
{{CSSRef}}
+ +

Essas palavras-chave definem se um elemento gera caixas de exibição.

+ +

Sintaxe

+ +
+
contents {{Experimental_Inline}}
+
Esses elementos não produzem uma caixa específica por si mesmos. Eles são substituídos por sua pseudo-caixa e suas caixas filho. Observe que a especificação CSS Display Level 3 define como o contents +

o valor deve afetar "elementos incomuns" - elementos que não são renderizados apenas pelos conceitos da caixa CSS, como elementos substituídos. Consulte o Apêndice B: Efeitos da exibição: conteúdo em Elementos incomuns para obter mais detalhes.

+ +

Devido a um erro nos navegadores, atualmente isso remove o elemento da árvore de acessibilidade - os leitores de tela não analisam o que está dentro. Consulte a seção Preocupações com acessibilidade abaixo para obter mais detalhes.

+
+
none
+
Desativa a exibição de um elemento para que não tenha efeito no layout (o documento é renderizado como se o elemento não existisse). Todos os elementos descendentes também têm a exibição desativada.
+ Para que um elemento ocupe o espaço que normalmente ocuparia, mas sem renderizar nada, use o {{CSSxRef("visibility")}} propriedade em vez disso.
+
+ +

Sintaxe formal

+ +
{{CSSSyntax}}
+ +

Exemplos

+ +

Neste primeiro exemplo, o parágrafo com uma classe de segredo é definido como display: none; a caixa e qualquer conteúdo agora não são renderizados.

+ +

display: none

+ +

HTML

+ +
+
<p>Visible text</p>
+<p class="secret">Invisible text</p>
+ +

CSS

+ +
p.secret {
+  display: none;
+}
+ +

Resultado

+ +

{{EmbedLiveSample("Hide_element", "100%", 60)}}

+
+ +
+

display: contents

+ +

Neste exemplo, o externo {{htmlelement("div")}} possui uma borda vermelha de 2 pixels e uma largura de 300 px. No entanto, também temdisplay: contents especificado, portanto, este <div> não será renderizado, a borda e a largura não serão mais aplicadas e o elemento filho será exibido como se o pai nunca tivesse existido.

+ +

HTML

+ +
<div class="outer">
+  <div>Inner div.</div>
+</div>
+
+ +

CSS

+ +
.outer {
+  border: 2px solid red;
+  width: 300px;
+  display: contents;
+}
+
+.outer > div {
+  border: 1px solid green;
+}
+
+ +

Resultado

+ +

{{EmbedLiveSample("Display_contents", 300, 60)}}

+
+ +

Preocupações com acessibilidade

+ +

As implementações atuais na maioria dos navegadores removerão da árvore de acessibilidade qualquer elemento com um display valor de contents. Isso fará com que o elemento - e em algumas versões do navegador, seus elementos descendentes - não sejam mais anunciados pela tecnologia de leitura de tela. Esse é um comportamento incorreto de acordo com a especificação CSSWG.

+ + + +

Compatibilidade do navegador

+ + + +

Support of contents

+ +

{{Compat("css.properties.display.contents", 10)}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/css/display-inside/index.html b/files/pt-br/web/css/display-inside/index.html new file mode 100644 index 0000000000..64c09da01a --- /dev/null +++ b/files/pt-br/web/css/display-inside/index.html @@ -0,0 +1,121 @@ +--- +title: +slug: Web/CSS/display-inside +translation_of: Web/CSS/display-inside +--- +
{{CSSRef}}
+ +

Essas palavras-chave especificam o interior do elemento{{CSSxRef("display")}} type, que define o tipo de contexto de formatação que apresenta seu conteúdo (supondo que seja um elemento não substituído). Essas palavras-chave são usadas como valores do display e pode ser usada para fins legados como uma única palavra-chave ou conforme definido na especificação do Nível 3, juntamente com um valor do {{CSSxRef("<display-outside>")}} palavras-chave.

+ +

Sintaxe

+ +

O <display-inside> O valor é definido usando uma palavra-chave da lista abaixo:

+ +
+
flow {{Experimental_Inline}}
+
O elemento expõe seu conteúdo usando o layout de fluxo (layout em bloco e em linha).
+ Se o seu tipo de exibição externo for +

inline ou run-in,

+ +

e estiver participando de um contexto de formatação em bloco ou em linha, gera uma caixa em linha. Caso contrário, ele gera uma caixa de contêiner de bloco.

+ +

Dependendo do valor de outras propriedades como

+ +

{{CSSxRef("position")}}, {{CSSxRef("float")}}, ou {{CSSxRef("overflow")}}) e se ele próprio participa de um contexto de formatação em bloco ou embutido, ele estabelece um novo contexto de formatação de bloco (BFC) para seu conteúdo ou integra seu conteúdo ao contexto de formatação pai.

+
+
flow-root {{Experimental_Inline}}
+
O elemento gera uma caixa de elemento de bloco que estabelece um novo contexto de formatação de bloco, definindo onde está a raiz da formatação.
+
table
+
Esses elementos se comportam como HTML{{HTMLElement("table")}} elementos. Ele define uma caixa no nível do bloco.
+
flex
+
O elemento se comporta como um elemento de bloco e expõe seu conteúdo de acordo com o modelo flexbox.
+
grid
+
O elemento se comporta como um elemento de bloco e expõe seu conteúdo de acordo com o modelo de grade.
+
ruby {{Experimental_Inline}}
+
O elemento se comporta como um elemento embutido e apresenta seu conteúdo de acordo com o modelo de formatação ruby. Ele se comporta como o HTML correspondente{{HTMLElement("ruby")}} elementos.
+
+ +
+

Nota: Navegadores que suportam a sintaxe de dois valores, encontrando apenas o valor interno, como quandodisplay: flex or display: grid especificado, definirá seu valor externo como block. Isso resultará no comportamento esperado; por exemplo, se você especificar um elemento a ser display: grid, você esperaria que a caixa criada no contêiner da grade fosse uma caixa no nível do bloco.

+
+ +

Sintaxe formal

+ +
{{CSSSyntax}}
+ +

Exemplo

+ +

Neste exemplo, a caixa pai foi fornecida display: flow-root e assim estabelece um novo BFC e contém o item flutuado.

+ +

HTML

+ +
<div class="box">
+  <div class="float">I am a floated box!</div>
+  <p>I am content inside the container.</p>
+</div>
+
+ +

CSS

+ +
.box {
+    background-color: rgb(224, 206, 247);
+    border: 5px solid rebeccapurple;
+    display: flow-root;
+}
+
+.float {
+    float: left;
+    width: 200px;
+    height: 150px;
+    background-color: white;
+    border:1px solid black;
+    padding: 10px;
+}
+ +

Resultado

+ +

{{EmbedLiveSample("Example", "100%", 180)}}

+ +

Compatibilidade do navegador

+ + + +

Suporte a vários valores de palavras-chave

+ +

{{Compat("css.properties.display.multi-keyword_values", 10)}}

+ +

Suporte de fluxo-raiz

+ +

{{Compat("css.properties.display.flow-root", 10)}}

+ +

Suporte de tabela

+ +

{{Compat("css.properties.display.table_values", 10)}}

+ +

Suporte de grade

+ +

{{Compat("css.properties.display.grid", 10)}}

+ +

Suporte de flex

+ +

{{Compat("css.properties.display.flex", 10)}}

+ +

Suporte de ruby

+ +

{{Compat("css.properties.display.ruby_values", 10)}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/css/display-internal/index.html b/files/pt-br/web/css/display-internal/index.html new file mode 100644 index 0000000000..edd5179e5f --- /dev/null +++ b/files/pt-br/web/css/display-internal/index.html @@ -0,0 +1,69 @@ +--- +title: +slug: Web/CSS/display-internal +translation_of: Web/CSS/display-internal +--- +
{{CSSRef}}
+ +

Alguns modelos de layout, como table e ruby Alguns modelos de layout, como possuem uma estrutura interna complexa, com várias funções diferentes que seus filhos e descendentes podem preencher. Esta página define os valores de exibição "internos", que só têm significado nesse modo de layout específico.

+ +

Sintaxe

+ +

Salvo indicação em contrário, o tipo de exibição interno e o tipo de exibição externo de elementos que usam esses valores de exibição são definidos para a palavra-chave fornecida.

+ +
+
table-row-group
+
Esses elementos se comportam como{{HTMLElement("tbody")}} HTML elementos.
+
table-header-group
+
Esses elementos se comportam como{{HTMLElement("thead")}} HTML elementos.
+
table-footer-group
+
Esses elementos se comportam como {{HTMLElement("tfoot")}} HTML elementos.
+
table-row
+
Esses elementos se comportam como {{HTMLElement("tr")}} HTML elementos.
+
table-cell
+
Esses elementos se comportam como {{HTMLElement("td")}} HTML elementos.
+
table-column-group
+
Esses elementos se comportam como{{HTMLElement("colgroup")}} HTML elementos.
+
table-column
+
Esses elementos se comportam como {{HTMLElement("col")}} HTML elementos.
+
table-caption
+
Esses elementos se comportam como{{HTMLElement("caption")}} HTML elementos.
+
ruby-base {{Experimental_Inline}}
+
Esses elementos se comportam como{{HTMLElement("rb")}} HTML elementos.
+
ruby-text {{Experimental_Inline}}
+
Esses elementos se comportam como {{HTMLElement("rt")}} HTML elementos.
+
ruby-base-container {{Experimental_Inline}}
+
Esses elementos se comportam como{{HTMLElement("rbc")}} HTML elementos gerado como caixas anônimas.
+
ruby-text-container {{Experimental_Inline}}
+
Esses elementos se comportam como {{HTMLElement("rtc")}} HTML elementos.
+
+ +

Compatibilidade do navegador

+ + + +

Suporte de valores de tabela

+ +

table, table-cell, table-column, table-column-group, table-footer-group, table-header-group, table-row, and table-row-group

+ +

{{Compat("css.properties.display.table_values", 10)}}

+ +

Suporte de valores de rubi

+ +

ruby, ruby-base, ruby-base-container, ruby-text, and ruby-text-container

+ +

{{Compat("css.properties.display.ruby_values", 10)}}

+ +

Veja também

+ +
    +
  • {{CSSxRef("display")}} +
      +
    • {{CSSxRef("<display-outside>")}}
    • +
    • {{CSSxRef("<display-inside>")}}
    • +
    • {{CSSxRef("<display-listitem>")}}
    • +
    • {{CSSxRef("<display-box>")}}
    • +
    • {{CSSxRef("<display-legacy>")}}
    • +
    +
  • +
diff --git a/files/pt-br/web/css/display-legacy/index.html b/files/pt-br/web/css/display-legacy/index.html new file mode 100644 index 0000000000..c4bf7e06c2 --- /dev/null +++ b/files/pt-br/web/css/display-legacy/index.html @@ -0,0 +1,102 @@ +--- +title: +slug: Web/CSS/display-legacy +translation_of: Web/CSS/display-legacy +--- +
{{CSSRef}}
+ +

O CSS 2 usou uma sintaxe de palavra-chave única para o display , exigindo palavras-chave separadas para variantes em nível de bloco e em linha do mesmo modo de layout. Esta página detalha esses valores.

+ +

Sintaxe

+ +
+
inline-block
+
+

O elemento gera uma caixa de elemento de bloco que fluirá com o conteúdo circundante, como se fosse uma única caixa embutida (se comportando como um elemento substituído).

+ +

É equivalente a inline flow-root.

+
+
inline-table
+
O inline-table O valor não possui um mapeamento direto em HTML. Ele se comporta como um HTML{{HTMLElement("table")}} elemento, mas como uma caixa embutida, em vez de uma caixa no nível do bloco. Dentro da caixa da tabela há um contexto em nível de bloco.
+
+ É equivalente a inline table.
+
inline-flex
+
O elemento se comporta como um elemento embutido e apresenta seu conteúdo de acordo com o modelo flexbox.
+
+ É equivalente a inline flex.
+
inline-grid
+
O elemento se comporta como um elemento embutido e apresenta seu conteúdo de acordo com o modelo de grade.
+
+ É equivalente a inline grid.
+
+ +

Sintaxe formal

+ +
{{CSSSyntax}}
+ +

Exemplo

+ +

No exemplo abaixo, estamos criando um contêiner flex inline com a palavra-chave herdada inline-flex.

+ +
+

HTML

+ +
<div class="container">
+  <div>Flex Item</div>
+  <div>Flex Item</div>
+</div>
+
+Not a flex item
+
+ +

CSS

+ +
.container {
+  display: inline-flex;
+}
+
+ +

Result

+ +

{{EmbedLiveSample("Example", 300, 150)}}

+
+ +

Na nova sintaxe, o contêiner flex inline seria criado usando dois valores, inline para o tipo de exibição externo e flex para o tipo de exibição interno.

+ +
.container {
+  display: inline flex;
+}
+ +

Compatibilidade do navegador

+ + + +

Suporte deinline-block

+ +

{{Compat("css.properties.display.inline-block", 10)}}

+ +

Suporte deinline-table

+ +

{{Compat("css.properties.display.inline-table", 10)}}

+ +

Suporte deinline-flex

+ +

{{Compat("css.properties.display.inline-flex", 10)}}

+ +

Suporte deinline-grid

+ +

{{Compat("css.properties.display.inline-grid", 10)}}

+ +

Veja também

+ +
    +
  • {{CSSxRef("display")}} +
      +
    • {{CSSxRef("<display-outside>")}}
    • +
    • {{CSSxRef("<display-inside>")}}
    • +
    • {{CSSxRef("<display-listitem>")}}
    • +
    • {{CSSxRef("<display-internal>")}}
    • +
    • {{CSSxRef("<display-box>")}}
    • +
    +
  • +
diff --git a/files/pt-br/web/css/display-listitem/index.html b/files/pt-br/web/css/display-listitem/index.html new file mode 100644 index 0000000000..6d45a8e82d --- /dev/null +++ b/files/pt-br/web/css/display-listitem/index.html @@ -0,0 +1,63 @@ +--- +title: +slug: Web/CSS/display-listitem +translation_of: Web/CSS/display-listitem +--- +
{{CSSRef}}
+ +

O list-item palavra-chave faz com que o elemento gere um::marker pseudoelemento com o conteúdo especificado por sua {{CSSxRef("list-style")}} propriedades (por exemplo, um marcador) junto com uma caixa principal do tipo especificado para seu próprio conteúdo.

+ +

Sintaxe

+ +

Um valor único de list-item fará com que o elemento se comporte como um item da lista. Isso pode ser usado junto com{{CSSxRef("list-style-type")}} e {{CSSxRef("list-style-position")}}.

+ +

list-item também pode ser combinado com qualquer {{CSSxRef("<display-outside>")}} palavra-chave e o flow ou flow-root {{CSSxRef("<display-inside>")}} palavras-chave.

+ +
+

Nota: Nos navegadores que suportam a sintaxe de dois valores, se nenhum valor interno for especificado, o padrão seráflow. Se nenhum valor externo for especificado, a caixa principal terá um tipo de exibição externo deblock.

+
+ +

Sintaxe formal

+ +
{{CSSSyntax}}
+ +

Exemplo

+ +

HTML

+ +
<div class="fake-list">I will display as a list item</div>
+
+ +

CSS

+ +
.fake-list {
+  display: list-item;
+  list-style-position: inside;
+}
+
+ +

Resultado

+ +

{{EmbedLiveSample("Example", "100%", 150)}}

+ +

Compatibilidade do navegador

+ + + +

Suporte delist-item

+ +

{{Compat("css.properties.display.list-item", 10)}}

+ +

Veja também

+ +
    +
  • {{CSSxRef("display")}} +
      +
    • {{CSSxRef("<display-outside>")}}
    • +
    • {{CSSxRef("<display-inside>")}}
    • +
    • {{CSSxRef("<display-internal>")}}
    • +
    • {{CSSxRef("<display-box>")}}
    • +
    • {{CSSxRef("<display-legacy>")}}
    • +
    +
  • +
diff --git a/files/pt-br/web/css/display-outside/index.html b/files/pt-br/web/css/display-outside/index.html new file mode 100644 index 0000000000..84b0676bcd --- /dev/null +++ b/files/pt-br/web/css/display-outside/index.html @@ -0,0 +1,77 @@ +--- +title: +slug: Web/CSS/display-outside +translation_of: Web/CSS/display-outside +--- +
{{CSSRef}}
+ +

O <display-outside> as palavras-chave especificam a parte externa do elemento {{CSSxRef("display")}} type, que é essencialmente seu papel no layout de fluxo. Essas palavras-chave são usadas como valores do display e pode ser usada para fins legados como uma única palavra-chave ou conforme definido na especificação do Nível 3, juntamente com um valor do {{CSSxRef("<display-inside>")}} palavras-chave.

+ +

Sintaxe

+ +

O <display-outside> O valor é definido usando uma palavra-chave da lista abaixo:

+ +

Valor

+ +
+
block
+
O elemento gera uma caixa de elemento de bloco, gerando quebras de linha antes e depois do elemento, quando no fluxo normal.
+
inline
+
O elemento gera uma ou mais caixas de elementos embutidos que não geram quebras de linha antes ou depois de si mesmas. No fluxo normal, o próximo elemento estará na mesma linha se houver espaço
+
run-in {{Experimental_Inline}}
+
O elemento gera uma caixa de introdução. Se o irmão adjacente do elemento definido comodisplay: run-in box é uma caixa de bloco, o run-in box se torna a primeira caixa embutida da caixa de bloco a seguir.
+
Os elementos de entrada funcionam como linhas ou blocos, dependendo dos elementos circundantes. Ou seja: Se a caixa de introdução contém uma caixa de bloco, o mesmo que bloco. Se uma caixa de bloco segue a caixa de introdução, a caixa de introdução torna-se a primeira caixa embutida da caixa de bloco. Se uma caixa embutida se seguir, a caixa de introdução se tornará uma caixa de bloco.
+  
+  
+
+ +
+

Nota: Navegadores que suportam a sintaxe de dois valores, encontrando apenas o valor externo, como quandodisplay: block ou display: inline especificado, definirá o valor interno comoflow. Isso resultará no comportamento esperado; por exemplo, se você especificar um elemento a ser bloco, seria de esperar que os filhos desse elemento participassem do layout de fluxo normal em bloco e em linha.

+
+ +

Sintaxe formal

+ +
{{CSSSyntax}}
+
+ +

Exemplo

+ +

No exemplo a seguir, os elementos de extensão (normalmente exibidos como elementos embutidos) são definidos como display: block e, assim, divida em novas linhas e expanda para preencher seu contêiner na dimensão embutida.

+ +

HTML

+ +
<span>span 1</span>
+<span>span 2</span>
+ +

CSS

+ +
span {
+    display: block;
+    border: 1px solid rebeccapurple;
+}
+ +

Resultado

+ +

{{EmbedLiveSample("Example", 300, 60)}}

+ +

Compatibilidade do navegador

+ + + +

{{Compat("css.properties.display.display-outside", 10)}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/css/display/index.html b/files/pt-br/web/css/display/index.html new file mode 100644 index 0000000000..1b97bc92fe --- /dev/null +++ b/files/pt-br/web/css/display/index.html @@ -0,0 +1,355 @@ +--- +title: display +slug: Web/CSS/display +tags: + - CSS + - Posicionamento CSS + - Propriedades CSS +translation_of: Web/CSS/display +--- +
{{CSSRef}}
+ +

Resumo

+ +

A propriedade CSS  display especifica o tipo de caixa de renderização usada por um elemento. No HTML, os valores padrões da propriedade  display são feitas a partir do comportamento descrito nas especificações HTML ou da folha de estilo padrão do navegador/usuário. O valor padrão em XML é inline.

+ +

Além dos muitos tipos diferentes de exibição de caixa, o valor  none permite desativar a exibição de um elemento; quando você usa none, todos os elementos descendentes também tem a sua exibição desativada. O documento é renderizado como se o elemento não existisse na árvore do documento.

+ +

{{cssinfo}}

+ +

Sintaxe

+ +
Sintaxe formal: {{csssyntax("display")}}
+
+ +
display: none
+
+display: inline
+display: block
+display: list-item
+display: inline-block
+display: inline-table
+display: table
+display: table-cell
+display: table-column
+display: table-column-group
+display: table-footer-group
+display: table-header-group
+display: table-row
+display: table-row-group
+display: flex
+display: inline-flex
+display: grid
+display: inline-grid
+display: run-in
+
+display: inherit
+
+ +

Valores

+ +

display-value

+ +
+
É a palavra-chave para definir tipo de renderização que será usada no elemento. Os valores possiveis e seus significados são: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Value setValueDescription
Valores Básicos (CSS 1)none +

Desabilita a exibição do elemento (sem afetar o layout); todos os elementos filhos também tem sua exibição desabilitada. O documento é renderizado como se o elemento não existisse.

+ +

Para renderizar as dimensões de caixa do elemento, tendo ainda seu conteúdo "invisivel", veja a propriedade {{cssxref("visibility")}}.

+
inlineO elemento gera uma ou mais caixas de elementos inline.
blockO elemento gera uma caixa de elemento de bloco.
list-itemO elemento gera uma caixa de bloqueio para o conteúdo e uma caixa embutida de item de lista separada.
Valores estendidos(CSS 2.1)inline-blockO elemento gera uma caixa de elemento de bloco que fluirá com o conteúdo circundante, como se fosse uma única caixa embutida (se comportando como um elemento substituído)
Valores do modelo de tabela(CSS 2.1)inline-tableO inline-table O valor não possui um mapeamento direto em HTML. Se comporta como um{{HTMLElement("table")}} HTML elemento, mas como uma caixa embutida, em vez de uma caixa no nível do bloco. Dentro da caixa da tabela há um contexto em nível de bloco.
tableComporta-se como o{{HTMLElement("table")}} HTML elemento. Ele define uma caixa no nível do bloco.
table-captionComporta-se como o{{HTMLElement("caption")}} HTML elemento.
table-cellComporta-se como o {{HTMLElement("td")}} HTML elemento
table-columnEsses elementos se comportam como o correspondente {{HTMLElement("col")}} HTML elementos.
table-column-groupEsses elementos se comportam como o correspondente{{HTMLElement("colgroup")}} HTML elementos.
table-footer-groupEsses elementos se comportam como o correspondente {{HTMLElement("tfoot")}} HTML elementos
table-header-groupEsses elementos se comportam como o correspondente{{HTMLElement("thead")}} HTML elementos
table-rowComporta-se como o {{HTMLElement("tr")}} HTML elemento
table-row-groupEsses elementos se comportam como o correspondente {{HTMLElement("tbody")}} HTML elementos
Valores do modelo Flexbox (CSS3)flexO elemento se comporta como um elemento de bloco e apresenta seu conteúdo de acordo com o modelo flexbox.
inline-flexO elemento se comporta como um elemento embutido e apresenta seu conteúdo de acordo com o modelo flexbox.
Valores do modelo de caixa de grade (CSS3) {{experimental_inline}}grid +

O elemento se comporta como um elemento de bloco e apresenta seu conteúdo de acordo com o modelo de grade.

+ +
Como isso é experimental, a maioria dos navegadores não suporta. Preste atenção especialmente que -moz-grid não é a versão prefixada disso, mas um modelo de layout XUL que não deve ser usado em um site.
+
inline-gridO elemento se comporta como um elemento embutido e apresenta seu conteúdo de acordo com o modelo de grade.
Valores experimentais {{experimental_inline}}run-in +
    +
  • Se a caixa de entrada contiver uma caixa de bloco, o mesmo que bloco.
  • +
  • Se uma caixa de bloco segue a caixa de introdução, a caixa de introdução torna-se a primeira caixa embutida da caixa de bloco.
  • +
  • Se uma caixa embutida se seguir, a caixa de introdução se tornará uma caixa de bloco.
  • +
+
+
+
+ +

Exemplos

+ +

Ver exemplos ao vivo

+ +
p.secret  { display: none }
+<p style="display:none"> invisible text </p>
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Box', '#display', 'display')}}{{Spec2('CSS3 Box')}}Adicionado o run-in valor.
{{SpecName('CSS3 Grid', '#grid-declaration0', 'display')}}{{Spec2('CSS3 Grid')}}Adicionado os valores do modelo da caixa de grade.
{{SpecName('CSS3 Flexbox', '#flex-containers', 'display')}}{{Spec2('CSS3 Flexbox')}}Adicionado os valores do modelo de caixa flexível.
{{SpecName('CSS2.1', 'visuren.html#display-prop', 'display')}}{{Spec2('CSS2.1')}}Foram adicionados os valores do modelo de tabela e inline-block.
{{SpecName('CSS1', '#display', 'display')}}{{Spec2('CSS1')}}Valores básicos:none, block, inline, e list-item.
+ +

Navegadores compatíveis 

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
none, inline e block1.01.0 (1.0)4.07.01.0 (85)
inline-block1.03.0 (1.9)5.5 (-7.0)
+ apenas elementos inline naturais
7.01.0 (85)
list-item1.01.0 (1.0)6.07.01.0 (85)
run-in {{experimental_inline}}1.0
+ Não antes dos elementos inline
{{CompatNo}}8.07.01.0 (85)
+ Não antes dos elementos inline
+

4.0

+ +

Removido em 32

+
5.0 (532.5)
inline-table1.03.0 (1.9)8.07.01.0 (85)
table, table-cell, table-column, table-colgroup, table-header-group, table-row-group, table-footer-group, table-row, and table-caption1.01.0 (1.0)8.07.01.0 (85)
flex21.0{{property_prefix("-webkit")}}{{CompatGeckoDesktop("18.0")}}(behind a pref) [1]{{CompatNo}}12.50{{CompatNo}}
inline-flex21.0{{property_prefix("-webkit")}}{{CompatGeckoDesktop("18.0")}}(behind a pref) [1]{{CompatNo}}12.50{{CompatNo}}
grid {{experimental_inline}}{{CompatUnknown}}{{CompatNo}}10.0{{property_prefix("-ms")}}{{CompatUnknown}}{{CompatUnknown}}
inline-grid {{experimental_inline}}{{CompatUnknown}}{{CompatNo}}10.0{{property_prefix("-ms")}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Suporte básico{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Para ativar o suporte ao flexbox, no Firefox 18 e 19, o usuário precisa alterar a preferência about: config "layout.css.flexbox.enabled" para true. O flexbox de várias linhas é suportado desde Firefox 28.

+ +

Veja mais

+ +
    +
  • {{Cssxref("visibility")}}, {{Cssxref("float")}}, {{Cssxref("position")}}
  • +
diff --git a/files/pt-br/web/css/element()/index.html b/files/pt-br/web/css/element()/index.html new file mode 100644 index 0000000000..f52f5eb6e7 --- /dev/null +++ b/files/pt-br/web/css/element()/index.html @@ -0,0 +1,101 @@ +--- +title: element +slug: Web/CSS/element() +tags: + - Background + - CSS + - CSS4-images + - Função CSS + - Layout + - Web +translation_of: Web/CSS/element() +--- +
{{CSSRef}}{{SeeCompatTable}}
+ +

A função CSS element() define uma {{cssxref("<image>")}} gerada de um elemento HTML qualquer. Essa imagem é dinamica, significando que se o elemento HTML for mudado, a propriedade CSS usando este valor será atualizada automaticamente.

+ +

Um cenario particularmente util para usar esta função seria colocar uma imagem em um elemento {{HTMLElement("canvas")}}, e então usar-lo como um background.

+ +

Em navegadores Gecko, você pode usar o metodo não padronizado {{domxref("document.mozSetImageElement()")}} para mudar o elemento sendo usado como background por um elemento de background selecionado por CSS.

+ +

Sintaxe

+ +
element( id )
+ +

Onde:

+ +
+
id
+
É o ID de um elemento para usar como background, especificado usando o atributo HTML #id no elemento.
+
+ +

Exemplos

+ +

Esses exemplos podem ser vistos em tempo real em versões do Firefox que suportam -moz-element().

+ +

Um exemplo de alguma maneira real

+ +

Esse exemplo usa uma {{HTMLElement("div")}} escondida como background. O elemento de background tem um gradiente, mas tambem um texto que é usado como parte do background.

+ +
<div style="width:400px; height:400px; background:-moz-element(#myBackground1) no-repeat;">
+  <p>This box uses the element with the #myBackground1 ID as its background!</p>
+</div>
+
+<div style="overflow:hidden; height:0;">
+  <div id="myBackground1" style="width:1024px; height:1024px; background-image: linear-gradient(to right, red, orange, yellow, white);">
+  <p style="transform-origin:0 0; transform: rotate(45deg); color:white;">This text is part of the background. Cool, huh?</p>
+  </div>
+</div>
+ +

A {{HTMLElement("div")}} com ID "myBackground1" é usada como background, mantendo o paragrafo "This box uses the element with the #myBackground1 ID as its background!".

+ +

example1.png

+ +

Um exemplo ainda mais bizarro

+ +

Esse exemplo usa um elemento {{HTMLElement("button")}} se repetindo como background. Isso mostra que você pode usar qualquer elemento como background, mas não mostra necessariamente boas praticas de design.

+ +
<div style="width:400px; height:100px; background:-moz-element(#myBackground2);">
+</div>
+
+<div style="overflow:hidden; height:0;">
+  <button id="myBackground2" type="button">Evil button!</button>
+</div>
+
+ +

example2.png

+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoEstatusComentário
{{SpecName('CSS4 Images', '#element-notation', 'Using Elements as Images: the element() notation')}}{{Spec2('CSS4 Images')}}Actualmente adiado para o CSS4.
+ +

Compatibilidade dos navegadores

+ +

 

+ + + +

{{Compat("css.types.image.element")}}

+ +

 

+ +

Veja tambem

+ +
    +
  • {{domxref("document.mozSetImageElement()")}}
  • +
diff --git a/files/pt-br/web/css/elemento_substituido/index.html b/files/pt-br/web/css/elemento_substituido/index.html new file mode 100644 index 0000000000..22ba1b8ad0 --- /dev/null +++ b/files/pt-br/web/css/elemento_substituido/index.html @@ -0,0 +1,40 @@ +--- +title: Elemento substituído +slug: Web/CSS/Elemento_substituido +translation_of: Web/CSS/Replaced_element +--- +
{{CSSRef()}}
+ +

Sumario

+ +

In CSS, a replaced element is an element whose representation is outside the scope of CSS. These are a type of external object whose representation is independent of the CSS. Typical replaced elements are:

+ +
    +
  • {{HTMLElement("iframe")}}
  • +
  • {{HTMLElement("video")}}
  • +
  • {{HTMLElement("embed")}}
  • +
  • {{HTMLElement("img")}}
  • +
+ +

Some elements are treated as replaced elements only in specific cases:

+ +
    +
  • {{HTMLElement("audio")}}
  • +
  • {{HTMLElement("canvas")}}
  • +
  • {{HTMLElement("object")}}
  • +
  • {{HTMLElement("applet")}}
  • +
+ +

The only form control that is also a replaced element is {{HTMLElement("input")}} of the image type. All other form controls are non-replaced elements.

+ +

Objects inserted using the CSS {{cssxref("content")}} properties are anonymous replaced elements.

+ +

CSS handles replaced elements specifically in some cases, like when calculating margins and some auto values.

+ +

Note that some replaced elements, but not all, have intrinsic dimensions or a defined baseline, which is used by some CSS properties like {{cssxref("vertical-align")}}.

+ +

Veja também

+ +
    +
  • {{CSS_key_concepts()}}
  • +
diff --git a/files/pt-br/web/css/env()/index.html b/files/pt-br/web/css/env()/index.html new file mode 100644 index 0000000000..113a0b2f84 --- /dev/null +++ b/files/pt-br/web/css/env()/index.html @@ -0,0 +1,134 @@ +--- +title: env() +slug: Web/CSS/env() +tags: + - CSS + - CSS Function + - CSS Variables + - Draft + - Reference + - Variables + - env + - env() +translation_of: Web/CSS/env() +--- +
{{CSSRef}}
+ +

A função CSS env() pode ser usada para inserir o valor de uma variável de ambiente definida pelo agente do usuário em seu CSS, de uma maneira semelhante à função {{cssxref("var")}} e propriedades personalizadas. A diferença é que, além de serem definidas pelo agente do usuário em vez de serem definidas pelo usuário, as variáveis de ambiente têm escopo global para um documento, enquanto as propriedades personalizadas têm um escopo para o(s) elemento(s) no(s) qual(is) é/são declarado(s).

+ +
body {
+  padding:
+    env(safe-area-inset-top, 20px)
+    env(safe-area-inset-right, 20px)
+    env(safe-area-inset-bottom, 20px)
+    env(safe-area-inset-left, 20px);
+}
+ +

Além disso, ao contrário das propriedades personalizadas, que não podem ser usadas fora do escopo das declarações, a função env() pode ser usada em qualquer parte do valor de uma propriedade ou em qualquer parte de um descriptor (por exemplo, regras Media). À medida que a especificação evolui, essa também pode ser usada em outros lugares, como em seletores.

+ +

Originalmente fornecido pelo navegador iOS para permitir que os desenvolvedores coloquem seu conteúdo em uma safe area (área segura) na janela de visualização, os valores de safe-area-inset-* definidos na especificação podem ser usados para ajudar a garantir que o conteúdo seja visível até mesmo para usuários que usam uma tela não retangular.

+ +

Sintaxe

+ +
/* Usando os quatro valores de inserção safe area sem valores de fallback */
+env(safe-area-inset-top);
+env(safe-area-inset-right);
+env(safe-area-inset-bottom);
+env(safe-area-inset-left);
+
+/* Usando-os com valores de fallback */
+env(safe-area-inset-top, 20px);
+env(safe-area-inset-right, 1em);
+env(safe-area-inset-bottom, 0.5vh);
+env(safe-area-inset-left, 1.4rem);
+
+ +

Valores

+ +
+
safe-area-inset-topsafe-area-inset-rightsafe-area-inset-bottom, safe-area-inset-left
+
As variáveis safe-area-inset-* são quatro variáveis de ambiente que definem um retângulo por seus valores de inserção: top, right, bottom e left a partir da borda da janela de visualização, no qual é seguro colocar o conteúdo sem o risco de ser cortado pela forma de um visor não retangular. Para janelas de visualização retangulares, como o monitor de um laptop comum, seu valor é igual a zero. Para telas não retangulares - como um visor de um relógio redondo - os quatro valores definidos pelo agente do usuário formam um retângulo de modo que todo o conteúdo dentro do retângulo seja visível.
+
+ +
+

Nota: Ao contrário de outras propriedades CSS, os nomes de propriedades definidos pelo agente do usuário fazem distinção entre maiúsculas e minúsculas.

+
+ +

Sintaxe formal

+ +
{{cssSyntax}}
+ +

Exemplos

+ +

O exemplo abaixo faz uso do segundo parâmetro opcional de env(), que permite fornecer um valor de fallback caso a variável de ambiente não esteja disponível.

+ +
<p>
+ Se a função <code>env()</code> é suportada em seu navegador,
+ o texto deste parágrafo deverá estar na borda <i>top</i>, <i>right</i> e <i>bottom</i>,
+ ter 50px de preenchimento entre a borda e o texto. O CSS é equivalente
+ ao preenchimento: <code>padding: 0 0 0 50px</code>,
+ porque, ao contrário de outras propriedades CSS, os nomes de
+ propriedades do agente do usuário diferenciam letras maiúsculas de
+ minúsculas.
+</p>
+ +
p {
+  width: 300px;
+  border: 2px solid red;
+  padding:
+    env(safe-area-inset-top, 50px)
+    env(safe-area-inset-right, 50px)
+    env(safe-area-inset-bottom, 50px)
+    env(SAFE-AREA-INSET-LEFT, 50px);
+}
+ +

{{EmbedLiveSample("Exemplos")}}

+ +

Exemplo com valores

+ +
padding: env(safe-area-inset-bottom, 50px); /* zero para todos agentes do usuário que são retangulares*/
+padding: env(Safe-area-inset-bottom, 50px); /* 50px porque as propriedades do agente do usuário diferenciam maiúsculas de minúsculas */
+padding: env(x, 50px 20px); /* como se estivesse preenchendo: '50px 20px' que foram definidos, porque x não é uma variável de ambiente válida */
+padding: env(x, 50px, 20px); /* ignorado '50px, 20px' porque não é um valor de preenchimento válido e x não é uma variável de ambiente válida */
+
+ +

A sintaxe fallback, como de propriedades customizadas, permite vírgulas. Mas se o valor da propriedade não suportar vírgulas, o valor não é válido.

+ +
+

Nota: As propriedades do agente do usuário não são redefinidas pela propriedade all.

+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName("CSS3 Environment Variables", "#env-function", "env()")}}{{Spec2("CSS3 Environment Variables")}}Definição inicial.
+ +

Compatibilidade entre navegadores

+ + + +

{{Compat("css.properties.custom-property.env")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/css/filter-function/grayscale()/index.html b/files/pt-br/web/css/filter-function/grayscale()/index.html new file mode 100644 index 0000000000..b495a0dbbf --- /dev/null +++ b/files/pt-br/web/css/filter-function/grayscale()/index.html @@ -0,0 +1,39 @@ +--- +title: grayscale() +slug: Web/CSS/filter-function/grayscale() +tags: + - CSS + - Efeito filtro + - Filtros + - Função CSS + - Referencia +translation_of: Web/CSS/filter-function/grayscale() +--- +
{{cssref}}
+ +

grayscale() é uma função do CSS que modifica a imagem adicionada para as cores branco e preto . Esse resultado é um efeito "filtro". {{cssxref("<filter-function>")}}.

+ +
{{EmbedInteractiveExample("pages/css/function-grayscale.html")}}
+ + + +

Sintaxe

+ +
grayscale(quantidade)
+ +

Parâmetros

+ +
+
quantidade
+
A quantia da conversão é especificada em {{cssxref ("<number>")}} (número) ou {{cssxref ("<percentage>")}} (porcentagem). Um valor de 100% indica que a cor está compeltamente dentro da escala de cinza. Um valor de 0% não altera as cores da imagem, que permanecerá igual a original. Valores entre 0% e 100% são multiplicadores lineares no efeito cinza, modificando a escala de cores conforme a quantidade determinada. A quantia em número é equivalente a em porcentagem.
+
+ +
grayscale(0)     /* Não afeta a imagem */
+grayscale(.7)    /* .7 => 70% de branco&preto */
+grayscale(100%)  /* Completamente em branco&preto */
+ +

Veja também 

+ +
    +
  • {{cssxref("<filter-function>")}}
  • +
diff --git a/files/pt-br/web/css/filter-function/index.html b/files/pt-br/web/css/filter-function/index.html new file mode 100644 index 0000000000..e07f2f87a1 --- /dev/null +++ b/files/pt-br/web/css/filter-function/index.html @@ -0,0 +1,68 @@ +--- +title: +slug: Web/CSS/filter-function +tags: + - CSS + - CSS Data Type + - Filter Effects + - NeedsCompatTable + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/CSS/filter-function +--- +
{{cssref}}
+ +

The <filter-function> CSS data type represents a graphical effect that can change the appearance of an input image. It is used in the {{cssxref("filter")}} and {{cssxref("backdrop-filter")}} properties.

+ +

Syntax

+ +

The <filter-function> data type is specified using one of the filter functions listed below. Each function requires an argument which, if invalid, results in no filter being applied.

+ +
+
blur()
+
Blurs the image.
+
brightness()
+
Makes the image brighter or darker.
+
contrast()
+
Increases or decreases the image's contrast.
+
drop-shadow()
+
Applies a drop shadow behind the image.
+
grayscale()
+
Converts the image to grayscale.
+
hue-rotate()
+
Changes the overall hue of the image.
+
invert()
+
Inverts the colors of the image.
+
opacity()
+
Makes the image transparent.
+
saturate()
+
Super-saturates or desaturates the input image.
+
sepia()
+
Converts the image to sepia.
+
+ +

Specification

+ + + + + + + + + + + + + + + + +
SpecificationStatusComments
{{ SpecName('Filters 1.0', '#typedef-filter-function', '<filter-function>') }}{{ Spec2('Filters 1.0') }}Initial definition.
+ +

See also

+ +
    +
  • Properties that use this data type: {{cssxref("filter")}} and {{cssxref("backdrop-filter")}}
  • +
diff --git a/files/pt-br/web/css/filter-function/opacity()/index.html b/files/pt-br/web/css/filter-function/opacity()/index.html new file mode 100644 index 0000000000..8e41945429 --- /dev/null +++ b/files/pt-br/web/css/filter-function/opacity()/index.html @@ -0,0 +1,40 @@ +--- +title: opacity() +slug: Web/CSS/filter-function/opacity() +tags: + - Efeitos de Filtro + - Função CSS + - Referencia +translation_of: Web/CSS/filter-function/opacity() +--- +
{{cssref}}
+ +

A função CSS opacity() aplica transparência às amostras na imagem inputada. Seu resultado é uma {{cssxref("<filter-function>")}}.

+ +
+

Nota: Essa função é similar à propriedade {{Cssxref("opacity")}} mais estabelecida. A diferença é que com filtros, alguns browsers fornecem aceleração de hardware para uma melhor performance.

+
+ +

Sintaxe

+ +
opacity(amount)
+ +

Parâmetros

+ +
+
amount
+
A quantidade de conversão, especificada com um {{cssxref("<number>")}} ou uma {{cssxref("<percentage>")}}. Um valor de 0% é completamente transparente, enquanto que um valor de 100% mantém o input inalterado. Valores entre 0% e 100% são multiplicadores lineares do efeito. O valor de lacuna para interpolação é 1.
+
+ +

Exemplos

+ +
opacity(0%)   /* Completamente transparente */
+opacity(50%)  /* 50% transparente */
+opacity(1)    /* Nenhum efeito */
+ +

Ver também

+ +
    +
  • {{cssxref("<filter-function>")}}
  • +
  • Propriedade CSS {{cssxref("opacity")}}
  • +
diff --git a/files/pt-br/web/css/filter-function/sepia()/index.html b/files/pt-br/web/css/filter-function/sepia()/index.html new file mode 100644 index 0000000000..0ad03c1c1f --- /dev/null +++ b/files/pt-br/web/css/filter-function/sepia()/index.html @@ -0,0 +1,35 @@ +--- +title: sepia() +slug: Web/CSS/filter-function/sepia() +tags: + - Efeitos de Filtro + - Função CSS + - Referencia +translation_of: Web/CSS/filter-function/sepia() +--- +
{{cssref}}
+ +

A função CSS sepia() converte a imagem inputada em sépia, dando uma aparência mais amarelada/marrom e quente. Seu resultado é uma {{cssxref("<filter-function>")}}.

+ +

Sintaxe

+ +
sepia(amount)
+ +

Parâmetros

+ +
+
amount
+
A quantidade de conversão, especificada por um {{cssxref("<number>")}} ou uma {{cssxref("<percentage>")}}. Um valor de 100% é completamente sépia, enquanto que um valor de 0% mantém o input inalterado. Valores entre 0% e 100% são multiplicadores lineares do efeito. O valor de lacuna para interpolação é 0.
+
+ +

Exemplos

+ +
sepia(0)     /* Sem efeito */
+sepia(.65)   /* 65% sépia */
+sepia(100%)  /* Completamente sépia */
+ +

Ver também

+ +
    +
  • {{cssxref("<filter-function>")}}
  • +
diff --git a/files/pt-br/web/css/flex-direction/index.html b/files/pt-br/web/css/flex-direction/index.html new file mode 100644 index 0000000000..53dabec16b --- /dev/null +++ b/files/pt-br/web/css/flex-direction/index.html @@ -0,0 +1,153 @@ +--- +title: flex-direction +slug: Web/CSS/flex-direction +tags: + - CSS + - CSS Flexbox + - Documentação + - Propriedade CSS +translation_of: Web/CSS/flex-direction +--- +
{{CSSRef}}
+ +

A propriedade CSS flex-direction define como os itens flexíveis são colocados no contêiner flexível, definindo o eixo principal e a direção (normal ou invertido).

+ +
{{EmbedInteractiveExample("pages/css/flex-direction.html")}}
+ + + +

Observer que os valores row e row-reverse são afetados pela direcionalidade do contêiner flexível. Se seu atributo {{HTMLAttrxRef("dir")}} for ltr, row representa o eixo horizontal orientado da esquerda para a direita, e row-reverse está orientado da direita para esquerda; Se seu atributo  rtl, row representa o eixo orientado da direita para a esquerda e  row-reverse da esquerda para a direita.

+ +

Syntax

+ +
/* The direction text is laid out in a line */
+flex-direction: row;
+
+/* Like <row>, but reversed */
+flex-direction: row-reverse;
+
+/* The direction in which lines of text are stacked */
+flex-direction: column;
+
+/* Like <column>, but reversed */
+flex-direction: column-reverse;
+
+/* Global values */
+flex-direction: inherit;
+flex-direction: initial;
+flex-direction: unset;
+
+ +

Valores

+ +

Os seguintes valores são aceitos:

+ +
+
row
+
O eixo principal do flex container é definido para ser o mesmo que a direção do texto. Os pontos de início e término principais são iguais à direção do conteúdo.
+
row-reverse
+
Se comporta da mesma forma que row porém os pontos de inicio e término seram invertidos (permutados).
+
column
+
O eixo principal do flex container é igual ao eixo do bloco. Os pontos de início e término principais são iguais aos pontos de antes e depois do modo de escrita.
+
column-reverse
+
Se comporta da mesma forma que column porém os pontos de inicio e término seram invertidos (permutados).
+
+ +

Formal syntax

+ +
{{csssyntax}}
+ +

Example

+ +

HTML

+ +
<h4>This is a Column-Reverse</h4>
+<div id="content">
+  <div class="box" style="background-color:red;">A</div>
+  <div class="box" style="background-color:lightblue;">B</div>
+  <div class="box" style="background-color:yellow;">C</div>
+</div>
+<h4>This is a Row-Reverse</h4>
+<div id="content1">
+  <div class="box1" style="background-color:red;">A</div>
+  <div class="box1" style="background-color:lightblue;">B</div>
+  <div class="box1" style="background-color:yellow;">C</div>
+</div>
+
+ +

CSS

+ +
#content {
+  width: 200px;
+  height: 200px;
+  border: 1px solid #c3c3c3;
+  display: flex;
+  flex-direction: column-reverse;
+}
+
+.box {
+  width: 50px;
+  height: 50px;
+}
+
+#content1 {
+  width: 200px;
+  height: 200px;
+  border: 1px solid #c3c3c3;
+  display: flex;
+  flex-direction: row-reverse;
+}
+
+.box1 {
+  width: 50px;
+  height: 50px;
+}
+ +

Result

+ +

{{EmbedLiveSample('Example', '', '300', '', 'Web/CSS/flex-direction')}}

+ +

Accessibility Concerns

+ +

Usar a propriedade flex-direction com o valores de row-reverse or column-reverse vai criar uma desconexão entre a apresentação visual do conteúdo e a ordem do DOM. Isso afetará adversamente os usuários com problemas de visão navegando com o auxílio de tecnologia assistiva, como um leitor de tela. Se a oredem visual (CSS) for importante, os usuários de leitores de tela não terão acesso à ordem de leitura correta.

+ + + +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Flexbox', '#flex-direction', 'flex-direction')}}{{Spec2('CSS3 Flexbox')}}Initial definition
+ +

{{cssinfo}}

+ +

Browser compatibility

+ + + +

{{Compat("css.properties.flex-direction")}}

+ +

See also

+ + diff --git a/files/pt-br/web/css/flex-flow/index.html b/files/pt-br/web/css/flex-flow/index.html new file mode 100644 index 0000000000..db281a2699 --- /dev/null +++ b/files/pt-br/web/css/flex-flow/index.html @@ -0,0 +1,89 @@ +--- +title: flex-flow +slug: Web/CSS/flex-flow +tags: + - flex-box +translation_of: Web/CSS/flex-flow +--- +
{{CSSRef}}
+ +

A propriedade CSS flex-flow é uma junção das propriedades {{cssxref("flex-direction")}} e {{cssxref("flex-wrap")}}.

+ +
{{EmbedInteractiveExample("pages/css/flex-flow.html")}}
+ + + +

Sintaxe

+ +
/* flex-flow: <'flex-direction'> */
+flex-flow: row;
+flex-flow: row-reverse;
+flex-flow: column;
+flex-flow: column-reverse;
+
+/* flex-flow: <'flex-wrap'> */
+flex-flow: nowrap;
+flex-flow: wrap;
+flex-flow: wrap-reverse;
+
+/* flex-flow: <'flex-direction'> and <'flex-wrap'> */
+flex-flow: row nowrap;
+flex-flow: column wrap;
+flex-flow: column-reverse wrap-reverse;
+
+/* Global values */
+flex-flow: inherit;
+flex-flow: initial;
+flex-flow: unset;
+
+ +

Valores

+ +

Consulte {{cssxref("flex-direction")}} e {{cssxref("flex-wrap")}} para ver os detalhes sobre os valores.

+ +

Sintaxe formal

+ +
{{csssyntax}}
+ +

Exemplos

+ +
elemento {
+  /* O eixo principal é a direção do bloco com main-start e main-end invertidos.
+   * Os itens flex estão dispostos em múltiplas linhas */
+  flex-flow: column-reverse wrap;
+}
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{ SpecName('CSS3 Flexbox','#flex-flow-property','flex-flow') }}{{ Spec2('CSS3 Flexbox') }}Definição inicial
+ +

{{cssinfo}}

+ +

Compatibilidade de navegadores

+ + + +

{{Compat("css.properties.flex-flow")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/css/flex-wrap/index.html b/files/pt-br/web/css/flex-wrap/index.html new file mode 100644 index 0000000000..a73e5626eb --- /dev/null +++ b/files/pt-br/web/css/flex-wrap/index.html @@ -0,0 +1,162 @@ +--- +title: flex-wrap +slug: Web/CSS/flex-wrap +tags: + - CSS + - CSS Flex Box + - Propriedades CSS + - Referencia +translation_of: Web/CSS/flex-wrap +--- +
{{ CSSRef}}
+ +

A propriedade CSS flex-wrap define se os itens flexíveis são forçados a ficarem na mesma linha ou se podem ser quebradas em varias linhas. Se o argumento for valido, ele define a direção em que as linhas são empilhadas.

+ +

{{EmbedInteractiveExample("pages/css/flex-wrap.html")}}

+ + + +

Veja Using CSS flexible boxes para mais propriedades e informação.

+ +

Syntax

+ +
flex-wrap: nowrap; /* Default value */
+flex-wrap: wrap;
+flex-wrap: wrap-reverse;
+
+/* Global values */
+flex-wrap: inherit;
+flex-wrap: initial;
+flex-wrap: unset;
+
+ +

A propriedade flex-wrap é especificada como uma unica palavra-chave escolhida na lista de valores abaixo.

+ +

Valores

+ +

Os seguintes valores são aceitos :

+ +
+
nowrap
+
Os itens flexíveis são agrupados em uma unica linha, o que pode fazer com que o flex container transborde. O cross-start é equivalente ao início ou antes, dependendo do valor da {{cssxref("flex-direction")}}. Este é o valor padrão.
+
wrap
+
Os itens flexíveis são quebrados em multiplas linhas. O cross-start é equivalente a iniciar ou antes dependendo do valor do flex-direction e cross-end é o oposto do especificado cross-start.
+
wrap-reverse
+
Se comporta da mesma maneira que o wrap mas a de linha ocorre na direção contrária, ou seja, para a linha acima.
+
+ +

Formal definição

+ +

{{cssinfo}}

+ +

Formal syntax

+ +
{{csssyntax}}
+ +

Exemplos

+ +

Definindo valores em um flex container wrap

+ +

HTML

+ +
+
<h4>This is an example for flex-wrap:wrap </h4>
+<div class="content">
+  <div class="red">1</div>
+  <div class="green">2</div>
+  <div class="blue">3</div>
+</div>
+<h4>This is an example for flex-wrap:nowrap </h4>
+<div class="content1">
+  <div class="red">1</div>
+  <div class="green">2</div>
+  <div class="blue">3</div>
+</div>
+<h4>This is an example for flex-wrap:wrap-reverse </h4>
+<div class="content2">
+  <div class="red">1</div>
+  <div class="green">2</div>
+  <div class="blue">3</div>
+</div>
+
+ +

CSS

+ +
/* Common Styles */
+.content,
+.content1,
+.content2 {
+    color: #fff;
+    font: 100 24px/100px sans-serif;
+    height: 150px;
+    text-align: center;
+}
+
+.content div,
+.content1 div,
+.content2 div {
+    height: 50%;
+    width: 300px;
+}
+.red {
+    background: orangered;
+}
+.green {
+    background: yellowgreen;
+}
+.blue {
+    background: steelblue;
+}
+
+/* Flexbox Styles */
+.content {
+    display: flex;
+    flex-wrap: wrap;
+}
+.content1 {
+    display: flex;
+    flex-wrap: nowrap;
+}
+.content2 {
+    display: flex;
+    flex-wrap: wrap-reverse;
+}
+
+
+
+ +

Resultados

+ +

{{ EmbedLiveSample('Setting_flex_container_wrap_values', '700px', '700px', '', 'Web/CSS/flex-wrap') }}

+ +

Especificação

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{ SpecName('CSS3 Flexbox', '#flex-wrap-property', 'flex-wrap') }}{{ Spec2('CSS3 Flexbox') }}
+ +

Compatibilidade com navegadores

+ + + +

{{Compat("css.properties.flex-wrap")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/css/flex/index.html b/files/pt-br/web/css/flex/index.html new file mode 100644 index 0000000000..f7c7c55fc7 --- /dev/null +++ b/files/pt-br/web/css/flex/index.html @@ -0,0 +1,267 @@ +--- +title: flex +slug: Web/CSS/flex +translation_of: Web/CSS/flex +--- +
{{CSSRef}}
+ +

A propriedade flex do CSS, define como um ítem será posicionado para no espaço disponível dentro de seu container.

+ +
{{EmbedInteractiveExample("pages/css/flex.html")}}
+ + + +

Propriedades

+ +

Esta propriedade é uma abreviação das seguintes propriedades CSS:

+ +
    +
  • {{cssxref("flex-grow")}}
  • +
  • {{cssxref("flex-shrink")}}
  • +
  • {{cssxref("flex-basis")}}
  • +
+ +
+ + + + +

{{EmbedLiveSample("flex", 1200, 370, "", "", "example-outcome-frame")}}

+ +

By default flex items don't shrink below their minimum content size. To change this, set the item's {{cssxref("min-width")}} or {{cssxref("min-height")}}.

+
+ +

Sintaxe

+ +
/* Propriedades principais */
+flex: auto;
+flex: initial;
+flex: none;
+
+/* Valor único, sem unidade: flex-grow */
+flex: 2;
+
+/* Valor único, unidade width/height: flex-basis */
+flex: 10em;
+flex: 30%;
+flex: min-content;
+
+/* Dois valores: flex-grow | flex-basis */
+flex: 1 30px;
+
+/* Dois valores: flex-grow | flex-shrink */
+flex: 2 2;
+
+/* Três valores: flex-grow | flex-shrink | flex-basis */
+flex: 2 2 10%;
+
+/* Valores globais */
+flex: inherit;
+flex: initial;
+flex: unset;
+
+ +

The flex property may be specified using one, two, or three values.

+ +
    +
  • One-value syntax: the value must be one of: + +
      +
    • a <number>: In this case it is interpreted as flex: <number> 1 0; the <flex-shrink> value is assumed to be 1 and the <flex-basis> value is assumed to be 0.
    • +
    • one of the keywords: none, auto, or initial.
    • +
    +
  • +
  • Two-value syntax: the first value must be a {{cssxref("<number>")}} and it is interpreted as <flex-grow>. The second value must be one of: +
      +
    • a {{cssxref("<number>")}}: then it is interpreted as <flex-shrink>.
    • +
    • a valid value for {{cssxref("width")}}: then it is interpreted as <flex-basis>.
    • +
    +
  • +
  • Three-value syntax: the values must be in the following order: +
      +
    1. a {{cssxref("<number>")}} for <flex-grow>.
    2. +
    3. a {{cssxref("<number>")}} for <flex-shrink>.
    4. +
    5. a valid value for {{cssxref("width")}} for <flex-basis>.
    6. +
    +
  • +
+ +

Values

+ +
+
initial
+
The item is sized according to its width and height properties. It shrinks to its minimum size to fit the container, but does not grow to absorb any extra free space in the flex container. This is equivalent to setting "flex: 0 1 auto".
+
auto
+
The item is sized according to its width and height properties, but grows to absorb any extra free space in the flex container, and shrinks to its minimum size to fit the container. This is equivalent to setting "flex: 1 1 auto".
+
none
+
The item is sized according to its width and height properties. It is fully inflexible: it neither shrinks nor grows in relation to the flex container. This is equivalent to setting "flex: 0 0 auto".
+
<'flex-grow'>
+
Defines the {{cssxref("flex-grow")}} of the flex item. Negative values are considered invalid. Defaults to 1 when omitted.
+
<'flex-shrink'>
+
Defines the {{cssxref("flex-shrink")}} of the flex item. Negative values are considered invalid. Defaults to 1 when omitted.
+
<'flex-basis'>
+
Defines the {{cssxref("flex-basis")}} of the flex item. A preferred size of 0 must have a unit to avoid being interpreted as a flexibility. Defaults to 0 when omitted.
+
+ +

Formal syntax

+ +
{{csssyntax}}
+ +

Example

+ +
#flex-container {
+  display: flex;
+  flex-direction: row;
+}
+
+#flex-container > .flex-item {
+  flex: auto;
+}
+
+#flex-container > .raw-item {
+  width: 5rem;
+}
+
+ +
<div id="flex-container">
+  <div class="flex-item" id="flex">Flex box (click to toggle raw box)</div>
+  <div class="raw-item" id="raw">Raw box</div>
+</div>
+
+ + + +

Result

+ +

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

+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Flexbox', '#flex-property', 'flex')}}{{Spec2('CSS3 Flexbox')}}Initial definition
+ +

{{cssinfo}}

+ +

Browser compatibility

+ + + +

{{Compat("css.properties.flex")}}

+ +

See also

+ + diff --git a/files/pt-br/web/css/float/index.html b/files/pt-br/web/css/float/index.html new file mode 100644 index 0000000000..e75e2c4c06 --- /dev/null +++ b/files/pt-br/web/css/float/index.html @@ -0,0 +1,290 @@ +--- +title: float +slug: Web/CSS/float +tags: + - CSS +translation_of: Web/CSS/float +--- +
{{CSSRef}}
+ +

Resumo

+ +

A propriedade float do CSS determina que um elemento deve ser retirado do seu fluxo normal e colocado ao longo do lado direito ou esquerdo do seu containêr, onde textos  e elementos em linha irão se posicionar ao seu redor.

+ +

Um elemento flutuante é um tipo de elemento cujo valor de float é diferente de none.

+ +

{{cssinfo}}

+ +

Como float implica o uso the block layout, ele modifica o valor computado de {{cssxref("display")}} em alguns casos:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Valor EspecificadoValor Computado
inlineblock
inline-blockblock
inline-tabletable
table-rowblock
table-row-groupblock
table-columnblock
table-column-groupblock
table-cellblock
table-captionblock
table-header-groupblock
table-footer-groupblock
flexflex, porém float não produz efeito em tais elementos
inline-flexinline-flex, porém float não produz efeito em tais elementos
otherunchanged
+ +
Nota: Se você está se referindo a essa propriedade do Javascript como um membro do objeto {{domxref("element.style")}}, você deve referir-se a cssFloat. Observe também que as versões 8 e posteriores referem-se a styleFloat. Esta é uma exceção à regra de que o nome do membro DOM é o nome em estilo camel-case do nome CSS separado por traço (e se deve ao fato de que "float" é uma palavra reservada em Javascript, tal qual a necessidade de especificar "class" como "className" e "for" como "htmlFor").
+ +

Sintaxe

+ +
float: left;
+float: right;
+float: none;
+float: inline-start;
+float: inline-end;
+
+/* Global values */
+float: inherit;
+float: initial;
+float: unset;
+
+ +

Valores

+ +
+
left
+
É uma palavra-chave que indica que o elemento deve flutuar à esquerda do bloco.
+
right
+
É uma palavra-chave que indica que o elemento deve flutuar à direita do bloco.
+
none
+
É uma palavra-chave que indica que o elemtno não deve flutuar.
+
inline-start {{experimental_inline}}
+
É uma palavra-chave que indica que o elemento deve flutuar no lado inicial do seu bloco, ou seja, o lado esquerdo em scripts ltr e no direito em scripts rtl.
+
inline-end {{experimental_inline}}
+
É uma palavra-chave que indica que o elemento deve flutuar no lado final do seu bloco, ou seja, o lado direito em scripts ltr e no esquerdo em scripts rtl.
+
+ +

Sintaxe Formal

+ +
{{csssyntax}}
+ +

Exemplos

+ +

HTML

+ +
<style type="text/css">
+  div { border: solid red;  max-width: 70ex; }
+  h4  { float: left;  margin: 0; }
+</style>
+
+<div>
+  <h4>HELLO!</h4>
+  This is some text. This is some text. This is some text.
+  This is some text. This is some text. This is some text.
+  This is some text. This is some text. This is some text.
+  This is some text. This is some text. This is some text.
+</div>
+ +

{{ EmbedLiveSample('Exemplos', '', '', '', 'Web/CSS/float') }}

+ +
+

HELLO!

+This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text. This is some text.
+ +

 

+ +

Como floats são posicionados

+ +

Como mencionado acima, quando um elemento é flutuado ele é retirado do seu fluxo normal no documento. Ele é reposicionado à esquerda ou à direita até tocar a borda do seu próprio box ou outro elemento flutuante.

+ +

Na imagem abaixo, existem 3 quadrados vermelho. Dois flutuando à esquerda e um flutuando à direita. Observe que o segundo quadrado vermelho à esquerda é posicionado à direita do primeiro. Quadrados adicionais poderiam continuar sendo empilhados à direita até que eles completassem o box, após isso eles iriam para próxima linha. 

+ +

+ +

Limpando floats

+ +

No exemplo abaixo, os elementos flutuantes são menores verticalmente que o bloco de texto com os quais estão flutuando. Apesar disso, se o texto não fosse comprido o bastante para passar abaixo do limite inferior de todos os floats, nos veríamos efeitos não previstos. Se o parágrafo abaixo, por enquanto, somente lê "Lorem ipsum dolor sit amet,",  e fosse seguido por outro cabeçalho do mesmo estilo de cabeçaljo "Floats Example", o segundo cabeçalho iria aparecer entre os dois boxes vermelhos. Muito provavelmente, queremos que o próximo título seja alinhado à esquerda. Para conseguir isso, precisamos limpar os floats.

+ +

O jeito mais simples de limpar os floats neste exemplo é adicionar a propriedade {{Cssxref("clear")}} para o próximo cabeçalho que queremos assegurar que esteja alinhado à esquerda. 

+ +
h2.secondHeading { clear: both; }
+
+ +

Porém, este método apenas funciona se não existirem outros elementos com o mesmo block formatting context  aos quais nós queiramos que o cabeçalho continue aparecendo ao lado horizontalmente. Se o nosso H2 possui irmãos os quais são barras laterais flutuadas à esquerda e à direita, usar clear irá forçá-lo a aparecer abaixo das duas barras laterais, o que provavelmente não é o que queríamos.

+ +

Se limpar floats em um elemento não é uma opção, uma outra abordagem é limitar o contexto de formatação do bloco do containêr flutuante. Referindo-se ao exemplo acima novamente, aparentemente todos os três quadrados vermelhos possuem um elemento paragrafo P . Nós podemos atribuir a propiedade {{Cssxref("overflow")}} neste paragrafo para hidden ou auto  para obrigá-lo a expandir para contê-los, porém não permitirá que os mesmos parágrafos pulem fora do limite inferior.

+ +
p.withRedBoxes { overflow: hidden; height: auto; }
+
+ +
Nota: Atribuir overflow para scroll irá conter também qualquer elemento filho flutuante, mas mostrará as barras de rolagem não importando o comprimento vertical do elemento. Aqui nós estamos atribuindo height como auto mesmo sendo este o padrão para indicar que o containêr deve crescer para acomodar seu conteúdo. 
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoSituaçãoComentário
{{SpecName('CSS Logical Properties', '#float-clear', 'float and clear')}}{{Spec2('CSS Logical Properties')}}Adiciona os valores inline-start e inline-end.
{{SpecName('CSS3 Box', '#float', 'float')}}{{Spec2('CSS3 Box')}} +

Muitos valores novos, nem todos claramente definidos ainda. Qualquer diferença em comportamento não relacionado a novas funções são involutárias; por favor informe.

+
{{SpecName('CSS2.1', 'visuren.html#float-position', 'float')}}{{Spec2('CSS2.1')}}Sem mudanças
{{SpecName('CSS1', '#float', 'float')}}{{Spec2('CSS1')}}Definição inicial
+ +

Compatibilidade de browser

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1.0{{CompatVersionUnknown}}{{CompatGeckoDesktop("1")}}4.07.01.0
inline-start, inline-end{{CompatNo}}{{CompatUnknown}}{{CompatGeckoDesktop("45")}} [1]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support1.0{{CompatVersionUnknown}}{{CompatGeckoMobile("1")}}1.06.06.01.0
inline-start, inline-end{{CompatNo}}{{CompatUnknown}}{{CompatGeckoMobile("45")}} [1]2.5{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] Habilitado por padrão no Nightly e Aurora (Dev edition); para ativar em uma versão release ou beta, você precisa alterar o layout.css.float-logical-values.enabled para true.

+ +

Veja também

+ + diff --git a/files/pt-br/web/css/font-family/index.html b/files/pt-br/web/css/font-family/index.html new file mode 100644 index 0000000000..0d9bb5dc45 --- /dev/null +++ b/files/pt-br/web/css/font-family/index.html @@ -0,0 +1,238 @@ +--- +title: font-family +slug: Web/CSS/font-family +tags: + - CSS + - Fontes CSS + - Lay + - Propriedade CSS + - Refer + - Web +translation_of: Web/CSS/font-family +--- +

{{CSSRef}}

+ +

Resumo

+ +

A propriedade font-family do CSS permite que se faça uma lista de prioridades de familias de fontes e/ou nomes genéricos de famílias a serem especificados para um elemento selecionado. Ao contrário da maioria das demais propriedades CSS, os valores são separados por vírgula para indicar quais são as alternativas. O Browser irá utilizar a primeira fonte da lista que for encontrada no computador, ou poderá fazer o dowload utilizando a informação contida na regra {{cssxref("@font-face")}}.

+ +

Programadores WEB devem sempre adicionar pelo menos uma família genérica para a lista de font-family, já que não há garantia que aquela fonte específica está instalada no computador, ou possa ser baixada pela regra {{cssxref("@font-face")}}. A família genérica permite o browser selecionar uma fonte aceita pelo computador, quando necessário.

+ +

É também conveniente usar de antemão a propriedade {{cssxref("font")}} para definir a font-size e outras propriedades relacionadas a fonte todas de uma só vez.

+ +
Nota: A propriedade font-family especifica a lista de fontes, da prioridade mais alta para a mais baixa. + +
A seleção de fontes não para simplesmente na primeira fonte nomeada na lista que está no sistema do usuário. Em vez disso, a seleção de fontes é feita um caractere de cada vez, para que, se uma fonte disponível não tiver um glifo que possa exibir um caracter necessário, as fontes disponíveis mais tarde sejam tentadas. No entanto, isso não funciona no Internet Explorer 6 ou anterior.
+
+Quando uma fonte está disponível apenas em alguns estilos, variantes ou tamanhos, essas propriedades também podem influenciar qual família de fontes é escolhida.
+
+ +

{{cssinfo}}

+ +

Syntax

+ +
Formal syntax: {{csssyntax("font-family")}}
+
+ +
font-family: Gill Sans Extrabold, sans-serif
+font-family: "Goudy Bookletter 1911", sans-serif
+
+font-family: sans-serif
+font-family: serif
+font-family: fantasy
+font-family: cursive
+font-family: monospace
+
+font-family: inherit
+
+ +

Valores

+ + + + + + + + + + + + +
<family-name>O nome de uma fonte. Por exemplo, "Times" e "Helvetica" são font families. Nomes de fonte-família contém espaços em branco para serem citados..
<generic-name> +

Generic font families are a fallback mechanism, a means of preserving some of the style sheet author's intent in case when none of the specified fonts are available. Generic family names are keywords and must not be quoted. A generic font family should be the a last alternative in the list of font family names.

+ +
+
serif
+
Glyphs have finishing strokes, flared or tapering ends, or have actual serifed endings.
+ E.g.  Palatino, "Palatino Linotype", Palladio, "URW Palladio", serif
+
sans-serif
+
Glyphs have stroke endings that are plain.
+ E.g. 'Trebuchet MS', 'Liberation Sans', 'Nimbus Sans L', sans-serif
+
monospace
+
All glyphs have the same fixed width.
+ E.g. "DejaVu Sans Mono", Menlo, Consolas, "Liberation Mono", Monaco, "Lucida Console", monospace
+
cursive
+
Glyphs in cursive fonts generally have either joining strokes or other cursive characteristics beyond those of italic typefaces. The glyphs are partially or completely connected, and the result looks more like handwritten pen or brush writing than printed letterwork.
+
fantasy
+
Fantasy fonts are primarily decorative fonts that contain playful representations of characters.
+
+
+ +

Valid family names

+ +

Font family names must either be given quoted as strings, or unquoted as a sequence of one or more identifiers. This means that punctuation characters and digits at the start of each token must be escaped in unquoted font family names.

+ +

For example, the following declarations are valid:

+ +
font-family: Gill Sans Extrabold, sans-serif;
+font-family: "Goudy Bookletter 1911", sans-serif;
+ +

The following declarations are invalid:

+ +
font-family: Goudy Bookletter 1911, sans-serif;
+font-family: Red/Black, sans-serif;
+font-family: "Lucida" Grande, sans-serif;
+font-family: Ahem!, sans-serif;
+font-family: test@foo, sans-serif;
+font-family: #POUND, sans-serif;
+font-family: Hawaii 5-0, sans-serif;
+ +

Examples

+ +

Example 1

+ +
body {
+  font-family: "Gill Sans Extrabold", Helvetica, sans-serif;
+}
+
+.receipt {
+  font-family: Courier, "Lucida Console", monospace;
+}
+
+ +

Example 2

+ +
.exampleserif {
+    font-family: Times, "Times New Roman", Georgia, serif;
+}
+
+.examplesansserif {
+    font-family: Verdana, Arial, Helvetica, sans-serif;
+}
+
+.examplemonospace {
+    font-family: "Lucida Console", Courier, monospace;
+}
+
+.examplecursive {
+    font-family: cursive;
+}
+
+.examplefantasy {
+    font-family: fantasy;
+}
+
+ +
<div class="exampleserif">
+This is an example of a serif font.
+</div>
+
+<div class="examplesansserif">
+This is an example of a sans-serif font.
+</div>
+
+<div class="examplemonospace">
+This is an example of a monospace font.
+</div>
+
+<div class="examplecursive">
+This is an example of a cursive font.
+</div>
+
+<div class="examplefantasy">
+This is an example of a fantasy font.
+</div>
+ +

Live Sample

+ +

{{ EmbedLiveSample('Example_2','600','120') }}

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Fonts', '#font-family-prop', 'font-family')}}{{Spec2('CSS3 Fonts')}}No significant change
{{SpecName('CSS2.1', 'fonts.html#propdef-font-family', 'font-family')}}{{Spec2('CSS2.1')}}No significant change
{{SpecName('CSS1', '#font-family', 'font-familiy')}}{{Spec2('CSS1')}}Initial definition
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1.0{{CompatGeckoDesktop("1")}}3.03.51.0
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support1.0{{CompatGeckoMobile("1")}}6.06.01.0
+
diff --git a/files/pt-br/web/css/font-feature-settings/index.html b/files/pt-br/web/css/font-feature-settings/index.html new file mode 100644 index 0000000000..dff644c1b5 --- /dev/null +++ b/files/pt-br/web/css/font-feature-settings/index.html @@ -0,0 +1,182 @@ +--- +title: font-feature-settings +slug: Web/CSS/font-feature-settings +tags: + - CSS + - Fontes CSS + - Propriedade CSS + - Referencia +translation_of: Web/CSS/font-feature-settings +--- +
{{CSSRef}}
+ +

Sumário

+ +

A propriedade font-feature-settings do CSS te dá controle sobre tipografia avançada nas fontes do tipo OpenType.

+ +
Nota: Sempre que possível, deve usar o {{cssxref("font-variant")}} propriedade abreviada ou uma propriedade extensa associada, {{cssxref("font-variant-ligatures")}}, {{cssxref("font-variant-caps")}}, {{cssxref("font-variant-east-asian")}}, {{cssxref("font-variant-alternates")}}, {{cssxref("font-variant-numeric")}} ou {{cssxref("font-variant-position")}}.
+
+Esta propriedade é um recurso de baixo nível projetado para lidar com casos especiais onde não existe outra maneira de habilitar ou acessar um recurso de fonte OpenType.
+
+Em particular, esta propriedade CSS não deve ser usada para habilitar small caps.
+ +

{{cssinfo}}

+ +

Sintaxe

+ +
/* Use the default settings */
+font-feature-settings: normal;
+
+/* Set values for OpenType feature tags */
+font-feature-settings: "smcp";
+font-feature-settings: "smcp" on;
+font-feature-settings: "swsh" 2;
+font-feature-settings: "smcp", "swsh" 2;
+
+/* Global values */
+font-feature-settings: inherit;
+font-feature-settings: initial;
+font-feature-settings: unset;
+
+ +

Valores

+ +
+
normal
+
Text is laid out using default settings.
+
<feature-tag-value>
+
Ao renderizar texto, a lista de características OpenType é passada para o mecanismo de layout de texto para ativar ou desativar recursos do tipo de letra. A tag é sempre uma {{cssxref("<string>")}} de 4 caracteres ASCII. Se possuir mais ou menos caracteres ou conter caracteres fora da faixa U+20 - U+7E, toda a propriedade é invalida.
+ O valor é um inteiro positivo. As duas palavras-chaves on e off são sinônimos de 1 e 0 respectivamente. Se nenhum valor é definido, o padrão é 1. Para características OpenType não-booleanas (ex. stylistic alternates), o valor implica em um glifo particular para ser selecionado; para valores booleanos, é um interruptor.
+
+ +

Sintaxe formal

+ +
{{csssyntax}}
+ +

Exemplos

+ +
/* use small-cap alternate glyphs */
+.smallcaps { font-feature-settings: "smcp" on; }
+
+/* convert both upper and lowercase to small caps (affects punctuation also) */
+.allsmallcaps { font-feature-settings: "c2sc", "smcp"; }
+
+/* enable historical forms */
+.hist { font-feature-settings: "hist"; }
+
+/* disable common ligatures, usually on by default */
+.noligs { font-feature-settings: "liga" 0; }
+
+/* enable tabular (monospaced) figures */
+td.tabular { font-feature-settings: "tnum"; }
+
+/* enable automatic fractions */
+.fractions { font-feature-settings: "frac"; }
+
+/* use the second available swash character */
+.swash { font-feature-settings: "swsh" 2; }
+
+/* enable stylistic set 7 */
+.fancystyle {
+  font-family: Gabriola; /* available on Windows 7, and on Mac OS */
+  font-feature-settings: "ss07";
+}
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificacãoEstadoComment
{{SpecName('CSS3 Fonts', '#propdef-font-feature-settings', 'font-feature-settings')}}{{Spec2('CSS3 Fonts')}}Initial definition
+ +

Compatibilidade do navegador

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico +

16.0 {{property_prefix("-webkit")}}
+ {{CompatChrome(48.0)}} (unprefixed)

+
+

{{CompatGeckoDesktop("2.0")}} {{property_prefix("-moz")}} [1]
+ {{CompatGeckoDesktop("29.0")}} {{property_prefix("-moz")}} [2]
+ {{CompatGeckoDesktop("34.0")}} [3]

+
10.015.0 {{property_prefix("-webkit")}}{{CompatSafari("9.1")}} (partial support in versions 4.0-6.0)
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewChrome para AndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Suporte básico{{CompatAndroid(4.4)}}{{CompatChrome(48.0)}} (unprefixed){{CompatChrome(48.0)}} (unprefixed) +

{{CompatGeckoDesktop("2.0")}} {{property_prefix("-moz")}} [1]
+ {{CompatGeckoDesktop("29.0")}} {{property_prefix("-moz")}} [2]
+ {{CompatGeckoDesktop("34.0")}} [3]

+
{{CompatUnknown}}{{CompatOpera("24")}}{{CompatSafari("9.3")}} (partial support in versions 3.2-6.1)
+
+ +

[1] From Gecko 2.0 (Firefox 4.0) to Gecko 14.0 (Firefox 14.0) included, Gecko supported an older syntax, slightly different from the modern one: OpenType Font Feature support in Firefox 4.

+ +

[2] The ISO/IEC CD 14496-22 3rd edition suggests to use the ssty feature to provide glyph variants adjusted to be more suitable for use in scripts (for example primes used as superscripts). Starting with Firefox 29, this is done automatically by the MathML rendering engine. It also suggests applying the dtls feature to letters when positing mathematical accent over it, in order to get dotless forms (for example dotless i, j with a hat). Starting with Firefox 35, this is done automatically by the MathML rendering engine. You can always override via CSS the default values determined by the MathML rendering engine.

+ +

[3] Starting with Firefox 34, the version prefixed with -moz- is only kept for backward compatibility purpose. It is controlled by the layout.css.prefixes.font-features, defaulting to true. The prefixed property will be removed in the future.

+ +

Veja Também

+ + diff --git a/files/pt-br/web/css/font-kerning/index.html b/files/pt-br/web/css/font-kerning/index.html new file mode 100644 index 0000000000..59005e877f --- /dev/null +++ b/files/pt-br/web/css/font-kerning/index.html @@ -0,0 +1,166 @@ +--- +title: font-kerning +slug: Web/CSS/font-kerning +translation_of: Web/CSS/font-kerning +--- +
{{CSSRef}}
+ +

A propriedade CSS font-kerning controla o o uso da informação de kerning, que é, o controle de como as letras serão espaçadas. A informação de kerning é armazenada na fonte, e se a fonte é well-kerned, essa caracteristica permite que o espaçamento entre caracteres seja muito parecido, independente dos caracteres.

+ +

Example of font-kerning

+ +
font-kerning: auto;
+font-kerning: normal;
+font-kerning: none;
+
+/* Global values */
+font-kerning: inherit;
+font-kerning: initial;
+font-kerning: unset;
+
+ +

{{cssinfo}}

+ +

Syntax

+ +

Values

+ +
+
auto
+
This keyword defers to the browser regarding whether to use kerning. When the font size is small, font kerning may look strange and browsers will disable it. This is the default value.
+
normal
+
This keyword requires kerning to be applied.
+
none
+
This keyword prevents the browser from using the kerning information stored in the font.
+
+ +

Formal syntax

+ +
{{csssyntax}}
+ +

Examples

+ +
p {
+  font-kerning: none;
+}
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Fonts', '#propdef-font-kerning', 'font-kerning')}}{{Spec2('CSS3 Fonts')}}Initial definition
+ +

Browser Compatibility

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support32[1]{{CompatVersionUnknown}}{{CompatGeckoDesktop("34")}}[2]10[3]{{ CompatUnknown() }}7
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}{{CompatVersionUnknown}}{{CompatGeckoMobile("34")}}[2]{{ CompatUnknown() }}{{ CompatUnknown() }}7
+
+ +

[1] Requires prefix -webkit-font-kerning. First version supporting this property is not known.

+ +

[2] Experimental implementation was available since Gecko 24. It was governed by the preference layout.css.font-features.enabled defaulting to true on Nightly and Aurora only.

+ +

[3] OpenType layout features might be supported using font-feature-settings property, however individual font-kerning property is not supported.

+ +

Kerning Demo

+ +

HTML Content

+ +
<div id="kern"></div>
+<div id="nokern"></div>
+<textarea id="input">AV T. ij</textarea>
+ +

CSS Content

+ +
#nokern, #kern {
+  font-size: 2rem;
+  font-family: serif;
+}
+#nokern {
+  font-kerning: none;
+}
+#kern {
+  font-kerning: normal;
+}
+ +

JS Content

+ +
var input  = document.getElementById('input'),
+    kern   = document.getElementById('kern'),
+    nokern = document.getElementById('nokern');
+input.addEventListener('keyup', function() {
+  kern.textContent = input.value; /* Update content */
+  nokern.textContent = input.value;
+});
+kern.textContent = input.value; /* Initialize content */
+nokern.textContent = input.value;
+
+ +

{{ EmbedLiveSample('Kerning_Demo') }}

+ +

See also

+ +
    +
  • {{cssxref("font-variant")}}, {{cssxref("font-variant-position")}}, {{cssxref("font-variant-east-asian")}}, {{cssxref("font-variant-caps")}}, {{cssxref("font-variant-ligatures")}}, {{cssxref("font-variant-numeric")}}, {{cssxref("font-variant-alternates")}}, {{cssxref("font-synthesis")}}, {{cssxref("letter-spacing")}}.
  • +
diff --git a/files/pt-br/web/css/font-size/index.html b/files/pt-br/web/css/font-size/index.html new file mode 100644 index 0000000000..3560b57bc6 --- /dev/null +++ b/files/pt-br/web/css/font-size/index.html @@ -0,0 +1,234 @@ +--- +title: font-size +slug: Web/CSS/font-size +translation_of: Web/CSS/font-size +--- +
{{CSSRef}}
+ +

A propriedade font-size no CSS estabelece o tamanho da fonte. Esta propriedade também é usada para computaro tamanho de em, ex, e outras unidades {{cssxref("<length>")}} relativas.

+ +
{{EmbedInteractiveExample("pages/css/font-size.html")}}
+ + + +

Sintaxe

+ +
/* <absolute-size> values */
+font-size: xx-small;
+font-size: x-small;
+font-size: small;
+font-size: medium;
+font-size: large;
+font-size: x-large;
+font-size: xx-large;
+
+/* <relative-size> values */
+font-size: smaller;
+font-size: larger;
+
+/* <length> values */
+font-size: 12px;
+font-size: 0.8em;
+
+/* <percentage> values */
+font-size: 80%;
+
+/* Global values */
+font-size: inherit;
+font-size: initial;
+font-size: unset;
+
+ +

The font-size property is specified in one of the following ways:

+ +
    +
  • As one of the absolute-size or relative-size keywords
  • +
  • As a <length> or a <percentage>, relative to the parent element's font size
  • +
+ +

Valores

+ +
+
xx-small, x-small, small, medium, large, x-large, xx-large
+
Absolute-size keywords, based on the user's default font size (which is medium).
+
larger, smaller
+
Relative-size keywords. The font will be larger or smaller relative to the parent element's font size, roughly by the ratio used to separate the absolute-size keywords above.
+
{{cssxref("<length>")}}
+
+

A positive {{cssxref("<length>")}} value. For most font-relative units (such as em and ex), the font size is relative to the parent element's font size.

+ +

For font-relative units that are root-based (such as rem), the font size is relative to the size of the font used by the {{HTMLElement("html")}} (root) element.

+
+
{{cssxref("<percentage>")}}
+
+

A positive {{cssxref("<percentage>")}} value, relative to the parent element's font size.

+
+
+ +
+

Note: To maximize accessibility, it is generally best to use values that are relative to the user's default font size.

+
+ +

Formal syntax

+ +
{{csssyntax}}
+ +

Possible approaches

+ +

There are several ways to specify the font size, including with keywords or numerical values for pixels or ems. Choose the appropriate method based on the needs for the particular web page.

+ +

Keywords

+ +

Keywords are a good way to set the size of fonts on the web. By setting a keyword font size on the {{HTMLElement("body")}} element, you can set relative font-sizing everywhere else on the page, giving you the ability to easily scale the font up or down on the entire page accordingly.

+ +

Pixels

+ +

Setting the font size in pixel values (px) is a good choice when you need pixel accuracy. A px value is static. This is an OS-independent and cross-browser way of literally telling the browsers to render the letters at exactly the number of pixels in height that you specified. The results may vary slightly across browsers, as they may use different algorithms to achieve a similar effect.

+ +

Font sizing settings can also be used in combination. For example, if a parent element is set to 16px and its child element is set to larger, the child element displays larger than the parent element in the page.

+ +
Note: Defining font sizes in px is not accessible, because the user cannot change the font size from the browser. For example, users with limited vision may wish to set the font size much larger than the size chosen by a web designer. Avoid using them for font sizes if you wish to create an inclusive design.
+ +

Ems

+ +

Another way of setting the font size is with em values. The size of an em value is dynamic. When defining the font-size property, an em is equal to the size of the font that applies to the parent of the element in question. If you haven't set the font size anywhere on the page, then it is the browser default, which is often 16px. So, by default 1em = 16px, and 2em = 32px. If you set a font-size of 20px on the body element, then 1em = 20px and 2em = 40px. Note that the value 2 is essentially a multiplier of the current em size.

+ +

In order to calculate the em equivalent for any pixel value required, you can use this formula:

+ +
em = desired element pixel value / parent element font-size in pixels
+ +

For example, suppose the font-size of the body of the page is set to 16px. If the font-size you want is 12px, then you should specify 0.75em (because 12/16 = 0.75). Similarly, if you want a font size of 10px, then specify 0.625em (10/16 = 0.625); for 22px, specify 1.375em (22/16).

+ +

The em is a very useful unit in CSS, since it automatically adapts its length relative to the font that the reader chooses to use.

+ +

One important fact to keep in mind: em values compound. Take the following HTML and CSS:

+ +
html {
+  font-size: 62.5%; /* font-size 1em = 10px on default browser settings */
+}
+span {
+  font-size: 1.6em;
+}
+ +
<div>
+<span>Outer <span>inner</span> outer</span>
+</div>
+
+ +

The result is:

+ +

{{EmbedLiveSample("Ems", 400, 40)}}

+ +

Assuming that the browser's default font-size is 16px, the words “outer” would be rendered at 16px, but the word “inner” would be rendered at 25.6px. This is because the inner {{HTMLElement("span")}}'s font-size is 1.6em which is relative to its parent's font-size, which is in turn relative to its parent's font-size. This is often called compounding.

+ +

Rems

+ +

rem values were invented in order to sidestep the compounding problem. rem values are relative to the root html element, not the parent element. In other words, it lets you specify a font size in a relative fashion without being affected by the size of the parent, thereby eliminating compounding.

+ +

The CSS below is nearly identical to the previous example. The only exception is that the unit has been changed to rem.

+ +
html {
+  font-size: 62.5%; /* font-size 1em = 10px on default browser settings */
+}
+span {
+  font-size: 1.6rem;
+}
+
+ +

Then we apply this CSS to the same HTML, which looks like this:

+ +
<span>Outer <span>inner</span> outer</span>
+ +

{{EmbedLiveSample("Rems", 400, 40)}}

+ +

In this example, the words “outer inner outer” are all displayed at 16px (assuming that the browser's font-size has been left at the default value of 16px).

+ +

Examples

+ +

Example 1

+ +
/* Sets paragraph text to be very large */
+p { font-size: xx-large; }
+
+/* Sets <h1> 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; }
+
+ +

Example 2

+ +

CSS

+ +
.small {
+  font-size: xx-small;
+}
+.larger {
+  font-size: larger;
+}
+.point {
+  font-size: 24pt;
+}
+.percent {
+  font-size: 200%;
+}
+
+ +

HTML

+ +
<h1 class="small">Small H1</h1>
+<h1 class="larger">Larger H1</h1>
+<h1 class="point">24 point H1</h1>
+<h1 class="percent">200% H1</h1>
+ +

Result

+ +

{{EmbedLiveSample('Example_2','600','200')}}

+ +

Notes

+ +

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

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Fonts', '#font-size-prop', 'font-size')}}{{Spec2('CSS3 Fonts')}}No change.
{{SpecName('CSS3 Transitions', '#animatable-css', 'font-size')}}{{Spec2('CSS3 Transitions')}}Defines font-size as animatable.
{{SpecName('CSS2.1', 'fonts.html#propdef-font-size', 'font-size')}}{{Spec2('CSS2.1')}}No change.
{{SpecName('CSS1', '#font-size', 'font-size')}}{{Spec2('CSS1')}}Initial definition.
+ +

{{cssinfo}}

+ +

Browser compatibility

+ + + +

{{Compat("css.properties.font-size")}}

diff --git a/files/pt-br/web/css/font-variation-settings/index.html b/files/pt-br/web/css/font-variation-settings/index.html new file mode 100644 index 0000000000..c0c7a280f8 --- /dev/null +++ b/files/pt-br/web/css/font-variation-settings/index.html @@ -0,0 +1,145 @@ +--- +title: font-variation-settings +slug: Web/CSS/font-variation-settings +translation_of: Web/CSS/font-variation-settings +--- +
{{CSSRef}}
+ +

A propriedade CSS font-variation-settings fornece controle de baixo nível sobre características de variable font, especificando os nomes dos quatro eixos das características que você deseja variar, juntamente com seus valores.

+ +
{{EmbedInteractiveExample("pages/css/font-variation-settings.html")}}
+ + + +
Note: This property is a low-level mechanism designed to set variable font features where no other way to enable or access those features exist. You should only use it when no basic properties exist to set those features (e.g. {{cssxref("font-weight")}}, {{cssxref("font-style")}}).
+ +
Note: font characteristics set using font-variation-settings will always override those set using the corresponding basic font properties, e.g. font-weight, no matter where they appear in the cascade. In some browsers, this is currently only true when the @font-face declaration includes a font-weight range.
+ +

Sintaxe

+ +
/* Usar as configurações padrão */
+font-variation-settings: normal;
+
+/* Definir valores para os nomes dos eixos de fontes variáveis */
+font-variation-settings: "XHGT" 0.7;
+
+/* Valores globais */
+font-variation-settings: inherit;
+font-variation-settings: initial;
+font-variation-settings: unset;
+
+ +

Values

+ +

O valor desta propriedade pode assumir uma de duas formas:

+ +
+
normal
+
O texto é colocado usando as configurações padrão.
+
<string> <number>
+
Ao renderizar texto, a lista de nomes dos eixos de fontes variáveis é passada para o mecanismo de layout de texto para ativar ou desativar os recursos de fonte. Cada configuração é sempre um ou mais pares que consistem em um {{cssxref("<string>")}} de 4 caracteres ASCII seguidos por um {{cssxref("number")}} indicando o valor do eixo a ser definido. Se a <string> tiver mais ou menos caracteres ou contiver caracteres fora do intervalo de códigos U+20 - U+7E, toda a propriedade será inválida. O <number> pode ser fracionário ou negativo, dependendo do intervalo de valores disponível em sua fonte, conforme definido pelo designer da fonte.
+
+ +
{{csssyntax}}
+ +

Eixos registrados e personalizados

+ +

Os eixos de fontes variáveis vêm em dois tipos: registrados e personalizados.

+ +

Os eixos registrados são os mais comumente encontrados - comuns o suficiente para que os autores das especificações considerassem que valia a pena padronizar. Observe que isso não significa que o autor precise incluir tudo isso em sua fonte.

+ +

Aqui estão os eixos registrados, juntamente com suas propriedades CSS correspondentes:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Tag do EixoPropriedade CSS
"wght"{{cssxref("font-weight")}}
"wdth"{{cssxref("font-stretch")}}
"slnt" (slant){{cssxref("font-style")}}: oblique + angle
"ital"{{cssxref("font-style")}}: italic
"opsz" +

{{cssxref("font-optical-sizing")}}

+
+ +

Os eixos personalizados podem ser qualquer coisa que o designer da fonte deseje variar em sua fonte, por exemplo, alturas ascendentes ou descendentes, o tamanho das serifas ou qualquer outra coisa que possam imaginar. Qualquer eixo pode ser usado desde que seja dado um eixo exclusivo de 4 caracteres. Alguns acabam se tornando mais comuns e podem até se registrar com o tempo.

+ +
+

Nota: As tags de eixo registrados são identificadas usando tags minúsculas, enquanto os eixos personalizados devem receber tags maiúsculas. Observe que os designers de fontes não são forçados a seguir essa prática de maneira alguma, e alguns não o fazem. O ponto importante aqui é que as tags de eixo diferenciam maiúsculas de minúsculas.

+
+ +

Exemplos

+ +

Veja abaixo exemplos interativos que demonstram os eixos registrados. Você pode encontrar vários outros exemplos de fontes variáveis em nosso Variable fonts guide, v-fonts.com, e axis-praxis.org.

+ +
+

Aviso: Para usar fontes variáveis em seu sistema operacional, você precisa verificar se está atualizado. Por exemplo, os sistemas operacionais Linux precisam da versão mais recente do Linux Freetype, e o macOS anterior à 10.13 não suportam fontes variáveis. Se o seu sistema operacional não estiver atualizado, você não poderá usar fontes variáveis em páginas da Web ou no Firefox Developer Tools.

+
+ +

Peso (wght)

+ +

O CSS do exemplo a seguir pode ser editado para permitir que você mude os valores de peso da fonte.

+ +
{{EmbedGHLiveSample("css-examples/variable-fonts/weight.html", '100%', 520)}}
+ +

Inclinação (slnt)

+ +

O CSS do exemplo a seguir pode ser editado para permitir que você mude os valores oblíquos / oblíquos da fonte.

+ +
{{EmbedGHLiveSample("css-examples/variable-fonts/slant.html", '100%', 520)}}
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('CSS4 Fonts', '#low-level-font-variation-settings-control-the-font-variation-settings-property', 'font-variation-settings')}}{{Spec2('CSS4 Fonts')}}Initial definition
+ +

{{cssinfo}}

+ +

Compatibilidade do navegador

+ + + +

{{Compat("css.properties.font-variation-settings")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/css/font-weight/index.html b/files/pt-br/web/css/font-weight/index.html new file mode 100644 index 0000000000..33d4118762 --- /dev/null +++ b/files/pt-br/web/css/font-weight/index.html @@ -0,0 +1,284 @@ +--- +title: font-weight +slug: Web/CSS/font-weight +translation_of: Web/CSS/font-weight +--- +
{{CSSRef}}
+ +

Resumo

+ +

A propriedade CSS font-weight especifica o peso ou a intensidade da fonte (ex.: negrito). Algumas fontes oferecem apenas as opções normal e negrito.

+ +

{{cssinfo}}

+ +

Sintaxe

+ +
font-weight: normal;
+font-weight: bold;
+
+/* Relativo ao elemento pai */
+font-weight: lighter;
+font-weight: bolder;
+
+font-weight: 100;
+font-weight: 200;
+font-weight: 300;
+font-weight: 400;
+font-weight: 500;
+font-weight: 600;
+font-weight: 700;
+font-weight: 800;
+font-weight: 900;
+
+/* Valores globais */
+font-weight: inherit;
+font-weight: initial;
+font-weight: unset;
+
+ +

Valores

+ +
+
normal
+
Peso normal. O mesmo que 400.
+
bold
+
Peso negrito. O mesmo que 700.
+
lighter
+
Um peso de fonte mais claro que o elemento pai (dentre os pesos disponíveis da fonte).
+
bolder
+
Um peso de fonte mais escuro que o elemento pai (dentre os pesos disponíveis da fonte).
+
100, 200, 300, 400, 500, 600, 700, 800, 900
+
Pesos numéricos para fontes que oferecem mais que normal e negrito.
+
+ +

Contingência

+ +

Caso o dado peso solicitado não esteja disponível, a seguinte heurística é usada para determinar o peso efetivo a ser usado:

+ +
    +
  • Se solicitado um peso maior que 500, usa-se o próximo peso mais escuro (ou, se não houver, usa-se o próximo mais claro).
  • +
  • Se solicitado um peso menor que 400, usa-se o próximo peso mais claro  (ou, se não houver, usa-se o próximo mais escuro).
  • +
  • Se solicitado o peso 400, usa-se o peso 500. Se 500 não estiver disponível, usa-se a heurística para peso menor do que 500.
  • +
  • Se solicitado o peso 500, usa-se o peso 400. Se 400 não estiver disponível, usa-se a heurística para peso menor do que 400.
  • +
+ +

Isto significa que para fontes que oferecem apenas normal e negrito, 100-500 significa normal, e 600-900 significa negrito.

+ +

Significado de pesos relativos

+ +

Quando for solicitado lighter ou bolder, a seguinte tabela é usada para calcular o peso absoluto do elemento:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Valor herdadobolderlighter
100400100
200400100
300400100
400700100
500700100
600900400
700900400
800900700
900900700
+ +

Mapeamento de nomes comuns de pesos

+ +

Os valores de 100 a 900 correspondem grosseiramente aos seguintes nomes comuns de pesos:

+ +
+
100
+
Thin (Hairline)
+
200
+
Extra Light (Ultra Light, Ultra Fino)
+
300
+
Light (Fino)
+
400
+
Normal
+
500
+
Medium (Médio)
+
600
+
Semi Bold (Demi Bold, Semi Negrito)
+
700
+
Bold (Negrito)
+
800
+
Extra Bold (Ultra Bold, Super Negrito)
+
900
+
Black (Heavy)
+
+ +

Interpolação

+ +

Um valor de font-weight é interpolado com passos discretos (múltiplos de 100). A interpolação acontece no espaço de números reais e depois é feita uma conversão para números inteiros por arredondamento para o múltiplo de 100 mais próximo. Valores exatamente entre dois múltiplos de 100 são arredondados para mais.

+ +

Sintaxe formal

+ +
{{csssyntax}}
+ + +

Exemplos

+ +

HTML

+ +
<p>
+  Alice was beginning to get very tired of sitting by her sister on the
+  bank, and of having nothing to do: once or twice she had peeped into the
+  book her sister was reading, but it had no pictures or conversations in
+  it, 'and what is the use of a book,' thought Alice 'without pictures or
+  conversations?'
+</p>
+
+<div>I'm heavy<br/>
+  <span>I'm lighter</span>
+</div>
+
+ +

CSS

+ +
/* Set paragraph text to be bold. */
+p {
+  font-weight: bold;
+}
+
+/* Set div text to two steps darker than
+   normal but less than a standard bold. */
+div {
+ font-weight: 600;
+}
+
+/* Sets text enclosed within span tag
+   to be one step lighter than the parent. */
+span {
+  font-weight: lighter;
+}
+ +

Result

+ +

{{EmbedLiveSample("Exemplos","400","300")}}

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçõesStatusComentário
{{SpecName('CSS3 Fonts', '#font-weight-prop', 'font-weight')}}{{Spec2('CSS3 Fonts')}}Sem alterações.
{{SpecName('CSS3 Transitions', '#animatable-css', 'font-weight')}}{{Spec2('CSS3 Transitions')}}Permite animação do atributo font-weight.
{{SpecName('CSS2.1', 'fonts.html#propdef-font-weight', 'font-weight')}}{{Spec2('CSS2.1')}}Sem alterações.
{{SpecName('CSS1', '#font-weight', 'font-weight')}}{{Spec2('CSS1')}} 
+ +

Compatibilidade de browser

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico2.0{{CompatGeckoDesktop(1.0)}}3.03.51.3
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Suporte básico1.0{{CompatGeckoMobile(1.0)}}6.06.03.1
+
diff --git a/files/pt-br/web/css/general_sibling_combinator/index.html b/files/pt-br/web/css/general_sibling_combinator/index.html new file mode 100644 index 0000000000..e718cb7283 --- /dev/null +++ b/files/pt-br/web/css/general_sibling_combinator/index.html @@ -0,0 +1,117 @@ +--- +title: General sibling selectors +slug: Web/CSS/General_sibling_combinator +translation_of: Web/CSS/General_sibling_combinator +--- +
{{CSSRef("Selectors")}}
+ +

Resumo

+ +

O combinador geral de irmãos (~) separa dois seletores e corresponde ao segundo elemento somente se ele for precedido pelo primeiro, e ambos compartilham um pai comum.

+ +

Sintaxe

+ +
elemento_anterior ~ elemento_alvo { propriedades de estilo }
+
+ +

Exemplo

+ +
p ~ span {
+  color: red;
+}
+ +
<span>Este não é vermelho.</span>
+<p>Aqui temos um parágrafo.</p>
+<code>Aqui temos um pouco de código.</code>
+<span>E aqui há um span vermelho!</span>
+<code>Mais código...</code>
+<span>E este também é um span vermelho!</span>
+
+ +

{{ EmbedLiveSample('Example', 280, 120) }}

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSS4 Selectors', '#general-sibling-combinators', 'following-sibling combinator') }}{{Spec2('CSS4 Selectors')}}Renomeia o combinador como "irmão subsequente".
{{ SpecName('CSS3 Selectors', '#general-sibling-combinators', 'general sibling combinator') }}{{Spec2('CSS3 Selectors')}}Definição inicial.
+ + + +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1.0{{CompatVersionUnknown}}{{CompatGeckoDesktop("1")}}793
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureFirefox Mobile (Gecko)AndroidEdgeIE PhoneOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

 

+ +

Veja mais

+ + diff --git a/files/pt-br/web/css/getting_started/cascading_and_inheritance/index.html b/files/pt-br/web/css/getting_started/cascading_and_inheritance/index.html new file mode 100644 index 0000000000..90723ea85c --- /dev/null +++ b/files/pt-br/web/css/getting_started/cascading_and_inheritance/index.html @@ -0,0 +1,127 @@ +--- +title: Cascata e herança +slug: Web/CSS/Getting_Started/Cascading_and_inheritance +tags: + - Guía + - Iniciante +translation_of: Learn/CSS/Building_blocks/Cascade_and_inheritance +--- +

{{ CSSTutorialTOC() }}

+ +

{{ previousPage("/en-US/docs/Web/Guide/CSS/Getting_Started/How_CSS_works", "How CSS works.")}}Essa é a quarta seção do  Primeiros Passos (Tutorial CSS); Ela descreve como folhas de estilos interagem em cascata e como elementos herdam os estilos dos seus pais. Você pode usar herança para alterar o estilo de varios elementos da sua página de uma unica vez.

+ +

Informação: Cascata e Herança

+ +

O estilo final de um elemento pode ser setado em varios locais diferentes, que interagem entre si de uma forma complexa. Está forma de interação torna o CSS poderoso, mas pode torna-lo confuso e dificil de depurar.

+ +

Existem três fontes principais de estilos que constituem a cascata. São elas:

+ +
    +
  • Os estilos padrões do navegador;
  • +
  • Os estilos especificados pelos usarios que estão lendo o documento;
  • +
  • Os estilos criados pelo desenvolvedor. Que podem ser incluidos em três locais: +
      +
    • Em um arquivo externo: Este tutorial utiliza principalmente este método de definição de estilos
    • +
    • No inico do documento: Este método é usado apenes para estilos que se aplicam a uma única página.
    • +
    • Em um elemento específico: Este método é pouco recomendado, mas pode ser utilizado para testes.
    • +
    +
  • +
+ +

O estilo do usuario modificam o estilo padão do navegador e o estilo do desenvolvedor da página modifica ambos os outros estilos. Neste tutorial você estará desenvolvendo as folhas de estilos.

+ +
+
Exemplo
+ +

Quando você ler este documento em um navegador, parte dos estilos dele são definidos pelo próprio navegador.

+ +

Parte pode ser definida em configurações personanizadas no navegador. No Firefox, esta configurações podem ser personalizadas na janela de preferências, ou você pode especificar os estilos no arquivo userContent.css do seu navegador.

+ +

Parte dos estilos vem de folhas de estilo ligadas ao documento pelo servidor da wiki.

+
+ +

Quando você abre o documento de exemplo em seu navegador, alguns elementos {{ HTMLElement("strong") }}  vem em negrito. Isto vem das configurações padrão do seu navegador.

+ +

Os {{ HTMLElement("strong") }} são vermelhos. Isto vem da sua própria folha de estilo (previamente definida).

+ +

Os {{HTMLElement ("strong")}} elementos também herdam muito do {{HTMLElement ("p")}} estilo do elemento, porque eles são seus filhos. Da mesma forma, o {{HTMLElement ("p")}} elemento herda grande parte da {{HTMLElement ("body")}} estilo do elemento.

+ +

Para os estilos em cascata, as folhas de estilo do autor têm prioridade, depois as folhas de estilo leitor, e enfim os padrões do navegador.

+ +

Para estilos herdados, o estilo próprio de um nó filho tem prioridade sobre estilo herdado de seu pai.

+ +

Estas não são as únicas prioridades a serem aplicadas. Mais tarde, uma página deste tutorial explicará.

+ +

Mais detalhes

+ +
+

CSS também fornece uma maneira para que o leitor anule o estilo do autor do documento, usando a palavra-chave! Important. 

+ +

Isto significa que, como autor do documento, você não poderá prever exatamente o que os leitores irão ver.

+ +

Se você quiser saber todos os detalhes da cascata e herança, consulte  Assigning property values, Cascading, and Inheritance na especificação do CSS

+
+ +

Ação: Usando herança

+ +
    +
  1. Edite o seu arquivo CSS.
  2. +
  3. Adicione esta linha, copiando e colando-lo. Realmente não importa se você adicioná-lo acima ou abaixo da linha que já está lá. No entanto, adicionando-o no topo é mais lógico, porque em seu documento a {{ HTMLElement("p") }} elemento pai do {{ HTMLElement("strong") }} element: +
    p {color: blue; text-decoration: underline;}
    +
    +
  4. +
  5. Agora atualize seu navegador para ver o efeito no seu documento de amostra. O subjacente afeta todo o texto no parágrafo, incluindo as letras iniciais. Os elementos {{ HTMLElement("strong") }} herdaram o estilo sublinhado a partir de seu elemento pai {{ HTMLElement("p") }}.
    + +

    Mas os elementos {{ HTMLElement("strong") }} ainda são vermelhos. A cor vermelha é o seu próprio estilo, por isso tem prioridade sobre a cor azul de seu elemento pai {{ HTMLElement("p") }}.

    +
  6. +
+ + +
+ + + + + + + + +
Antes
Cascading Style Sheets
+ + + + + + + + +
Depois
Cascading Style Sheets
+ +
+
Desafio
+Mude o seu estilo de modo que somente as letras vermelhas sublinhadas: + + + + + + + +
Cascading Style Sheets
+ +
+
Possible solution
+ +

Move the declaration for underlining from the rule for {{ HTMLElement("p") }} to the one for {{ HTMLElement("strong") }}. The resulting file looks like this:

+ +
p {color: blue; }
+strong {color: red; text-decoration: underline;}
+
+ +

 

+Hide solution
+Veja a solução do desafio.
+ +

Qual o próximo?

+ +

{{ nextPage("/en-US/docs/Web/Guide/CSS/Getting_Started/Selectors", "Selectors")}} Sua folha de estilo de amostra especifica estilos para as tags, <p> e <strong>, mudando o estilo dos elementos correspondentes em todo o documento. A próxima seção descreve como especificar mais seletores.

diff --git a/files/pt-br/web/css/getting_started/como_css_funciona/index.html b/files/pt-br/web/css/getting_started/como_css_funciona/index.html new file mode 100644 index 0000000000..d8759320b8 --- /dev/null +++ b/files/pt-br/web/css/getting_started/como_css_funciona/index.html @@ -0,0 +1,125 @@ +--- +title: Como o CSS funciona +slug: Web/CSS/Getting_Started/Como_CSS_funciona +tags: + - 'CSS:PrimeirosPassos' + - Guía + - Iniciante + - Web +translation_of: Learn/CSS/First_steps/How_CSS_works +--- +

{{ CSSTutorialTOC() }}

+ +

{{ previousPage("/en-US/docs/Web/Guide/CSS/Getting_Started/Why_use_CSS", "Why use CSS?") }} Essa terceira seção do tutorial CSS Getting Started mostra como o CSS funciona no seu navegador e a finalidade do Modelo de Objeto de Documento (DOM). Você vai aprender também como analizar seu documento de exemplo. 

+ +

Informação: Como o CSS funciona

+ +

Quando um navegador exibe um documento, ele deve combinar o conteúdo do documento com as informações de estilo. Ele processa o documento em duas etapas:

+ +
    +
  1. O navegador converte a linguagem de marcação e o CSS  no DOM (Modelo de Objeto de Documento). O DOM representa o documento na memória do computador. Ele combina o conteúdo do documento com seu estilo.
  2. +
  3. O navegador exibe o conteúdo do DOM.
  4. +
+ +

Uma linguagem de marcação utiliza elementos para definir a estrutura do documento. Você marca um elemento usando tags, que são sequências que começam com '<' e terminam com '>'. A maioria dos elementos possui tags emparelhadas, uma tag de início e uma tag final. Para a tag inicial, coloque o elemento entre '<' e '>'. Para a tag final, coloque um '/' depois do '<' e antes do nome do elemento.

+ +

Dependendo da linguagem de marcação, alguns elementos possuem apenas uma tag de início, ou uma única tag em que '/' vem após o nome do elemento. Um elemento pode também ser um recipiente e incluir outros elementos entre sua tag inicial e final. Lembre-se de sempre fechar as tags dentro do recipiente.

+ +

O DOM tem uma estrutura de árvore. Cada elemento, atributo e execução de texto na linguagem de marcação se torna um nó na estrutura da árvore. Os nós são definidos pelas suas relações com outros nós do DOM. Alguns elementos são pais de nós filhos, e nós filhos possuem irmãos.

+ +

Entender o DOM ajuda você no design, na depuração e manutenção do seu CSS, porque o DOM é onde o CSS e o conteúdo do documento se encontram.

+ +
+
Exemplo
+No seu documento de exemplo, a tag <p>  e seu final </p> criam um recipiente: + +
<p>
+  <strong>C</strong>ascading
+  <strong>S</strong>tyle
+  <strong>S</strong>heets
+</p>
+
+ +

Exemplo em tempo real

+ +

http://jsfiddle.net/djaniketster/6jbpS/

+ +

No Dom, o nó 'P' correspondente é um pai. Seus filhos são os nós 'strongs' e os nós de texto. Os nós 'strong'  são eles próprios pais, com nós de texto como filhos.

+ +
P
+├─STRONG
+│ └─"C"
+├─"ascading"
+├─STRONG
+│ └─"S"
+├─"tyle"
+├─STRONG
+│ └─"S"
+└─"heets"
+
+ +

Ação: Analisando um DOM

+ +

Utilizando Inspetor DOM

+ +

Para analisar um DOM, você precisa de um programa especial. Você pode utilizar o add-on Inspetor DOM do Mozilla (DOMi)  para analisar um DOM. Você apenas precisa instalar o add-on (veja mais detalhes abaixo).

+ +
    +
  1. Use seu navegador Mozilla para abrir seu documento HTML de exemplo.
  2. +
  3. Na barra de menu do seu navegador, escolha Ferramentas  > Inspetor DOM, ou Ferramentas > Desenvolvimento Web > Inspetor DOM. +
    +
    Mais detalhes
    + +

    Se o seu navegador Mozilla não ter o DOMi, você pode instalá-lo a partir do site de Add-ons  e reiniciar seu navegador.  Depois, retorne para esse tutorial.

    + +

    Se você não quiser instalar o DOMi ( ou você está usuando um navegador que não seja Mozilla), você pode usar Raio-X Goggles na Web, conforme descrito na próxima seção. Ou você pode pular essa seção e ir direto para a próxima página. Ignorar essa seção não interfere no restante do tutorial.

    +
    +
  4. +
  5. No DOMi, expanda o nó do seu documento clicando em suas flechas. +

    Nota:  Espaçamentos em seu HTML pode fazer com que DOMi mostre alguns nós vazios de textos, que você pode ignorar.

    + +

    Parte do resultado você deverá ficar como mostrado abaixo, dependendo de qual nó você tenha expandido:

    + +
    │ ▼╴P
    +│ │ │ ▼╴STRONG
    +│ │ └#text
    +│ ├╴#text
    +│ ►╴STRONG
    +│ │
    + +

    Ao selecionar qualquer nó, você pode usar o painel do lado direito do DOMi para saber mais sobre o nó. Por exemplo, quando você seleciona um nó de texto, DOMi exibe o texto no painel do lado direito.

    + +

    Quando você seleciona um nó de elemento, DOMi analisa e fornece uma enorme quantidade de informações em seu painel do lado direito. Informação de estilo é apenas parte da informação que ele fornece.

    +
  6. +
+ +
+
Desafio
+ +

No DOMi, clique em um nó STRONG.

+ +

Use o painel do lado direito do DOMi para descobrir onde a cor do nó está definida como vermelho, e onde sua aparência é mais arrojada do que um texto normal.

+ + +
+
Possible solution
+ +

In the menu above the right-hand pane, choose CSS Rules. You see two items listed, one that references an internal resource and one that references your stylesheet file. The internal resource defines the font-weight property as bolder; your stylesheet defines the color property as red.

+Hide solution
+Veja a solução para o desafio.
+ +

Usando Raio-X Goggles da Web

+ +

Raio-X Goggles da Web exibe menos informação do que o Inspetor DOM, mas é mais simples de instalar e usar.

+ +
    +
  1. Vá para a página inicial do Raio-X Goggles da Web.
  2. +
  3. Arraste o link do bookmarklet na página para a barra de ferramentas do seu navegador.
  4. +
  5. Abra o seu documento HTML de exemplo.
  6. +
  7. Ative o Raio-X Goggles da Web clicando no bookmarklet na sua barra de ferramentas.
  8. +
  9. Mova o ponteiro do mouse ao redor sobre o documento para ver os elementos.
  10. +
+ +

O que vem depois?

+ +

{{ nextPage("/en-US/docs/Web/Guide/CSS/Getting_Started/Cascading_and_inheritance", "Cascading & Inheritance") }}Se você aceitou o desafio, você viu que as informações de estilo de mais de um ligar interagem para criar o estilo final para um elemento. A próxima página explica mais sobre essas interações.

diff --git a/files/pt-br/web/css/getting_started/index.html b/files/pt-br/web/css/getting_started/index.html new file mode 100644 index 0000000000..bca1143a34 --- /dev/null +++ b/files/pt-br/web/css/getting_started/index.html @@ -0,0 +1,97 @@ +--- +title: Iniciando com o CSS +slug: Web/CSS/Getting_Started +tags: + - CSS + - Guia(2) + - Guía + - Iniciante + - Web +translation_of: Learn/CSS/First_steps +--- +

 

+ +

Introdução

+ +

Esse tutorial é uma introdução ao Cascading Style Sheets (CSS) e aos seus recursos básicos, com exemplos práticos que você mesmo pode tentar no seu próprio computador. Está dividido em duas partes:

+ +
    +
  • A Parte I ilustra as características padrão do CSS que funcionam em todos os navegadores Mozilla e também em qualquer outro dentre os mais modernos.
  • +
+ +
    +
  • A Parte II conta com alguns exemplos de características especiais que funcionam nos navegadores Mozilla mas não necessariamente em outros ambientes.
  • +
+ +

Esse tutorial é baseado na Especificação do CSS 2.1.

+ +

Quem deve usar esse tutorial?

+ +

Esse tutorial é, principalmente, para iniciantes no CSS.

+ +

Se você é um iniciante, utilize a parte I deste tutorial para entender o CSS e como usá-lo. Depois utilize a parte II para entender seu escopo nas plataformas Mozilla.

+ +

Se você já conhece alguma coisa de CSS, sinta-se à vontade para pular as partes deste tutorial que já conhece, focando apenas no que interessa.

+ +

Se você já é um desenvolvedor CSS experiente mas não com Mozilla, você pode pular para a parte II.

+ +

O que você precisa saber antes de começar?

+ +

Para seguir a maior parte deste tutorial você precisa de um editor de texto e, especificamente para a parte II, um navegador Mozilla (Firefox, Camino ou SeaMonkey). Você também vai precisar saber como utilizá-los.

+ +

Se você não quiser trabalhar com arquivos, então você pode apenas ler o tutorial e observar as imagens, embora essa seja a maneira menos proveitosa de se aprender.

+ +

Algumas partes desse tutorial exigem outro software Mozilla, mas elas são opcionais. Se você não quiser baixar este outro software Mozilla, você pode ignorá-las. O software referenciado por esse tutorial inclui:

+ + + +

Nota: O CSS fornece alguns modos de se trabalhar com cores e algumas partes desse tutorial dependem de cores. Para que você possa seguir facilmente por essas partes, você vai precisar de um monitor colorido e visão colorida normal.

+ +

Como usar esse tutorial

+ +

Para usar esse tutorial, leia as páginas cuidadosamente e em sequência. Se você perder alguma página pode ser que encontre alguma dificuldade para entender as seguintes.

+ +

Em cada página, use a sessão de Informação para entender como o CSS trabalha. Use a sessão de Ação para tentar usar o CSS no seu próprio computador.

+ +

Para testar seu entendimento, faça o desafio do fim de cada página. Os links para as soluções podem ser encontrados no próprio desafio, dessa forma você não precisa olhá-las caso não queira.

+ +

Para entender mais do CSS, leia as informações que você pode encontrar nos campos com a legenda Mais detalhes (More details). Utilize os links para encontrar informações de referência sobre o CSS.

+ +

Parte I do Tutorial

+ +

Uma guia básico passo a passo do CSS

+ +
    +
  1. O que é o CSS
  2. +
  3. Porque usar o CSS
  4. +
  5. Como o CSS funciona
  6. +
  7. Cascata e herança
  8. +
  9. Seletores
  10. +
  11. CSS legível
  12. +
  13. Estilos de texto
  14. +
  15. Cores
  16. +
  17. Conteúdo
  18. +
  19. Listas
  20. +
  21. Caixas
  22. +
  23. Layout
  24. +
  25. Tabelas
  26. +
  27. Mídia
  28. +
+ +

Parte II do Tutorial

+ +

Exemplos do uso do CSS juntamente com outras tecnologias

+ +
    +
  1. JavaScript
  2. +
  3. Gráficos SVG
  4. +
  5. Dados XML
  6. +
  7. Ligações XBL
  8. +
  9. Interfaces de usuário XUL
  10. +
+ +

{{ CSSTutorialTOC() }}

+ +

{{ languages( { "es": "es/CSS/Introducción", "de": "de/CSS/Einführung", "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", "pt": "pt/CSS/Como_come\u00e7ar", "zh-cn": "cn/CSS/\u5f00\u59cb" } ) }}

diff --git a/files/pt-br/web/css/getting_started/javascript/index.html b/files/pt-br/web/css/getting_started/javascript/index.html new file mode 100644 index 0000000000..e4ceadbb9b --- /dev/null +++ b/files/pt-br/web/css/getting_started/javascript/index.html @@ -0,0 +1,139 @@ +--- +title: JavaScript e CSS +slug: Web/CSS/Getting_Started/JavaScript +translation_of: Learn/JavaScript/Client-side_web_APIs/Manipulating_documents +--- +

{{ CSSTutorialTOC() }}

+

Esta é a pirmeira sessão da Parte II do Tutorial de CSS. A parte II consém alguns exemplos que mostram o escopo do CSS usado com outras tecnologias web e Mozilla.

+

Cada página da Parte II ilustra como o CSS interagem com outras tecnologias. Essas páginas não destinam-se a ensiná-lo como usar outras tecnologias. Para aprender sobre elas com detalhes, vá para os outros tutoriais.

+

Em vez disso, estas páginas são usadas para ilustrar os diversos usos do CSS. Para usar estas páginas, você deve ter algum conhecimento de CSS, mas você não precisa de nenhum conhecimento de outras tecnologias.

+

Sessão Anterior (da Parte I): Media
+ Próxima sessão: SVG

+

Informação: JavaScript

+

JavaScript é um programming language. JavaScript é largamente utilizado para pronmover interatividade em web sites e aplicações.

+

JavaScript pode interagir com stylesheets, permitindo a você criar programas que mudam o eastilo de um documento de forma dinâmica

+

Há três formas de fazer isso:

+
    +
  • Trabalhando com lista de documentos de stylesheets—por exemplo: adicionando, removendo ou adicionando uma stylesheet.
  • +
  • Trabalhando com as regras em uma stylesheet—por exemplo: adicionando, removendo ou modificando uma regra.
  • +
  • Trabalhando com um documento individual na DOM—modificando seu estilo independentemente do stylesheetsdo documento.
  • +
+ + + + + + + +
+ Mais detalhes
Para mais informações sobre JavaScript, veja a página JavaScript nesta wiki.
+

Ação: Uma demonstração de  JavaScript

+

Faça um novo documento em HTML, doc5.html. Copie e cole o conteúdo daqui, tenha certeza de rolar para copiar todo o código:

+
+
<!DOCTYPE html>
+<html>
+
+<head>
+<title>Mozilla CSS Getting Started - JavaScript demonstration</title>
+<link rel="stylesheet" type="text/css" href="style5.css" />
+<script type="text/javascript" src="script5.js"></script>
+</head>
+
+<body>
+<h1>JavaScript sample</h1>
+
+<div id="square"></div>
+
+<button type="button" onclick="doDemo(this);">Click Me</button>
+
+</body>
+</html>
+
+
+

Crie um novo arquivo  CSS, style5.css. Copie e cole o conteúdo daqui:

+
+
/*** JavaScript demonstration ***/
+#square {
+  width: 20em;
+  height: 20em;
+  border: 2px inset gray;
+  margin-bottom: 1em;
+}
+
+button {
+  padding: .5em 2em;
+}
+
+
+

Crie um novo arquivo de texto, script5.js. Coie e cole o conteúdo daqui:

+
+
// JavaScript demonstration
+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 Browser e pressione o botão.

+

Esta wiki não suporta JavaScript nas páginas, então não é possível mostrar uma demonstração aqui. parece algo assim, antes e depois de você pressionar o botão:

+ + + + + + + +
+ + + + + + +
+

JavaScript demonstration

+
+
+ + + + + + +
+

JavaScript demonstration

+
+
+
+ Notas importantes sobre esta demonstração: +
    +
  • Os links do documento HTML document linca a como usual, e também linca o script.
  • +
  • O script trabalha com elementos individuais no DOM. Ele modifica o square's style diretamente. Ele modifica o estilo dos botões indiretamente mudando um atributo.
  • +
  • Em JavaScript, document.getElementById("square") é similar em função ao seletor CSS #square.
  • +
  • Em JavaScript, backgroundColor corresponde à propriedade CSS background-color. JavaScript não permite hífens em nomes, então "camelCase" é usada no lugar dele.
  • +
  • Seu browser tem uma regra built-in CSS para button{{ mediawiki.external('disabled=\"true\"') }} ela muda a aparência dos botões quando está disabilitado.
  • +
+
+ + + + + + + +
+ Desafio
+

Mude o script e então o square salta para a direita em 20 em quando muda as cores, e salta de volta depois.

+
+

Veja a solução deste desafio.

+

O que vem agora?

+

Se você teve dificuldade para entender esta página, ou se tem algum coment[ario sobre, por favor, contribua nesta página de Discussão.

+

Nesta deminstração, o arquivo HTML linca o the script apesar do botão de elementos usar script. Mozilla extende CSS então consegue lincar o código JavaScript (e também conteúdo e outras stylesheets) para selecionar elementos. A próxima página demonstra isso: XBL bindings

diff --git a/files/pt-br/web/css/getting_started/lists/index.html b/files/pt-br/web/css/getting_started/lists/index.html new file mode 100644 index 0000000000..481c1f58c5 --- /dev/null +++ b/files/pt-br/web/css/getting_started/lists/index.html @@ -0,0 +1,271 @@ +--- +title: Manipulando Listas +slug: Web/CSS/Getting_Started/Lists +translation_of: Learn/CSS/Styling_text/Styling_lists +--- +

{{ CSSTutorialTOC() }}

+ +

{{ previousPage("/en-US/docs/Web/Guide/CSS/Getting_Started/Content", "Content") }}

+ +

Este é o 10º seção do CSS Introdução tutorial; ele descreve como você pode usar CSS para especificar o aparecimento de listas. Você cria um novo documento de amostra contendo listas, e um novo estilo que os estilos das listas.

+ +

Informação: Lists

+ +

Se você aceitou o desafio na última seção, em seguida, você viu como você pode adicionar conteúdo antes de qualquer elemento para exibi-lo como um item da lista.

+ +

CSS proporciona propriedades especiais que são projetados para listas. Geralmente é mais conveniente usar estas propriedades sempre que puder.

+ +

Para especificar o estilo para uma lista, use o {{cssxref ("list-style")}} propriedade para especificar o tipo de marcador.

+ +

O seletor na sua regra de CSS pode selecionar os elementos de item de lista (por exemplo, {{HTMLElement ("li")}}), ou pode selecionar o elemento primário da lista (por exemplo, {{HTMLElement ("ul")}}) de modo a que os elementos da lista herdam o modelo.

+ +

Listas não ordenadas

+ +

Em uma lista desordenada, cada item da lista é marcado da mesma forma.

+ +

CSS tem três tipos de marcadores, e aqui está como seu navegador exibe-os:

+ +
    +
  • disc
  • +
  • circle
  • +
  • square
  • +
+ +

        none

+ +

Alternativamente, você pode especificar o URL de uma imagem.

+ +
+
Exemplo
+ +

Essas regras especificam diferentes marcadores para diferentes classes de item da lista:

+ +
li.open {list-style: circle;} 
+li.closed {list-style: disc;}
+
+ +

Quando estas classes são usadas em uma lista, que distinguir entre os itens abertos e fechados (por exemplo, em uma lista de tarefas):

+ +
<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 pode parecer:

+ +

{{EmbedLiveSample ('Listas_não_ordenadas', '', '', '')}}

+
+ +

Listas ordenadas

+ +

Em uma listaordenada , cada item da lista é marcado diferentemente para mostrar a sua posição na sequência.

+ +

Use a propriedade {{cssxref ("list-style")}} para especificar o tipo de marcador:

+ +
    +
  • decimal
  • +
  • lower-roman
  • +
  • upper-roman
  • +
  • lower-latin
  • +
  • upper-latin
  • +
+ +
+
Exemplo
+ +

Esta regra especifica que em {{HTMLElement ("OL")}} elementos com a classe informações, os itens são identificados com letras maiúsculas.

+ +
<ol class="info">
+  <li>Lorem ipsum</li>
+  <li>Dolor sit</li>
+  <li>Amet consectetuer</li>
+  <li>Magna aliquam</li>
+  <li>Autem veleum</li>
+</ol>
+ +
ol.info {list-style: upper-latin;}
+
+ +

O {{HTMLElement ("LI")}} elementos da lista herdam esse estilo:

+ +

{{EmbedLiveSample ('Listas_ordenadas', '', '', '')}}

+
+ +
+
Mais detalhes
+ +

O {{cssxref ("list-style")}} propriedade é uma propriedade taquigrafia. Em folhas de estilo complexas você pode preferir usar propriedades separadas para definir valores separados. Para obter links para essas propriedades separadas, e mais detalhes de como CSS especifica listas, consulte o {{cssxref ("list-style")}} página de referência.

+ +

Se você estiver usando uma linguagem de marcação como HTML que fornece etiquetas convencionais para não-ordenada ({{HTMLElement ("ul")}}) e ordenou ({{HTMLElement ("ol")}}) listas, então é uma boa prática para usar as marcas na forma como eles se destinam. No entanto, você pode usar CSS para fazer {{HTMLElement ("ul")}} exibição ordenada e {{HTMLElement ("ol")}} visualização não ordenada, se desejar.

+ +

Browsers diferem na maneira de implementar os estilos para listas. Não espere que sua folha de estilo dê resultados idênticos em todos os navegadores.

+
+ +

Contadores

+ +
+

Nota:  Alguns navegadores não suportam contadores. O conteúdo CSS e compatibilidade do navegador página no site de modo Quirks contém um gráfico detalhado de compatibilidade do navegador para este e outros recursos CSS. Páginas individuais na referência CSS neste local também têm tabelas de compatibilidade do navegador.

+
+ +

Você pode usar contadores para numerar quaisquer elementos, não somente itens da lista. Por exemplo, em alguns documentos você pode querer numerar cabeçalhos ou parágrafos.

+ +

Para especificar a numeração, você precisa de um contador com um nome que você especificar.

+ +

Em alguns elementos antes da contagem é começar, reinicie o contador com a propriedade {{cssxref ("counter-reset")}} eo nome do seu contador. O pai dos elementos que você estiver contando é um bom lugar para fazer isso, mas você pode usar qualquer elemento que vem antes os itens da lista.

+ +

Em cada elemento que o contador é incrementado, use a propriedade {{cssxref ("contra-incremento")}} eo nome do seu contador.

+ +

Para mostrar seu contador, adicione {{cssxref (":: before")}} ou {{cssxref (":: after")}} para o selector e usar o conteúdo da propriedade (como você fez na página anterior, Conteúdo) .

+ +

No valor do conteúdo de propriedade, especifique counter () com o nome de seu contador. Opcionalmente especifique um tipo. Os tipos são os mesmos que na lista ordenada secção acima.

+ +

Normalmente, o elemento que apresenta o contador também incrementa-lo.

+ +
+
Exemplo
+ +

Esta regra inicializa um contador para cada {{HTMLElement ("h3")}} elemento com a classe numeradas:

+ +
h3.numbered {counter-reset: mynum;}
+
+ +

 

+ +

Esta regra mostra e incrementa o contador para cada {{HTMLElement ("p")}} elemento com a classe numeradas:

+ +
<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 
+   {counter-reset: 
+mynum;} 
+p.numbered:before
+  {content: counter(mynum) ": ";
+  counter-increment: mynum;
+  font-weight: bold;}
+
+ +

O resultado se parece com isso:

+ +

{{ EmbedLiveSample("Contadores", '300', '200', '') }}

+
+ +
+
Mais detalhes
+ +

Você não pode usar os contadores a menos que você sabe que todo mundo que lê o documento tem um navegador que os suporta.

+ +

Se você é capaz de usar contadores, eles têm a vantagem de que você pode estilizar os contadores separadamente dos itens da lista. No exemplo acima, os contadores estão em negrito mas os itens da lista não são.

+ +

Você também pode usar contadores em formas mais complexas, por exemplo, para numerar seções, títulos, subtítulos e parágrafos em documentos formais. Para mais detalhes, consulte contadores automáticos e numeração em CSS Specification.

+
+ +

Listas denominadas: Ação

+ +

Crie um novo documento HTML, doc2.html. Copie e cole o conteúdo daqui:

+ +
<!DOCTYPE html>
+<html>
+  <head>
+    <meta charset="UTF-8">
+    <title>Sample document 2</title>
+    <link rel="stylesheet" href="style2.css">
+  </head>
+  <body>
+
+    <h3 id="oceans">The oceans</h3>
+    <ul>
+      <li>Arctic</li>
+      <li>Atlantic</li>
+      <li>Pacific</li>
+      <li>Indian</li>
+      <li>Southern</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:

+ +
/* numbered paragraphs */
+h3.numbered {counter-reset: mynum;}
+
+p.numbered:before {
+  content: counter(mynum) ": ";
+  counter-increment: mynum;
+  font-weight: bold;
+}
+
+ +

Se o layout e comentário não são a seu gosto, alterá-los.

+ +

Abra o documento no seu browser. Se o seu navegador suporta contadores, você verá algo parecido com o exemplo abaixo. Se seu navegador não suporta contadores, então você não ver os números (e provavelmente nem mesmo os dois pontos):

+ +

{{EmbedLiveSample ('Listas_denominadas_Ação', '300', '400', '')}}

+ +
+
Desafios
+ +

Adicione uma regra à sua folha de estilo, para numerar os oceanos usando numerais romanos de I a V:

+ + + + + + + +
+

The oceans

+ +
    +
  • Arctic
  • +
  • Atlantic
  • +
  • Pacific
  • +
  • Indian
  • +
  • Southern
  • +
+
+ +

 

+ +

Mude sua folha de estilo para identificar os títulos com letras maiúsculas em parênteses como este:

+ + + + + + + +
+

(A) The oceans

+ +

. . .

+ +

(B) Numbered paragraphs

+ +

. . .

+
+
+ +

Ver soluções para esses desafios.

+ +

Qual o proximo?

+ +

{{NextPage ("/ en-US / docs / Web / Guia / CSS / Getting_Started / Boxes", "caixas")}} Quando seu navegador exibe seu documento de amostra, ele cria espaço ao redor dos elementos quando ele coloca-los na página. A próxima página descreve como você pode usar CSS para trabalhar com as formas subjacentes de elementos, caixas.

diff --git a/files/pt-br/web/css/getting_started/oque_é_css/index.html b/files/pt-br/web/css/getting_started/oque_é_css/index.html new file mode 100644 index 0000000000..b72101c453 --- /dev/null +++ b/files/pt-br/web/css/getting_started/oque_é_css/index.html @@ -0,0 +1,111 @@ +--- +title: O que é CSS +slug: Web/CSS/Getting_Started/Oque_é_CSS +translation_of: Learn/CSS/First_steps/How_CSS_works +--- +

{{ CSSTutorialTOC() }}

+ +

{{previousPage("/en-US/docs/CSS/Getting_Started", "Getting started")}} Esta é a primeira seção do tutorial de  introdução as CSS  e explica o que é CSS. Você criará um documento simples para trabalhar com CSS nelas nas próximas seções.

+ +

O que é CSS ?

+ +

Cascading Style Sheets (CSS) é uma linguagem para especificar como os documentos são apresentados aos usuários (Estilo do documento).

+ +

Um documento é um conjunto de informações que são estruturadas utilizando uma linguagem de marcação.

+ +
+
Examples
+ +
    +
  • Um documento, é uma página da web como esta que você está lendo.
    + A informação que você vê em uma página web  é geralmente estruturado utilizando a linguagem de marcação HTML (HyperText Markup Language).
  • +
  • Dialogos, também chamados de Janelas Modais de um aplicativo,  são frequentemente documentos.
    + Tais diálogos podem também ser estruturados usando linguagem de marcação, como XUL. Este é frequentemente o caso em aplicações Mozilla, mas não é um caso comum.
  • +
+
+ +

Neste tutorial, temos boxes com o título Mais detalhes como o box abaixo, contento informações opcionais. Se você estiver com pressa para avançar com este tutorial, sinta-se a vontade para ignorar estas boxes e avançar com o tutorial, talvez lê-lo mais tarde. Caso contrário lê-los quando chegar a eles, e talvez siga os links para saber mais.

+ +
+
Mais detalhes
+ +

Um documento não é a mesma coisa que um arquivo, ele pode ou não estar armazenado em um arquivo.

+ +

Por exemplo, o texto que você está lendo agora não é armazenado em um arquivo. Quando seu navegador solicita esta pagina, o servidor consulta um banco de dados e gera o documento, reunindo partes do documento a partir de muitos arquivos. No entanto, neste tutorial você irá trabalhar com documentos que estão armazenados em arquivos.

+ +

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

+ + + + + + + + + + + + + + + + + + + + +
HTMLpara paginas web
XMLpara documentos estruturados em geral
SVGpara gráficos
XULpara interfaces de usuários em Mozilla
+ +

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

+
+ +

Apresentar um documento ao usuário significa convertê-lo em uma forma que os seres humanos possam fazer uso. Navegadores como Firefox, Chrome ou Internet Explorer, são projetados para apresentar documentos visualmente  — por exemplo, na tela de um computador, projetor ou impressora.

+ +
+
Mais detalhes
+ +

CSS não é apenas para navegadores, e nem apenas para apresentação visual. Na terminoloia formal de CSS, o programa que apresenta  um documento a um usuário  é chamado de user agent (UA), no Brasil agente de usuário. Um navegador é apenas um UA. No entanto, na parte I deste Tutorial você vai apenas trabalhar com CSS no navegador.

+ +

Para mais definições formais sobre  terminologia relacionadas com CSS, veja Definições na especificação CSS.

+
+ +

Ação: Criando um documento

+ +
    +
  1. Use seu computador para criar um novo diretório e um novo arquivo de texto dentro deste dire†ório. O arquivo terá o documento.
  2. +
  3. Copie e cole o código HTML abaixo . Salve o arquivo usando o nome doc1.html +
    <!DOCTYPE html>
    +<html>
    +  <head>
    +  <meta charset="UTF-8">
    +  <title>Documento de exemplo</title>
    +  </head>
    +
    +  <body>
    +    <p>
    +      <strong>C</strong>ascading
    +      <strong>S</strong>tyle
    +      <strong>S</strong>heets
    +    </p>
    +  </body>
    +</html>
    +
    +
  4. +
  5. No seu navegador, abra uma nova aba ou uma nova janela, e abra o arquivo que você acabou de salvar. +

    Você deve ver o texto  com as letras iniciais em negrito, como este:

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

    O que você vê no seu  navegador, pode não ser exatamente o mesmo que este, por causa das configurações em seu navegador e neste tutorial. Se existirem diferenças nas fontes espaçamentos ou cores que você vê, elas não são importantes.

    +
  6. +
+ +

O que veremos depois?

+ +

{{nextPage("/en-US/docs/CSS/Getting_Started/Why_use_CSS", "Why use CSS?")}}Seu documento ainda não usa CSS. Na próxima seção você usará CSS para especificar o estilo.

diff --git a/files/pt-br/web/css/getting_started/porque_usar_css/index.html b/files/pt-br/web/css/getting_started/porque_usar_css/index.html new file mode 100644 index 0000000000..1219d9c096 --- /dev/null +++ b/files/pt-br/web/css/getting_started/porque_usar_css/index.html @@ -0,0 +1,105 @@ +--- +title: Por que usar CSS? +slug: Web/CSS/Getting_Started/Porque_usar_CSS +translation_of: Learn/CSS/First_steps/How_CSS_works +--- +

{{ CSSTutorialTOC() }}

+ +

{{ previousPage("/en-US/docs/Web/Guide/CSS/Getting_Started/What_is_CSS", "What is CSS?") }}Esta segunda parte do  CSS Getting Started tutorial explica a relação entre as CSS e o documento. No exercício você aprenderá como criar uma folha de estilos e linka-la para o documento que você criou para sua seção.

+ +

Informação: Por que usar CSS?

+ +

As CSS são usadas para definir estilos para os seus documentos, incluindo o design, layout e as variações na exbição para diferentes dispositivos e tamanho de tela. Você pode colocar suas CSS dentro da tag <head> do seu documento com uma folha de estilos incorporada, ou anexar uma folha de estilos externa . Para linkar uma folha de estilos externa para o seu documento é simples, adicione um link para a sua folha de estilos  na tag <head> de seu documento.

+ +

Uma folha de estilo externa, tem muitas vantagens.:

+ +
    +
  • Ajuda a evitar código repetido
  • +
  • Facilita a manutenção
  • +
  • Permite fazer mudança no site inteiro alterando apenas um arquivo.
  • +
+ +
+
Exemplo
+ +

Usando CSS, você armazena as informações de estilo em arquivos comuns que todas as páginas compartilham. Por exemplo, quando você linka varios documentos para a mesma folha de estilo que define a cor dos cabeçalhos h2, você pode aplicar o estilo para tags de cabeçalho h2 globalmente alterando apenas um atributo css..

+ +

Quando um usuario exibe uma página web, o navegador do usuário carrega as informações de estilo  juntamente com o conteúdo da página.

+ +

Quando um usuário imprime uma página da web,você pode fornecer informações de estilo diferente, que faz com que a página impressa fique de fácil leitura.

+
+ +

Como o HTML e o CSS trabalham juntos? Em geral, você usa HTML para descrever o conteúdo do documento, não o estilo do documento. Você usa CSS para especificar o estilo do documento, e não o seu conteúdo.  Mais adiante neste tutorial, você verá algumas exceções a esta disposição.

+ +
+
Mais detalhes
+ +

Uma linguagem de marcação como HTML também fornece maneiras de especificar estilo.

+ +

Por exemplo, você pode usar a tag <b> para fazer o texto em negrito, e pode especificar a cor de fundo  na sua tag <body>.

+ +

Quando você usa CSS, normalmente evita usar esses recursos da linguagem de marcação, para deixar informações de estilo em um unico lugar.

+
+ +

Ação: Criando uma folha de estilo

+ +
    +
  1. Crie outro arquivo de texto no mesmo diretório que o documento doc1.html você criou na primeira seção.
  2. +
  3. Salve seu documento como: style1.css. Este arquivo será sua folha de estilos.
  4. +
  5. Em seu CSS, cole a linha abaixo, e salve o arquivo: +
    strong {color: red;}
    +
    +
  6. +
+ +

Linkando seu documento para sua folha de estilo

+ +
    +
  1. Para linkar seu documento para sua folha de estilos, edite seu arquivo HTML. Adicionando o código abaixo: +
    <!DOCTYPE html>
    +<html>
    +  <head>
    +  <meta charset="UTF-8">
    +  <title>Documento Simples com CSS</title>
    +  <link rel="stylesheet" href="style1.css">
    +  </head>
    +  <body>
    +    <p>
    +      <strong>C</strong>ascading
    +      <strong>S</strong>tyle
    +      <strong>S</strong>heets
    +    </p>
    +  </body>
    +</html>
    +
    +
  2. +
  3. Salve o arquivo e atualize seu navegador. Sua folha de estilos fez com que as letras iniciais ficassem vermelhas: + + + + + + +
    Cascading Style Sheets
    +
  4. +
+ +

{{ LiveSampleLink('Action.3A_Creating_a_stylesheet', 'View above Demo') }}

+ +
+
Desafio
+ +

Além do vermelho, as CSS permitem que você escolha alguns outros nomes de cores.

+ +

Encontre mais cinco nomes de cores que as CSS trabalham.

+ +
+
Possible solution
+ +

CSS supports common color names like orange, yellow, blue, green, or black. It also supports some more exotic color names like chartreuse, fuschia, or burlywood. See CSS Color value for a complete list as well as other ways of specifying colors.

+Hide solution
+Veja a solução para este desafio.
+ +

O que veremos?

+ +

{{nextPage("/en-US/docs/Web/Guide/CSS/Getting_started/How_CSS_works", "How CSS works.")}}Agora você tem um documento de exemplo linkando a uma folha de estilos, você está pronto para  aprender mais sobre como seu navegador trabalha e exibe um documento.

diff --git a/files/pt-br/web/css/getting_started/seletores/index.html b/files/pt-br/web/css/getting_started/seletores/index.html new file mode 100644 index 0000000000..22b53c2049 --- /dev/null +++ b/files/pt-br/web/css/getting_started/seletores/index.html @@ -0,0 +1,429 @@ +--- +title: Seletores +slug: Web/CSS/Getting_Started/Seletores +translation_of: Learn/CSS/Building_blocks/Selectors +--- +

{{ CSSTutorialTOC() }}

+ +

{{ previousPage("/en-US/docs/Web/Guide/CSS/Getting_Started/Cascading_and_inheritance", "Cascading & inheritance")}}Esta é a 5ª seção de Primeiros passos (Tutorial Css), ela explica como você pode aplicar estilos seletivamente e como diferentes tipos de seletores possuem diferentes prioridades. Você adiciona mais atributos para tags no seu documento e como você pode usa-los em sua folha de estilos.

+ +

Informações: Seletores

+ +

CSS tem sua propria terminologia para descrever a linguagem CSS. Anteriormente nesse tutorial, você criou linha no seu stylesheet como esta:

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

No CSS, este código inteiro é uma regra. Esta regra inicia com strong, que é um seletor. Ele seleciona os elementos do DOM aos quais a regra se aplica.

+ +
+
Mais detalhes
+ +

A parte dentro 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 o separa de outros pares propriedade-valor na mesma declaração.

+ +

Esse tutorial se refere ao seletor strong como um seletor de tag. A Especificação do CSS se refere a este seletor como seletor de tipo.

+
+ +

Esta página de tutorial explica mais sobre os seletores que você pode utilizar nas regras CSS.

+ +

Em adição aos nomes das tags, você pode usar valores de atributos nos seletores. Isso permite que as regras sejam mais específicas.

+ +

Dois atributos são especiais para o CSS. São eles o class e o id.

+ +

Seletores com Classe

+ +

Use o atributo class em um elemento para atribuir o elemento a uma determinada classe. O nome da classe é de sua escolha. Muitos elementos em um documento podem pertencer a mesma classe.

+ +

Em seu CSS, digite um ponto final antes do nome da classe para usar como um seletor.

+ +

Seletores com ID

+ +

Use o atributo id em um elemento para atribuir um ID a esse elemento. O nome do ID é de sua escolha e ele deve ser único no documento.

+ +

Em seu CSS, digite cerquilha (#) antes do ID quanto estiver usando em um seletor ID.

+ +
+
Exemplo
+Esta tag HTML tem tanto um atributo class quanto um atributo id: + +
<p class="chave" id="principal">
+
+ +

O valor de id, principal, precisa ser unico no documento, mas outras tags no documento podem ter o atributo class com o mesmo nome, chave.

+ +

Em uma folha de estilo CSS, esta regra torna verde todos os elementos da classe chave. (Eles podem ou não serem elementos {{ HTMLElement("p") }}.)

+ +
.chave {
+  color: green;
+}
+
+ +

Esta regra torna negrito um elemento com id principal:

+ +
#principal {
+  font-weight: bolder;
+}
+
+
+ +

Seletores de Atributo

+ +

Você não está restrito aos dois atributos especiais, class e id. Você pode especificar outros atributos usando colchetes. Dentro dos colchetes você insere o nome do atributo, opcionalmente seguido por um operador correspondente e um valor. Além disso, a seleção pode ser feita case-insensitive adicionando um "i" depois do valor, mas nem todos os browsers suportam esta funcionalidade ainda. Exemplos:

+ +
+
[disabled]
+
Seleciona todos os elementos com o atributo "disabled".
+
[type='button']
+
Seleciona todos os elementos do tipo "button".
+
[class~=key]
+
Seleciona elementos com a classe "key" (mas não ex: "keyed", "monkey", "buckeye"). Funcionalmente equivalente a .key.
+
[lang|=es]
+
Selects elements specified as Spanish. This includes "es" and "es-MX" but not "eu-ES" (which is Basque).
+
[title*="example" i]
+
Seleciona elementos cujo título contém "exemplo", ignorando maiúsculas e minúsculas. Nos navegadores que não suportam o sinalizador "i", esse seletor provavelmente não corresponderá a nenhum elemento.
+
a[href^="https://"]
+
Seleciona links seguros.
+
img[src$=".png"]
+
IIndiretamente seleciona imagens PNG; qualquer imagem que seja PNG mas que a URL não termine em ".png" (como quando elas são uma query string) não serão selecionadas.
+
+ +

Seletores de pseudo-classes

+ +

Uma pseudo-classe em CSS é uma palavra-chave adicionada aos seletores que especifica um estado especial do elemento a ser selecionado. Por exemplo  {{ Cssxref(":hover") }}, aplicará um estilo quando o usuário passar o mouse sobre o elemento especificado pelo seletor.

+ +

Pseudo-classes, juntas com pseudo-elementos, te deixa aplicar um estilo para um elemento não apenas em relação ao conteúdo da árvore do documento, mas também em relação à fatores externos como o histórico do navegador ({{ cssxref(":visited") }}, por exemplo), o estado do conteúdo (como {{ cssxref(":checked") }} no mesmo elemento do formulário), ou a posição do mouse (como {{ cssxref(":hover") }} que te permite saber se o mouse está sobre um elemento ou não). Para ver uma lista completa de seletores, visite CSS3 Selectors working spec.

+ +
+
Syntax
+ +
selector:pseudo-class {
+  property: value;
+}
+
+
+ +

Lista de pseudo-classes

+ +
    +
  • {{ Cssxref(":link") }}
  • +
  • {{ Cssxref(":visited") }}
  • +
  • {{ Cssxref(":active") }}
  • +
  • {{ Cssxref(":hover") }}
  • +
  • {{ Cssxref(":focus") }}
  • +
  • {{ Cssxref(":first-child") }}
  • +
  • {{ Cssxref(":last-child") }}
  • +
  • {{ Cssxref(":nth-child") }}
  • +
  • {{ Cssxref(":nth-last-child") }}
  • +
  • {{ Cssxref(":nth-of-type") }}
  • +
  • {{ Cssxref(":first-of-type") }}
  • +
  • {{ Cssxref(":last-of-type") }}
  • +
  • {{ Cssxref(":empty") }}
  • +
  • {{ Cssxref(":target") }}
  • +
  • {{ Cssxref(":checked") }}
  • +
  • {{ Cssxref(":enabled") }}
  • +
  • {{ Cssxref(":disabled") }}
  • +
+ +

Informação: Especificidade

+ +

Várias regras podem ter seletores que correspondem ao mesmo elemento. Se uma propriedade recebeu apenas uma regra, não há conflito e a propriedade será definida ao elemento. Se são aplicadas mais do que uma regra a um elemento e definido a mesma propriedade, então o CSS dará prioridade à regra que tem o seletor mais específico. Um seletor ID é mais específico do que um seletor de classe, pseudo-classe ou atributo, que por sua vez é mais específico do que um de tag ou de pseudo-elemento.

+ +
+
Mais detalhes
+ +

Você também pode combinar seletores, fazendo um seletor mais específico. Por exemplo, o seletor .key seleciona todos os elementos que têm a classe com o nome key. O seletor p.key seleciona só os elementos {{ HTMLElement("p") }} nomeados com a classe key.

+
+ +

Se a folha de estilo possui regras conflitantes e elas são igualmente específicas, então o CSS dará prioridade à regra que é posterior na folha de estilo.

+ +

Quando você tem um problema com regras conflitantes, tente resolvê-los tornando uma das regras mais específicas, para que ela seja priorizada. Se você não pode fazer isto, tente mover uma das regras perto do fim da folha de estilo e então ela será priorizada.

+ +

Information: Selectors based on relationships

+ +

CSS has some ways to select elements based on the relationships between elements. You can use these to make selectors that are more specific.

+ + + + + + + + + + + + + + + + + + + + + + + + + +
Common selectors based on relationships
SelectorSelects
A EAny E element that is a descendant of an A element (that is: a child, or a child of a child, etc.)
A > EAny E element that is a child (i.e. direct descendant) of an A element
E:first-childAny E element that is the first child of its parent
B + EAny E element that is the next sibling of a B element (that is: the next child of the same parent)
+ +

You can combine these to express complex relationships.

+ +

You can also use the symbol * (asterisk) to mean "any element".

+ +
+
Example
+ +

An HTML table has an id attribute, but its rows and cells do not have individual identifiers:

+ +
<table id="data-table-1">
+...
+<tr>
+<td>Prefix</td>
+<td>0001</td>
+<td>default</td>
+</tr>
+...
+
+ +

These rules make the first cell in each row underline, and the sibling of first cell in each row strikethroughted (in example 2.nd cell) . They only affect one specific table in the document:

+ +
    #data-table-1 td:first-child {text-decoration: underline;}
+    #data-table-1 td:first-child + td {text-decoration: line-through;}
+
+ +

The result looks like:

+ + + + + + + +
+ + + + + + + + +
Prefix0001default
+
+
+ +
+
More details
+ +

In the usual way, if you make a selector more specific, then you increase its priority.

+ +

If you use these techniques, you avoid the need to specify class or id attributes on so many tags in your document. Instead, CSS does the work.

+ +

In large designs where speed is important, you can make your stylesheets more efficient by avoiding complex rules that depend on relationships between elements.

+ +

For more examples about tables, see Tables in the CSS Reference page.

+
+ +

Action: Using class and ID selectors

+ +
    +
  1. Edit your HTML file, and duplicate the paragraph by copying and pasting it.
  2. +
  3. Then add id and class attributes to the first copy, and an id attribute to the second copy as shown below. Alternatively, copy and paste the entire file again: +
    <!doctype html>
    +<html>
    +  <head>
    +  <meta charset="UTF-8">
    +  <title>Sample document</title>
    +  <link rel="stylesheet" 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>
    +
    +
  4. +
  5. Now edit your CSS file. Replace the entire contents with: +
    strong { color: red; }
    +.carrot { color: orange; }
    +.spinach { color: green; }
    +#first { font-style: italic; }
    +
    +
  6. +
  7. Save the files and refresh your browser to see the result: + + + + + + + + + +
    Cascading Style Sheets
    Cascading Style Sheets
    + +

    You can try rearranging the lines in your CSS file to show that the order has no effect.

    + +

    The class selectors .carrot and .spinach have priority over the tag selector strong.

    + +

    The ID selector #first has priority over the class and tag selectors.

    +
  8. +
+ +
+
Challenges
+ +
    +
  1. Without changing your HTML file, add a single rule to your CSS file that keeps all the initial letters that same color as they are now, but makes all the other text in the second paragraph blue: + + + + + + + + + +
    Cascading Style Sheets
    Cascading Style Sheets
    +
  2. +
  3. Now change the rule you have just added (without changing anything else), to make the first paragraph blue too: + + + + + + + + + +
    Cascading Style Sheets
    Cascading Style Sheets
    +
  4. +
+ +
+
Possible solution
+ +
    +
  1. Add a rule with an ID selector of #second and a declaration color: blue;, as shown below: + +
    #second { color: blue; }
    +
    + A more specific selector, p#second also works.
  2. +
  3. Change the selector of the new rule to be a tag selector using p: +
    p { color: blue; }
    +
    +
  4. +
+Hide solution
+See a solution for the challenge.
+ +

Action: Using pseudo-classes selectors

+ +
    +
  1. Create an HTML file with following content: +
    <!doctype html>
    +<html>
    +  <head>
    +  <meta charset="UTF-8">
    +  <title>Sample document</title>
    +  <link rel="stylesheet" href="style1.css">
    +  </head>
    +  <body>
    +    <p>Go to our <a class="homepage" href="http://www.example.com/" title="Home page">Home page</a>.</p>
    +  </body>
    +</html>
    +
    +
  2. +
  3. Now edit your CSS file. Replace the entire contents with: +
    a.homepage:link, a.homepage:visited {
    +  padding: 1px 10px 1px 10px;
    +  color: #fff;
    +  background: #555;
    +  border-radius: 3px;
    +  border: 1px outset rgba(50,50,50,.5);
    +  font-family: georgia, serif;
    +  font-size: 14px;
    +  font-style: italic;
    +  text-decoration: none;
    +}
    +
    +a.homepage:hover, a.homepage:focus, a.homepage:active {
    +  background-color: #666;
    +}
    +
    +
  4. +
  5. Save the files and refresh your browser to see the result (put the mouse over the following link to see the effect): + + + + + + +
    Go to our Home page  
    +
  6. +
+ +

Action: Using selectors based on relationships and pseudo-classes

+ +

With selectors based on relationships and pseudo-classes you can create complex cascade algorithms. This is a common technique used, for example, in order to create pure-CSS dropdown menus (that is only CSS, without using JavaScript). The essence of this technique is the creation of a rule like the following:

+ +
div.menu-bar ul ul {
+  display: none;
+}
+
+div.menu-bar li:hover > ul {
+  display: block;
+}
+ +

to be applied to an HTML structure like the following:

+ +
<div class="menu-bar">
+  <ul>
+    <li>
+      <a href="example.html">Menu</a>
+      <ul>
+        <li>
+          <a href="example.html">Link</a>
+        </li>
+        <li>
+          <a class="menu-nav" href="example.html">Submenu</a>
+          <ul>
+            <li>
+              <a class="menu-nav" href="example.html">Submenu</a>
+              <ul>
+                <li><a href="example.html">Link</a></li>
+                <li><a href="example.html">Link</a></li>
+                <li><a href="example.html">Link</a></li>
+                <li><a href="example.html">Link</a></li>
+              </ul>
+            </li>
+            <li><a href="example.html">Link</a></li>
+          </ul>
+        </li>
+      </ul>
+    </li>
+  </ul>
+</div>
+
+ +

See our complete CSS-based dropdown menu example for a possible cue.

+ +

What next?

+ +

Your sample stylesheet is starting to look dense and complicated. The next section describes ways to make CSS easier to read.{{nextPage("/en-US/docs/Web/Guide/CSS/Getting_Started/Readable_CSS", "Readable CSS")}}

diff --git a/files/pt-br/web/css/grid-auto-flow/index.html b/files/pt-br/web/css/grid-auto-flow/index.html new file mode 100644 index 0000000000..ae212a18a6 --- /dev/null +++ b/files/pt-br/web/css/grid-auto-flow/index.html @@ -0,0 +1,207 @@ +--- +title: grid-auto-flow +slug: Web/CSS/grid-auto-flow +tags: + - pt-br +translation_of: Web/CSS/grid-auto-flow +--- +

A propriedade de CSS grid-auto-flow controla como o algoritmo de arrumação automática funciona, especificando exatamente como os itens fluirão no grid.

+ +
/* Keywords Chaves */
+grid-auto-flow: row;
+grid-auto-flow: column;
+grid-auto-flow: dense;
+grid-auto-flow: row dense;
+grid-auto-flow: column dense;
+
+/* Valores globais */
+grid-auto-flow: inherit;
+grid-auto-flow: initial;
+grid-auto-flow: unset;
+
+ +

{{cssinfo}}

+ +

Syntaxe

+ +

Esta propriedade pode ser de duas maneiras:

+ +
    +
  • uma única keyword (palavra-chave):  row(linha), column(coluna), ou dense(denso).
  • +
  • duas keywords (palavras-chave): row dense(linha densa) ou column dense(coluna densa).
  • +
+ +

Valores

+ +
+
row (linha)
+
Keyword (palavra-chave) que determina que o algoritmo de arrumação automática coloca os itens preenchendo cada linha de uma vez, adicionando novas linhas se necessário. Se nem row(linha) ou column(coluna) for especificado, row (linha) é assumido.
+
column (coluna)
+
É uma keyword (palavra-chave) que determina que o algoritmo de arrumação automática coloque os itens preenchendo colunas, adicionando novas se necessário.
+
+ +
+
dense (denso)
+
Keyword (palavra-chave) que determina que o algoritmo de arrumação automática use um formato de compactação "denso", que tenta preencher os espaços anteriores do grid caso receba itens menores após. Isto talvez deixe os itens fora de ordem, preenchendo espaços deixados por itens maiores.
+
Se omitido, o algoritmo "esparso" é utilizado, onde o algoritmo de arrumação somente "avança" no grid ao colocar os itens, nunca voltando para preencher os espaços. Isso garante que todos os itens colocados automaticamente apareçam "em ordem", mesmo que deixem espaçs que poderiam ser preenchidos por itens posteriores.
+
+ +

Sintaxe Formal

+ +
{{csssyntax}}
+ +

Exemplo

+ +

Conteúdo HTML

+ +
<div id="grid">
+  <div id="item1"></div>
+  <div id="item2"></div>
+  <div id="item3"></div>
+  <div id="item4"></div>
+  <div id="item5"></div>
+</div>
+<select id="direction" onchange="changeGridAutoFlow()">
+  <option value="column">column</option>
+  <option value="row">row</option>
+</select>
+<input id="dense" type="checkbox" onchange="changeGridAutoFlow()">
+<label for="dense">dense</label>
+
+ +

Conteúdo CSS

+ +
#grid {
+  height: 200px;
+  width: 200px;
+  display: grid;
+  grid-gap: 10px;
+  grid-template: repeat(4, 1fr) / repeat(2, 1fr);
+  grid-auto-flow: column;  /* or 'row', 'row dense', 'column dense' */
+}
+
+#item1 {
+  background-color: lime;
+  grid-row-start: 3;
+}
+
+#item2 {
+  background-color: yellow;
+}
+
+#item3 {
+  background-color: blue;
+}
+
+#item4 {
+  grid-column-start: 2;
+  background-color: red;
+}
+
+#item5 {
+  background-color: aqua;
+}
+ + + +

{{EmbedLiveSample("Example", "200px", "230px")}}

+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName("CSS3 Grid", "#propdef-grid-auto-flow", "grid-auto-flow")}}{{Spec2("CSS3 Grid")}}Definição Inicial
+ +

Compatibilidade de Browser

+ + + +

{{Compat("css.properties.grid-auto-flow")}}

+ +

Veja Também

+ + + + diff --git a/files/pt-br/web/css/grid-template-columns/index.html b/files/pt-br/web/css/grid-template-columns/index.html new file mode 100644 index 0000000000..f096700b56 --- /dev/null +++ b/files/pt-br/web/css/grid-template-columns/index.html @@ -0,0 +1,193 @@ +--- +title: grid-template-columns +slug: Web/CSS/grid-template-columns +tags: + - CSS + - CSS Grid +translation_of: Web/CSS/grid-template-columns +--- +

A propriedade grid-template-columns do CSS define os nomes das linhas e funções de dimensionamento (track sizing) do {{glossary("grid column", "grid columns")}}.

+ +
/* valores padrão */
+grid-template-columns: none;
+
+/* exemplos de <track-list> */
+grid-template-columns: 100px 1fr;
+grid-template-columns: [linename] 100px;
+grid-template-columns: [linename1] 100px [linename2 linename3];
+grid-template-columns: minmax(100px, 1fr);
+grid-template-columns: fit-content(40%);
+grid-template-columns: repeat(3, 200px);
+
+/* exemplos de <auto-track-list> */
+grid-template-columns: 200px repeat(auto-fill, 100px) 300px;
+grid-template-columns: minmax(100px, max-content)
+                       repeat(auto-fill, 200px) 20%;
+grid-template-columns: [linename1] 100px [linename2]
+                       repeat(auto-fit, [linename3 linename4] 300px)
+                       100px;
+grid-template-columns: [linename1 linename2] 100px
+                       repeat(auto-fit, [linename1] 300px) [linename3];
+
+/* definições de herança */
+grid-template-columns: inherit;
+grid-template-columns: initial;
+grid-template-columns: unset;
+
+ +

{{cssinfo}}

+ +

Sintaxe

+ +

Alternativas

+ +
+
none
+
Indica que não há uma grade explícita. Colunas serão automaticamente geradas e seu tamanho será determinado pela propriedade {{cssxref("grid-auto-columns")}}.
+
<length>
+
Tamanho não negativo.
+
<percentage>
+
Is a non-negative {{cssxref("percentage", "<percentage>")}} value relative to the inline size of the grid container. If the size of the grid container depends on the size of its tracks, then the percentage must be treated as auto.
+ The intrinsic size contributions of the track may be adjusted to the size of the grid container and increase the final size of the track by the minimum amount that would result in honoring the percentage.
+
<flex>
+
Is a non-negative dimension with the unit fr specifying the track’s flex factor. Each <flex>-sized track takes a share of the remaining space in proportion to its flex factor. +

When appearing outside a minmax() notation, it implies an automatic minimum (i.e. minmax(auto, <flex>)).

+
+
max-content
+
Is a keyword representing the largest maximal content contribution of the grid items occupying the grid track.
+
min-content
+
Is a keyword representing the largest minimal content contribution of the grid items occupying the grid track.
+
{{cssxref("minmax", "minmax(min, max)")}}
+
Is a functional notation that defines a size range greater than or equal to min and less than or equal to max. If max is smaller than min, then max is ignored and the function is treated as min. As a maximum, a <flex> value sets the track’s flex factor. It is invalid as a minimum.
+
auto
+
Is a keyword that is identical to maximal content if it's a maximum. As a minimum it represents the largest minimum size (as specified by {{cssxref("min-width")}}/{{cssxref("min-height")}}) of the grid items occupying the grid track.
+
+

Note: auto track sizes (and only auto track sizes) can be stretched by the {{cssxref("align-content")}} and {{cssxref("justify-content")}} properties.

+
+
{{cssxref("fit-content", "fit-content( [ <length> | <percentage> ] )")}}
+
Represents the formula min(max-content, max(auto, argument)), which is calculated similar to auto (i.e. minmax(auto, max-content)), except that the track size is clamped at argument if it is greater than the auto minimum.
+
{{cssxref("repeat", "repeat( [ <positive-integer> | auto-fill | auto-fit ] , <track-list> )")}}
+
Represents a repeated fragment of the track list, allowing a large number of columns that exhibit a recurring pattern to be written in a more compact form.
+
+ +

Sintaxe formal

+ +
{{csssyntax}}
+ +

Exemplos

+ +

CSS

+ +
#grid {
+  display: grid;
+  width: 100%;
+  grid-template-columns: 50px 1fr;
+}
+
+#areaA {
+  background-color: lime;
+}
+
+#areaB {
+  background-color: yellow;
+}
+ +

HTML

+ +
<div id="grid">
+  <div id="areaA">A</div>
+  <div id="areaB">B</div>
+</div>
+ +

Resultado

+ +

{{EmbedLiveSample("Examples", "100%", "20px")}}

+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName("CSS3 Grid", "#propdef-grid-template-columns", "grid-template-columns")}}{{Spec2("CSS3 Grid")}}Definição inicial
+ +

Compatibilidade com o navegador

+ + + +

{{Compat("css.properties.grid-template-columns")}}

+ +

Leia Mais

+ + + + diff --git a/files/pt-br/web/css/grid-template-rows/index.html b/files/pt-br/web/css/grid-template-rows/index.html new file mode 100644 index 0000000000..daff379e41 --- /dev/null +++ b/files/pt-br/web/css/grid-template-rows/index.html @@ -0,0 +1,204 @@ +--- +title: grid-template-rows +slug: Web/CSS/grid-template-rows +translation_of: Web/CSS/grid-template-rows +--- +

A propriedade grid-template-rows do CSS define o nome das linhas e funções de dimensionamento (track sizing) do {{glossary("grid rows", "grid rows")}}.

+ +

{{EmbedInteractiveExample("pages/css/grid-template-rows.html")}}

+ + + +

Syntax

+ +
/* Keyword value */
+grid-template-rows: none;
+
+/* <track-list> values */
+grid-template-rows: 100px 1fr;
+grid-template-rows: [linename] 100px;
+grid-template-rows: [linename1] 100px [linename2 linename3];
+grid-template-rows: minmax(100px, 1fr);
+grid-template-rows: fit-content(40%);
+grid-template-rows: repeat(3, 200px);
+
+/* <auto-track-list> values */
+grid-template-rows: 200px repeat(auto-fill, 100px) 300px;
+grid-template-rows: minmax(100px, max-content)
+                       repeat(auto-fill, 200px) 20%;
+grid-template-rows: [linename1] 100px [linename2]
+                       repeat(auto-fit, [linename3 linename4] 300px)
+                       100px;
+grid-template-rows: [linename1 linename2] 100px
+                       repeat(auto-fit, [linename1] 300px) [linename3];
+
+/* Valores globais */
+grid-template-rows: inherit;
+grid-template-rows: initial;
+grid-template-rows: unset;
+
+ +

Esta propriedade pode ser especificada como:

+ +
    +
  • com a palavra-chave none
  • +
  • ou um valor <track-list> 
  • +
  • ou um valor <auto-track-list> 
  • +
+ +

Valores

+ +
+
none
+
É uma palavra-chave que indica que não há uma grid explícita. Qualquer linha irá ser implicitamente gerada e seu tamanho será determinado pela a propriedade {{cssxref("grid-auto-rows")}} .
+
{{cssxref("<length>")}}
+
É um comprimento não negativo.
+
{{cssxref("percentage", "<percentagem>")}}
+
É um valor de {{cssxref("percentage", "<percentagem>")}} não negativo, relativo ao tamanho do bloco do grid contêiner. Se o tamanho do grid contêiner depender do tamanho de suas tracks, então a percentagem deve ser tratada como auto
+ As contribuições de tamanho inerentes da track podem ser ajustados ao tamanho do grid contêiner, e aumentar o tamanho final da track pelo o valor mínimo que respeitará a percentagem.
+
{{cssxref("<flex_value>","<flex>")}}
+
Is a non-negative dimension with the unit fr specifying the track’s flex factor. Each <flex>-sized track takes a share of the remaining space in proportion to its flex factor. When appearing outside a minmax() notation, it implies an automatic minimum (i.e. minmax(auto, <flex>)).
+
max-content
+
Is a keyword representing the largest maximal content contribution of the grid items occupying the grid track.
+
min-content
+
Is a keyword representing the largest minimal content contribution of the grid items occupying the grid track.
+
{{cssxref("minmax", "minmax(min, max)")}}
+
Is a functional notation that defines a size range, greater than or equal to min, and less than or equal to max. If max is smaller than min, then max is ignored and the function is treated as min. As a maximum, a <flex> value sets the track’s flex factor. It is invalid as a minimum.
+
auto
+
Is a keyword that is identical to maximal content if it's a maximum. As a minimum it represents the largest minimum size (as specified by {{cssxref("min-width")}}/{{cssxref("min-height")}}) of the grid items occupying the grid track.
+
+

Note: auto track sizes (and only auto track sizes) can be stretched by the {{cssxref("align-content")}} and {{cssxref("justify-content")}} properties.

+
+
{{cssxref("fit-content", "fit-content( [ <length> | <percentage> ] )")}}
+
Represents the formula min(max-content, max(auto, argument)), which is calculated similar to auto (i.e. minmax(auto, max-content)), except that the track size is clamped at argument if it is greater than the auto minimum.
+
{{cssxref("repeat", "repeat( [ <positive-integer> | auto-fill | auto-fit ] , <track-list> )")}}
+
Represents a repeated fragment of the track list, allowing a large number of rows that exhibit a recurring pattern to be written in a more compact form.
+
+ +

Formal syntax

+ +
{{csssyntax}}
+ +

Examples

+ +

CSS

+ +
#grid {
+  display: grid;
+  height: 100px;
+  grid-template-rows: 30px 1fr;
+}
+
+#areaA {
+  background-color: lime;
+}
+
+#areaB {
+  background-color: yellow;
+}
+ +

HTML

+ +
<div id="grid">
+  <div id="areaA">A</div>
+  <div id="areaB">B</div>
+</div>
+ +

Result

+ +

{{EmbedLiveSample("Examples", "40px", "100px")}}

+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("CSS3 Grid", "#propdef-grid-template-rows", "grid-template-rows")}}{{Spec2("CSS3 Grid")}}Initial definition
+ +

{{cssinfo}}

+ +

Browser compatibility

+ +

 

+ + + +

{{Compat("css.properties.grid-template-rows")}}

+ +

 

+ +

See also

+ + + + diff --git a/files/pt-br/web/css/grid/index.html b/files/pt-br/web/css/grid/index.html new file mode 100644 index 0000000000..7b9826ed26 --- /dev/null +++ b/files/pt-br/web/css/grid/index.html @@ -0,0 +1,187 @@ +--- +title: grid +slug: Web/CSS/grid +translation_of: Web/CSS/grid +--- +

A propriedade grid do CSS é uma abreviação das propriedades que definem todas as propriedades da grade explícita ({{cssxref("grid-template-rows")}}, {{cssxref("grid-template-columns")}}, e {{cssxref("grid-template-areas")}}), e todas as propriedades implícitas da grade ({{cssxref("grid-auto-rows")}}, {{cssxref("grid-auto-columns")}}, e {{cssxref("grid-auto-flow")}}), em uma única declaração.

+ +
{{EmbedInteractiveExample("pages/css/grid.html")}}
+ + + +
+

Nota: Você pode especificar apenas as propriedades explícitas ou implícitas da grade em uma única declaração grid. As subpropriedades que você não especifica são definidas como seu valor inicial, como é normal para abreviações. Além disso, as propriedades da medianiz NÃO são redefinidas por essa abreviação.

+
+ +

Sintaxe

+ +
/* <'grid-template'> values */
+grid: none;
+grid: "a" 100px "b" 1fr;
+grid: [linename1] "a" 100px [linename2];
+grid: "a" 200px "b" min-content;
+grid: "a" minmax(100px, max-content) "b" 20%;
+grid: 100px / 200px;
+grid: minmax(400px, min-content) / repeat(auto-fill, 50px);
+
+/* <'grid-template-rows'> /
+   [ auto-flow && dense? ] <'grid-auto-columns'>? values */
+grid: 200px / auto-flow;
+grid: 30% / auto-flow dense;
+grid: repeat(3, [line1 line2 line3] 200px) / auto-flow 300px;
+grid: [line1] minmax(20em, max-content) / auto-flow dense 40%;
+
+/* [ auto-flow && dense? ] <'grid-auto-rows'>? /
+   <'grid-template-columns'> values */
+grid: auto-flow / 200px;
+grid: auto-flow dense / 30%;
+grid: auto-flow 300px / repeat(3, [line1 line2 line3] 200px);
+grid: auto-flow dense 40% / [line1] minmax(20em, max-content);
+
+/* Global values */
+grid: inherit;
+grid: initial;
+grid: unset;
+
+ +

Valores

+ +
+
<'grid-template'>
+
Define o {{cssxref("grid-template")}} incluindo {{cssxref("grid-template-columns")}}, {{cssxref("grid-template-rows")}} e {{cssxref("grid-template-areas")}}.
+
<'grid-template-rows'> / [ auto-flow && dense? ] <'grid-auto-columns'>?
+
Configura um fluxo automático definindo as faixas de linha explicitamente por meio da propriedade {{cssxref("grid-template-rows")}} (e a propriedade {{cssxref("grid-template-columns")}} para none) e especificando como repetir automaticamente as faixas da coluna via {{cssxref("grid-auto-columns")}} (e setando {{cssxref("grid-auto-rows")}} para auto). {{cssxref("grid-auto-flow")}} também é definido para a column, de acordo com dense, se especificado. +

Todas as outras subpropriedades grid são redefinidas para seus valores iniciais.

+
+
[ auto-flow && dense? ] <'grid-auto-rows'>? / <'grid-template-columns'>
+
Configura um fluxo automático definindo as faixas da coluna explicitamente por meio da propriedade {{cssxref("grid-template-columns")}} (e a propriedade {{cssxref("grid-template-rows")}} para none) e especificando como repetir automaticamente as faixas de linha via {{cssxref("grid-auto-rows")}} (e setando {{cssxref("grid-auto-columns")}} para auto). {{cssxref("grid-auto-flow")}} também é definido para  row de acordo com dense, se especificado. +

Todas as outras subpropriedades grid são redefinidas para seus valores iniciais.

+
+
+ +

Sintaxe formal

+ +
{{csssyntax}}
+ +

Exemplo

+ +

Conteúdo HTML

+ +
<div id="container">
+  <div></div>
+  <div></div>
+  <div></div>
+  <div></div>
+  <div></div>
+  <div></div>
+  <div></div>
+  <div></div>
+</div>
+ +

Conteúdo CSS

+ +
#container {
+  display: grid;
+  grid: repeat(2, 60px) / auto-flow 80px;
+}
+
+#container > div {
+  background-color: #8ca0ff;
+  width: 50px;
+  height: 50px;
+}
+ +

Resultado

+ +

{{EmbedLiveSample("Example", "100%", 150)}}

+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComment
{{SpecName("CSS3 Grid", "#propdef-grid", "grid")}}{{Spec2("CSS3 Grid")}}Definição inicial
+ +

{{cssinfo}}

+ +

Compatibilidade do navegador

+ + + +

{{Compat("css.properties.grid")}}

+ +

Veja também

+ + + + diff --git a/files/pt-br/web/css/height/index.html b/files/pt-br/web/css/height/index.html new file mode 100644 index 0000000000..7d06fb0534 --- /dev/null +++ b/files/pt-br/web/css/height/index.html @@ -0,0 +1,192 @@ +--- +title: height +slug: Web/CSS/height +translation_of: Web/CSS/height +--- +
{{CSSRef()}}
+ +

Sumário

+ +

A propriedade height do CSS determina a altura da área do conteúdo de um elemento. A área de conteúdo consiste no padding, margin e border do elemento.

+ +

As propriedades {{Cssxref("min-height")}} e {{Cssxref("max-height")}} sobrepõem a {{Cssxref("height")}}.

+ +

{{cssinfo}}

+ +

Sintaxe

+ +
Sintaxe formal: [<length> | <percentage>] && [border-box | content-box]? | available | min-content | max-content | fit-content | complex | auto
+
+ +
height: auto     /* auto keyword */
+
+height: 120px    /* <length> values */
+height: 10em
+
+height: 75%      /* <percentage> values */
+
+height: inherit
+
+ +

Valores

+ +
+
<length>
+
Veja {{cssxref("<length>")}} para unidades disponíveis.
+
<percentage>
+
Especificada como uma {{cssxref("<percentage>")}} da altura do conteúdo do bloco.
+
border-box {{ experimental_inline }}
+
Se presente, o último {{cssxref("<length>")}} ou {{cssxref("<percentage>")}} é aplicado a  caixa de borda do elemento.
+
content-box {{ experimental_inline }}
+
Se presente, o último {{cssxref("<length>")}} ou {{cssxref("<percentage>")}} é aplicado a caixa de conteúdo do elemento.
+
auto
+
O navegador calculará a altura do conteúdo especificado.
+
max-content {{ experimental_inline }}
+
A altura máxima intrínseca.
+
min-content {{ experimental_inline }}
+
A altura mínima intrínseca.
+
available {{ experimental_inline }}
+
Altura da caixa menos margem vertical, borda e padding.
+
fit-content {{ experimental_inline }}
+
O maior de: +
    +
  • a altura mínima intrínseca
  • +
  • a menor entre a altura intrínseca preferida e a altura disponível
  • +
+
+
+ +

Exemplos

+ +

HTML

+ +
<div id="red">
+  <span>I'm 50 pixels tall.</span>
+</div>
+<div id="green">
+  <span>I'm 25 pixels tall.</span>
+</div>
+<div id="parent">
+  <div id="child">
+    <span>I'm half the height of my parent.</span>
+  </div>
+</div>
+
+ +

CSS

+ +
div {
+  width: 250px;
+  margin-bottom: 5px;
+  border: 3px solid #999999;
+}
+
+#red {
+  height: 50px;
+}
+
+#green {
+  height: 25px;
+}
+
+#parent {
+  height: 100px;
+}
+
+#child {
+  height: 50%;
+  width: 75%;
+}
+
+ +

{{EmbedLiveSample('Exemplos')}}

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Box', '#the-width-and-height-properties', 'height')}}{{Spec2('CSS3 Box')}}Added the max-content, min-content, available, fit-content, border-box, content-box keywords.
{{SpecName('CSS3 Transitions', '#animatable-css', 'height')}}{{Spec2('CSS3 Transitions')}}Lists height as animatable.
{{SpecName('CSS2.1', 'visudet.html#the-height-property', 'height')}}{{Spec2('CSS2.1')}}Adds support for the {{cssxref("<length>")}} values and precises on which element it applies to.
{{SpecName('CSS1', '#height', 'height')}}{{Spec2('CSS1')}}Initial specification.
+ +

Compatibilidade entre navegadores

+ +

{{CompatibilityTable()}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico1.0{{CompatGeckoDesktop("1")}}4.07.01.0
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Suporte básico1.0{{CompatGeckoMobile("1")}}6.06.01.0
+
+ +

Veja também

+ +
    +
  • box model, {{Cssxref("width")}}, {{Cssxref("box-sizing")}}, {{Cssxref("min-height")}}, {{Cssxref("max-height")}}
  • +
diff --git a/files/pt-br/web/css/hifens/index.html b/files/pt-br/web/css/hifens/index.html new file mode 100644 index 0000000000..c8e718562f --- /dev/null +++ b/files/pt-br/web/css/hifens/index.html @@ -0,0 +1,902 @@ +--- +title: hifens +slug: Web/CSS/hifens +translation_of: Web/CSS/hyphens +--- +
{{CSSRef}}
+ +
A propriedade CSS  hyphens especifica como palavras devem ser hifenizadas quando o há quebra de texto em múltiplas linhas. Você pode prevenir a hifenização completamente, especificar pontos manualmente, ou permitir que o navegador insira automaticamente quando apropriado.
+ +
 
+ +
hyphens: none;
+hyphens: manual;
+hyphens: auto;
+
+/* Valores globais */
+hyphens: inherit;
+hyphens: initial;
+hyphens: unset;
+
+ +

Regras de hifenização são específicas para cada idioma. Em HTML, o idioma é determinado pelo atributo lang, e os navegadores irão utilizar hífen apenas caso este atributo esteja presente e se houver um dicionário de hifenização disponível. Em XML, deve ser usado o atributo xml:lang.

+ +
+

Nota: As regras que definem como a hifenização é realizada não são explicitamente definidas pela especificação, então a hifenização exata pode variar de navegador para navegador.

+
+ +

{{cssinfo}}

+ +

Sintaxe

+ +

A propriedade hyphens é especificada como uma única palavra-chave escolhida da lista abaixo.

+ +

Valores

+ +
+
none
+
Palavras não são separadas em quebras de linha, mesmo se seus caracteres sugiram pontos de quebra de linha. Linhas são quebradas apenas em espaços em branco.
+
manual
+
Palavras são separadas apenas onde caracteres dentro de uma palavras sugiram oportunidades de quebra de linha. Veja abaixo {{anch("Suggesting line break opportunities", "Oportunidades sugeridas de quebra de linha")}} para mais detalhes.
+
auto
+
O navegador é livre para quebrar palavras automaticamente nos pontos apropriados de hifenização, seguindo quaisquer regras que ele escolher. Entretanto, oportunidades sugeridas de quebras de linha (veja {{anch("Suggesting line break opportunities", "Oportunidades sugeridas de quebra de linha")}} abaixo) irão sobrepor a seleção automática de pontos de quebra quando presentes.
+
+ +
+

Nota: O comportamento da configuração auto requer que a propriedade idioma seja indicada corretamente para que as regras de hifenização sejam selecionadas. Você deve especificar o idioma utilizando o atributo HTML lang para garantir que a hifenização automática seja aplicada na linguagem de sua escolha.

+
+ +

Oportunidades sugeridas de quebra de linha

+ +

Existem dois caracteres Unicode que podem ser utilizados para especificar manualmente potenciais pontos de quebra de linha no texto:

+ +
+
U+2010 (HYPHEN)
+
O caractere hífen "duro" indica uma oportunidade de quebra de linha visível. Mesmo que não haja quebra de linha naquele ponto, o hífen ainda será renderizado.
+
U+00AD (SHY)
+
Um hífen invisivel, "suave". Este caractere não é renderizado visivelmente; ao invés, ele marca um local onde o browser deve quebrar a palavra se um hífen for necessário. Em HTML você pode usar &shy; para inserir um hífen suave.
+
+ +

Sintaxe formal

+ +
{{csssyntax}}
+ +

Exemplo

+ +

Este exemplo usa três classes, uma para cada configuração possível da propriedade hyphens.

+ +
<ul>
+  <li><code>none</code>: sem hífen; transbordar se necessário
+    <p lang="en" class="none">An extreme&shy;ly long English word</p>
+  </li>
+  <li><code>manual</code>: hífen apenas em &amp;hyphen; ou &amp;shy; (se necessário)
+    <p lang="en" class="manual">An extreme&shy;ly long English word</p>
+  </li>
+  <li><code>auto</code>: hífen onde o algorítmo decidir (se necessário)
+    <p lang="en" class="auto">An extreme&shy;ly long English word</p>
+  </li>
+</ul>
+
+ +
p {
+  width: 55px;
+  border: 1px solid black;
+ }
+p.none {
+  -webkit-hyphens: none;
+  -ms-hyphens: none;
+  hyphens: none;
+}
+p.manual {
+  -webkit-hyphens: manual;
+  -ms-hyphens: manual;
+  hyphens: manual;
+}
+p.auto {
+  -webkit-hyphens: auto;
+  -ms-hyphens: auto;
+  hyphens: auto;
+}
+
+ +
+

{{EmbedLiveSample("Example", "100%", "470'")}}

+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoCondiçãoComentário
{{SpecName("CSS3 Text", "#hyphens-property", "hyphens")}}{{Spec2("CSS3 Text")}}Initial definition
+ +

Compatibilidade dos navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(13.0)}}{{property_prefix("-webkit")}}[1]
+ {{CompatChrome(55.0)}} (unprefixed)
+

{{CompatGeckoDesktop("6.0")}}{{property_prefix("-moz")}}[2]
+ {{CompatGeckoDesktop("43.0")}}

+
{{CompatIE("10.0")}}{{property_prefix("-ms")}}[3]{{CompatOpera(44)}}{{CompatSafari(5.1)}}{{property_prefix("-webkit")}}
Hyphenation dictionary for Afrikaans (af, af-*){{CompatUnknown}}{{CompatGeckoDesktop("8.0")}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
Hyphenation dictionary for Bulgarian (bg, bg-*){{CompatUnknown}}{{CompatGeckoDesktop("8.0")}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
Hyphenation dictionary for Catalan (ca, ca-*){{CompatUnknown}}{{CompatGeckoDesktop("8.0")}}10.0{{CompatUnknown}}9.1
Hyphenation dictionary for Croatian (hr, hr-*){{CompatUnknown}}{{CompatGeckoDesktop("8.0")}}{{CompatNo}}{{CompatUnknown}}9.1
Hyphenation dictionary for Czech (cs, cs-*){{CompatUnknown}}{{CompatNo}}10.0{{CompatUnknown}}9.1
Hyphenation dictionary for Danish (da, da-*){{CompatUnknown}}{{CompatGeckoDesktop("8.0")}}10.0{{CompatUnknown}}9.1
Hyphenation dictionary for Dutch (nl, nl-*){{CompatUnknown}}{{CompatGeckoDesktop("8.0")}}10.0{{CompatUnknown}}5.1
Hyphenation dictionary for English (en, en-*){{CompatChrome(55.0)}} (unprefixed){{CompatGeckoDesktop("6.0")}}[4]10.0{{CompatOpera(44)}}5.1[5]
Hyphenation dictionary for Esperanto (eo, eo-*){{CompatUnknown}}{{CompatGeckoDesktop("8.0")}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
Hyphenation dictionary for Estonian (et, et-*){{CompatUnknown}}{{CompatGeckoDesktop("8.0")}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
Hyphenation dictionary for Finnish (fi, fi-*){{CompatUnknown}}{{CompatGeckoDesktop("8.0")}}{{CompatNo}}{{CompatUnknown}}9.1
Hyphenation dictionary for French (fr, fr-*){{CompatUnknown}}{{CompatGeckoDesktop("8.0")}}10.0{{CompatUnknown}}5.1
Hyphenation dictionary for Galician (gl, gl-*){{CompatUnknown}}9.0{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
Hyphenation dictionary for German, Traditional Orthography of 1901 (de-1901, de-AT-1901, de-DE-1901){{CompatUnknown}}8.0{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Hyphenation dictionary for German, Reformed Orthography of 1996 (de, de-1996, de-DE, de-AT, de-*){{CompatUnknown}}8.010.0{{CompatUnknown}}5.1
Hyphenation dictionary for German, Swiss Orthography (de-CH, de-CH-*){{CompatUnknown}}8.0{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Hyphenation dictionary for Hungarian (hu, hu-*){{CompatUnknown}}9.0{{CompatNo}}{{CompatUnknown}}9.1
Hyphenation dictionary for Icelandic (is, is-*){{CompatUnknown}}8.0{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
Hyphenation dictionary for Interlingua (ia, ia-*){{CompatUnknown}}8.0{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
Hyphenation dictionary for Italian (it, it-*){{CompatUnknown}}9.010.0{{CompatUnknown}}5.1
Hyphenation dictionary for Kurmanji (kmr, kmr-*){{CompatUnknown}}8.0{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
Hyphenation dictionary for Latin (la, la-*){{CompatVersionUnknown}}8.0{{CompatNo}}{{CompatOpera(44)}}{{CompatNo}}
Hyphenation dictionary for Lithuanian (lt, lt-*){{CompatUnknown}}8.0{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
Hyphenation dictionary for Mongolian (mn, mn-*){{CompatUnknown}}8.0{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
Hyphenation dictionary for Norwegian (Bokmål) (no, no-*, nb, nb-*){{CompatUnknown}}8.010.0{{CompatUnknown}}9.1
Hyphenation dictionary for Norwegian (Nynorsk) (nn, nn-*){{CompatUnknown}}8.010.0{{CompatUnknown}}{{CompatNo}}
Hyphenation dictionary for Polish (pl, pl-*){{CompatUnknown}}31.010.0{{CompatUnknown}}9.1
Hyphenation dictionary for Portuguese (pt, pt-*){{CompatUnknown}}8.0[6]10.0{{CompatUnknown}}9.1
Hyphenation dictionary for Brazilian Portuguese (pt-BR){{CompatUnknown}}8.0[6]10.0{{CompatUnknown}}{{CompatNo}}
Hyphenation dictionary for Russian (ru, ru-*){{CompatUnknown}}8.010.0{{CompatUnknown}}5.1
Hyphenation dictionary for Serbian, Bosnian, Serbo-Croatian (sh, sh-*, sr, sr-*, bs, bs-*){{CompatUnknown}}8.0{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
Hyphenation dictionary for Slovenian (sl, sl-*){{CompatUnknown}}8.0{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
Hyphenation dictionary for Spanish (es, es-*){{CompatUnknown}}8.010.0{{CompatUnknown}}5.1
Hyphenation dictionary for Swedish (sv, sv-*){{CompatUnknown}}8.010.0{{CompatUnknown}}9.1
Hyphenation dictionary for Turkish (tr, tr-*){{CompatUnknown}}9.010.0{{CompatUnknown}}9.1
Hyphenation dictionary for Ukrainian (uk, uk-*){{CompatUnknown}}9.0{{CompatNo}}{{CompatUnknown}}9.1
Hyphenation dictionary for Upper Sorbian (hsb, hsb-*){{CompatUnknown}}8.0{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
Hyphenation dictionary for Welsh (cy, cy-*){{CompatUnknown}}8.0{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
Hyphenation dictionary for other languages{{CompatUnknown}}{{CompatNo}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatAndroid("4.0")}}{{property_prefix("-webkit")}}[1]{{CompatChrome(55.0)}} (unprefixed){{CompatGeckoMobile("6.0")}}{{property_prefix("-moz")}}[2]
+ {{CompatGeckoDesktop("43.0")}}
{{CompatNo}}{{CompatOperaMobile(44)}}{{CompatSafari(4.2)}}{{property_prefix("-webkit")}}{{CompatChrome(55.0)}} (unprefixed)
Hyphenation dictionary for Afrikaans (af, af-*){{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Hyphenation dictionary for Bulgarian (bg, bg-*){{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Hyphenation dictionary for Catalan (ca, ca-*){{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Hyphenation dictionary for Croatian (hr, hr-*){{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Hyphenation dictionary for Czech (cs, cs-*){{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Hyphenation dictionary for Danish (da, da-*){{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Hyphenation dictionary for Dutch (nl, nl-*){{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Hyphenation dictionary for English (en, en-*){{CompatUnknown}}{{CompatChrome(55.0)}} (unprefixed){{CompatUnknown}}{{CompatUnknown}}{{CompatOperaMobile(44)}}{{CompatUnknown}}{{CompatChrome(55.0)}} (unprefixed)
Hyphenation dictionary for Esperanto (eo, eo-*){{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Hyphenation dictionary for Estonian (et, et-*){{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Hyphenation dictionary for Finnish (fi, fi-*){{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Hyphenation dictionary for French (fr, fr-*){{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Hyphenation dictionary for Galician (gl, gl-*){{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Hyphenation dictionary for German, Traditional Orthography of 1901 (de-1901, de-AT-1901, de-DE-1901){{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Hyphenation dictionary for German, Reformed Orthography of 1996 (de, de-1996, de-DE, de-AT, de-*){{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Hyphenation dictionary for German, Swiss Orthography (de-CH, de-CH-*){{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Hyphenation dictionary for Hungarian (hu, hu-*){{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Hyphenation dictionary for Icelandic (is, is-*){{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Hyphenation dictionary for Interlingua (ia, ia-*){{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Hyphenation dictionary for Italian (it, it-*){{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Hyphenation dictionary for Kurmanji (kmr, kmr-*){{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Hyphenation dictionary for Latin (la, la-*){{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOperaMobile(44)}}{{CompatUnknown}}{{CompatVersionUnknown}}
Hyphenation dictionary for Lithuanian (lt, lt-*){{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Hyphenation dictionary for Mongolian (mn, mn-*){{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Hyphenation dictionary for Norwegian (Bokmål) (no, no-*, nb, nb-*){{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Hyphenation dictionary for Norwegian (Nynorsk) (nn, nn-*){{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Hyphenation dictionary for Polish (pl, pl-*){{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Hyphenation dictionary for Portuguese (pt, pt-*){{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Hyphenation dictionary for Brazilian Portuguese (pt-BR){{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}} {{CompatUnknown}}
Hyphenation dictionary for Russian (ru, ru-*){{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Hyphenation dictionary for Serbian, Bosnian, Serbo-Croatian (sh, sh-*, sr, sr-*, bs, bs-*){{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Hyphenation dictionary for Slovenian (sl, sl-*){{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Hyphenation dictionary for Spanish (es, es-*){{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Hyphenation dictionary for Swedish (sv, sv-*){{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Hyphenation dictionary for Turkish (tr, tr-*){{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Hyphenation dictionary for Ukrainian (uk, uk-*){{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Hyphenation dictionary for Upper Sorbian (hsb, hsb-*){{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Hyphenation dictionary for Welsh (cy, cy-*){{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Hyphenation dictionary for other languages{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Sem hifenização automática, apenas -webkit-hyphens: none é suportado.

+ +

[2] Hifenização automática funciona apenas para idiomas cujos dicionários de hifenização sejam integrados com Gecko. Veja a nota abaixo para ver a lista completa destas linguagens.

+ +

[3] Hifenização automática funciona apenas para idiomas cujos dicionários de hifenização sejam integrados com Internet Explorer. Veja a nota abaixo para ver a lista completa destas linguagens.

+ +

[4] Usa um dicionário en-US.

+ +

[5] en-GB e en-US usam dicionários diferentes.

+ +

[6] Usa um dicionário Português.

+ +

Veja também

+ +
    +
  • {{Cssxref("content")}}
  • +
diff --git a/files/pt-br/web/css/id_selectors/index.html b/files/pt-br/web/css/id_selectors/index.html new file mode 100644 index 0000000000..8615966dfb --- /dev/null +++ b/files/pt-br/web/css/id_selectors/index.html @@ -0,0 +1,124 @@ +--- +title: Seletores de ID +slug: Web/CSS/ID_selectors +tags: + - Beginner + - CSS + - CSS Reference + - Iniciante + - Referencia + - Referencia CSS + - Selectors + - Seletores +translation_of: Web/CSS/ID_selectors +--- +
{{CSSRef("Selectors")}}
+ +

Em um documento HTML, os seletores de ID do CSS selecionam um elemento baseado no conteúdo de seu atributo {{htmlattrxref("ID")}},  o qual deve ser exatamente igual ao valor dado ao seletor.

+ +

Sintaxe

+ +
#valor_id { propriedades de estilo }
+ +

Note que isso é equivalente aos seguintes {{Cssxref("Attribute_selectors", "seletores de atributo")}}:

+ +
[id=valor_id] { propriedades de estilo }
+ +

Exemplo

+ +
span#identificado {
+  background-color: DodgerBlue;
+}
+
+ +
<span id="identificado">Aqui um span com um pouco de texto.</span>
+<span>Aqui outro.</span>
+
+ +

{{EmbedLiveSample("Exemplo", 200, 50)}}

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName("CSS4 Selectors", "#id-selectors", "ID selectors")}}{{Spec2("CSS4 Selectors")}} 
{{SpecName("CSS3 Selectors", "#id-selectors", "ID selectors")}}{{Spec2("CSS3 Selectors")}} 
{{SpecName("CSS2.1", "selector.html#id-selectors", "ID selectors")}}{{Spec2("CSS2.1")}} 
{{SpecName("CSS1", "#id-as-selector", "ID selectors")}}{{Spec2("CSS1")}}Definição inicial
+ +

Compatibilidade nos Navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
RecursoChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
RecursoAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
diff --git a/files/pt-br/web/css/image-set()/index.html b/files/pt-br/web/css/image-set()/index.html new file mode 100644 index 0000000000..97dc21d76e --- /dev/null +++ b/files/pt-br/web/css/image-set()/index.html @@ -0,0 +1,78 @@ +--- +title: image-set() +slug: Web/CSS/image-set() +translation_of: Web/CSS/image-set() +--- +
{{cssref}}
+ +

A notação de função CSS image-set() é um método de deixar o navegador escolher a imagem CSS mais apropriada de um dado conjunto, principalmente para telas de alta densidade de pixels.

+ +

Resolução e largura de banda diferem por dispositivo e acesso à rede. A função image-set() oferece a resolução de imagem mais apropriada para o dispositivo de um usuário, fornecendo um conjunto de opções de imagem — cada uma com uma declaração de resolução associada — da qual o navegador escolhe o mais apropriado para o dispositivo e as configurações. A resolução pode ser usada como um proxy para o tamanho do arquivo — um agente de usuário em uma conexão móvel lenta, com uma tela de alta resolução, pode preferir receber imagens de baixa resolução em vez de aguardar uma imagem de alta resolução carregar.

+ +

image-set() permite que o autor forneça opções em vez de determinar o que cada usuário individual precisa.

+ +

Sintaxe

+ +
image-set() = image-set( <image-set-option># )
+where <image-set-option> = [ <image> | <string> ] <resolution> and
+      <string> is an <url>
+
+ +

Valores

+ +

Mais comumente, você verá um valor de  url() <string>, mas o <image> pode ser qualquer tipo de imagem, exceto para um conjunto de imagens. A função image-set() não pode ser aninhada dentro de outra função image-set().

+ +

unidades <resolution> incluem x ou ddpx, para pontos por unidade de pixel, dpi, para pontos por polegada, e dpcm para pontos per centímetro. Toda imagem dentro de image-set() deve ter uma única resolução.

+ +

Exemplos

+ +
background-image: image-set( "cat.png" 1x,
+                             "cat-2x.png" 2x);
+ +

Este exemplo mostra como usar image-set() para fornecer duas opções alternativas {{cssxref("background-image")}}, escolhidas dependendo da resolução necessária: uma versão normal e uma versão de alta-resolução.

+ +

Preocupações de Acessibilidade

+ +

Tecnologia assistiva não pode analisar imagens de fundo. Se a imagem contiver informações críticas para entender a finalidade geral da página, é melhor descrevê-la semanticamente no documento.

+ + + +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('CSS4 Images', '#image-set-notation', 'The image-set() notation')}}{{Spec2('CSS4 Images')}} 
+ +

Compatibilidade entre navegadores

+ + + +

{{Compat("css.types.image.image-set")}}

+ +

Veja também

+ +
    +
  • {{cssxref("image")}}
  • +
  • {{cssxref("_image", "image()")}}
  • +
  • {{cssxref("element")}}
  • +
  • {{cssxref("url")}}
  • +
  • {{cssxref("<gradient>")}}
  • +
  • {{cssxref("image-set","image-set()")}}
  • +
  • {{cssxref("cross-fade")}}
  • +
diff --git a/files/pt-br/web/css/imagem/index.html b/files/pt-br/web/css/imagem/index.html new file mode 100644 index 0000000000..fe9631cb30 --- /dev/null +++ b/files/pt-br/web/css/imagem/index.html @@ -0,0 +1,157 @@ +--- +title: +slug: Web/CSS/imagem +tags: + - CSS + - CSS imagens + - Layout + - Referencia + - Tipo de data CSS + - Web + - graficos +translation_of: Web/CSS/image +--- +
{{CSSRef}}
+ +

O tipo de data CSS <image> representa uma imagem bi-dimensional. Existem dois tipos de imagens: imagens planas, referenciada por um {{cssxref("<url>")}}, e imagens geradas dinamicamente, geradas por {{cssxref("<gradient>")}} ou {{cssxref("element()")}}. Imagens podem ser usadas em inumeras propriedades CSS, como {{cssxref("background-image")}}, {{cssxref("border-image")}}, {{cssxref("content")}}, {{cssxref("cursor")}}, e {{cssxref("list-style-image")}}.

+ +

Tipos de imagens

+ +

CSS pode lidar com os seguintes tipos de imagens:

+ +
    +
  • Imagens com dimensões intrínsecas (tamanho natural), tipo um JPEG, PNG, ou outro formato rasterizado.
  • +
  • Imagens com multiplas dimensões intrínsecas,  +
    +
    existente em várias versões dentro de um único arquivo, como alguns formatos .ico. (Nesse caso, a dimensões intrínsecas serão a largura da imagem na área e a proporção mais semelhante à caixa contendo.)
    +
    +
  • +
  • Imagens sem dimensões intrínsecas mas com um aspecto intrínseco entre a largura e altura, como um SVG ou outro vetor.
  • +
  • Imagens com nenhuma dimensões intrínsecas, e nenhuma relação de aspecto intrínseco como um gradiente CSS.
  • +
+ +

CCS determina um tamanho concreto do objeto usando (1) suas dimensões intrínsecas; (2) seu tamanho especificado, definido por propriedades CSS como {{cssxref("width")}}, {{cssxref("height")}}, ou {{cssxref("background-size")}}; e (3) é o tamanho padrão, determinado pelo tipo de propriedade em que a imagem é usada:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Tipo de objetoTamanho do objeto padrão
{{cssxref("background-image")}}O tamanho da área de posicionamento do fundo do elemento.
{{cssxref("list-style-image")}}O tamanho de um carácter 1em
{{cssxref("border-image")}}O tamanho da área da imagem da borda do elemento
{{cssxref("cursor")}}O tamanho definido pelo navegador correspondente ao tamanho normal do cursor no sistema do cliente
{{cssxref("border-image-source")}}?
{{cssxref("mask-image")}}?
{{cssxref("shape-outside")}}?
{{cssxref("mask-border-source")}}?
Substituí o conteúdo, como quando combinando {{cssxref("content")}} com um pseudo-elemento ({{cssxref("::after")}} ou {{cssxref("::before")}})Um 300px × 150px retângulo
+ +

O tamanho do objeto concreto é calculado usando o seguinte algoritimo:

+ +
    +
  • Se o tamanho especificado define tanto a largura quanto a altura, esses valores serão usado no tamanho concreto do objeto.
  • +
  • Se o tamanho especificado define apenas a largura ou a altura, o valor que falta é determind se o valor espeficiado ado usando a relação intrínseca, se existir algum, as dimensões intrínsecas se o valoer espeficicado combinar, ou o tamanho do objeto padrão para esse valor ausente.
  • +
  • Se o tamanho especificado define nem largura ou altura, o tamanho concreto é calculado de modo que corresponda à proporção intrínseca da imagem mas sem exceder o tamanho padrão do objeto em qualquer dimensão. Se a imagem não tiver relação de aspecto intrínseco, o relação de aspecto intrínseco do objeto é aplicado para ser usado; se esse objeto for vazio, a largura ou altura que faltam são retirados do tamanho de objeto padrão.
  • +
+ +
Nota: Não são todos os navegadores que suportam cada tipo de imagem em cada propriedade. Veja a seção compatibilidade dos navegadores para mais detalhes.
+ +

Sintaxe

+ +

O tipo de data <image> pode ser representado por qualquer item seguinte:

+ +
    +
  • Uma imagem denotada pelo tipo de data {{cssxref("<url>")}}
  • +
  • Um tipo de data {{cssxref("<gradient>")}}
  • +
  • Uma parte da página web, definida pela função {{cssxref("element", "element()")}}
  • +
+ +

Exemplos

+ +

Imagens válidas

+ +
url(test.jpg)               /* Uma <url>, enquanto test.jpg é uma imagem real */
+linear-gradient(blue, red)  /* Um <gradient> */
+element(#realid)            /* Uma parte da página web, referenciada por uma função element() se "realid" for um ID existente na página */
+
+ +

Imagens inválidas

+ +
cervin.jpg        /* Um arquivo imagem deve ser definido usando a função url(). */
+url(report.pdf)   /* Um arquivo apontado pela função url() deve ser uma imagem. */
+element(#fakeid)  /* Um elemento ID deve ser um ID existente na página. */
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + +
EspecificaçõesStatusComentário
{{SpecName('CSS4 Images', '#typedef-image', '<image>')}}{{Spec2('CSS4 Images')}}Adiciona {{cssxref("element()")}}, {{cssxref("image()")}},  {{cssxref("conic-gradient()")}}, {{cssxref("repeating-conic-gradient()")}}, e {{cssxref("image-resolution")}}.
{{SpecName('CSS3 Images', '#typedef-image', '<image>')}}{{Spec2('CSS3 Images')}}Definição inicial. Depois disso, não existe definição explicita do tipo de data <image>. Imagens podem ser somente definidas usando a notação funciona url() .
+ +

Compatibilidade do navegador

+ +

 

+ + + +

{{Compat("css.types.image")}}

+ +

 

+ +

Veja também

+ +
    +
  • {{cssxref("<gradient>")}}
  • +
  • {{cssxref("element()")}}
  • +
diff --git a/files/pt-br/web/css/index.html b/files/pt-br/web/css/index.html new file mode 100644 index 0000000000..95d26a6966 --- /dev/null +++ b/files/pt-br/web/css/index.html @@ -0,0 +1,99 @@ +--- +title: CSS +slug: Web/CSS +tags: + - CSS + - Design + - Estilos + - Landing + - Layout + - Referencia +translation_of: Web/CSS +--- +
{{CSSRef}}
+ +

CSS (Cascading Style Sheets ou Folhas de Estilo em Cascata) é uma linguagem de estilo usada para descrever a apresentação de um documento escrito em HTML ou em XML (incluindo várias linguagens em XML como SVG, MathML ou XHTML). O CSS descreve como elementos são mostrados na tela, no papel, na fala ou em outras mídias.

+ +

CSS é uma das principais linguagens da open web e é padronizada em navagadores web de acordo com as especificação da W3C. Desenvolvido em níveis, o CSS1 está atualmente obsoleto, o CSS2.1 é uma recomendação e o CSS3, agora dividido em pequenos módulos, está progredindo para a sua padronização.

+ +
+
    +
  • Introdução CSS + +

    Se você é novo no desenvolvimento web, certifique-se de ler nosso artigo CSS básico para aprender o que é CSS e como usá-lo.

    +
  • +
  • Tutoriais CSS +

    Nossa área de aprendizado CSS contém diversos tutoriais para levá-lo do nível iniciante ao avançado, cobrindo todos os fundamentos.

    +
  • +
  • Referências CSS +

    Nossa extensa referência CSS para desenvolvedores web experientes descreve todas as propriedades e conceitos do CSS.

    +
  • +
+ +
+
+

Tutoriais

+ +

Nossa área de aprendizado CSS contempla múltiplos módulos que ensinam CSS desde o início — não é necessário conhecimento prévio.

+ +

Introdução ao CSS

+ +

Esse módulo inicia com o funcionamento básico do CSS, incluindo seletores e propriedades, escrever regras CSS, aplicar CSS ao HTML, como especificar comprimento, cor, e outras unidades em CSS, cascata e herança, o básico do modelo de caixas, e depuração de CSS.

+ +

Estilização do texto

+ +

Esse módulo discute os fundamentos da estilização de textos, incluindo a definição de fontes, negritos, itálicos, linhas e espaçamentos de letras, sombras e outras propriedades de textos.

+ +

Estilização de caixas

+ +

Esse módulo foca na estilização de caixas, um dos passos fundamentais para o layout de uma página web. Nesse módulo nós recapitulamos o modelo de caixas, então abordamos o controle do layout das caixas definindo margens, bordas e preenchimento, cores de fundo customizadas, imagens e outras características extravagantes como sombras e filtros em caixas.

+ +

Layout CSS

+ +

Neste ponto nós já vimos os fundamentos do CSS, como estilizar texto e estilizar e manipular caixas que contém seu conteúdo. Agora veremos como posicionar suas caixas no lugar certo em relação à janela de exibição e um ao outro. Nós cobrimos os pré-requisitos necessários e agora você pode se aprofundar no layout do CSS com diferentes configurações de exibição, métodos tradicionais de layout envolvendo float e posicionamento, e modernas ferramentas para layout como flexbox.

+ +

Referências

+ + +
+ +
+

Livro de receitas

+ +

O livro de receitas de layout CSS tem como objetivo juntar receitas para padrões comuns de layout, coisas que você pode precisar para implementar em seus sites. Além de prover código você pode usá-lo como ponto de partida em seus projetos, essas receitas destacam as diferentes formas de utilização das especificações de layout e as escolhas que você pode fazer como desenvolvedor.

+ +

Ferramentas para desenvolvimento de CSS

+ + +
+
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/css/inheritance/index.html b/files/pt-br/web/css/inheritance/index.html new file mode 100644 index 0000000000..c93b19440b --- /dev/null +++ b/files/pt-br/web/css/inheritance/index.html @@ -0,0 +1,53 @@ +--- +title: Herança +slug: Web/CSS/inheritance +tags: + - CSS + - Guide + - Guía + - Web +translation_of: Web/CSS/inheritance +--- +

Resumo

+ +

O resumo de cada definição de propriedade do CSS diz se tal propriedade é herdada por padrão ("Inherited": sim) ou é não herdada por padrão ("Inherited": não). Isso controla o que ocorre quando nenhum valor é especificado para uma propriedade em um elemento.

+ +

Propriedades herdadas

+ +

Quando nenhum valor de uma propriedade herdada foi especificado em um elemento, o elemento obtém o valor computado desta propriedade em seu elemento pai. Apenas o elemento raiz do documento obtém o valor inicial dado no resumo da propriedade.

+ +

Um exemplo típico de uma propriedade herdada é a propriedade {{ Cssxref("color") }}. Dadas as seguintes regras de estilo:

+ +
p { color: green }
+ +

e o markup:

+ +
<p>Este paragrafo tem <em>texto enfatizado</em> dentro dele.</p>
+ +

As palavras "texto enfatizado" vão aparecer em verde, já que o elemento em herdou o valor da propriedade {{ Cssxref("color") }} do elemento p. Ele não obtém o valor inicial da propriedade (o qual é a cor usada pelo elemento raiz quando a página não especifica nenhuma cor).

+ +

Propriedades não herdadas

+ +

Quando nenhum valor para uma propriedade não herdada (algumas vezes chamada de reset property em código Mozilla) é especificado em um elemento, o elemento obtém o valor inicial desta propriedade (como especificado no resumo da propriedade).

+ +

Um exemplo típico de uma propriedade não herdada é a propriedade {{ Cssxref("border") }}. Dadas as seguintes regras de estilo:

+ +
 p { border: medium solid }
+ +

e o markup

+ +
  <p>Este paragrafo tem <em>texto enfatizado</em> dentro dele.</p>
+ +

As palavras "texto enfatizado" não vão ter uma borda (já que o valor inicial de {{ Cssxref("border-style") }} é none).

+ +

Notas

+ +

A palavra-chave {{ Cssxref("inherit") }} permite aos autores especificar explicitamente a herança. Ela funciona tanto em propriedades herdadas como não herdadas.

+ +

Veja também

+ + diff --git a/files/pt-br/web/css/initial/index.html b/files/pt-br/web/css/initial/index.html new file mode 100644 index 0000000000..71d1c66431 --- /dev/null +++ b/files/pt-br/web/css/initial/index.html @@ -0,0 +1,80 @@ +--- +title: initial +slug: Web/CSS/initial +tags: + - Estado inicial + - Herança + - Iniciante + - Referencia + - User-agent + - estado padrão +translation_of: Web/CSS/initial +--- +
{{CSSRef}}
+ +

A palavra-chave CSS initial CSS se aplica ao valor inicial (ou padrão) de uma propriedade para um elemento. Este valor inicial é definido pelo navegador. Este valor pode ser aplicado em qualquer propriedade CSS. Isto inclui também o atalho CSS {{cssxref("all")}}, no qual o initial pode ser utilizado para restaurar todas as propriedades CSS para o seu estado inicial.

+ +
+

Nota: Em propriedades herdadas, O valor inicial pode ser inesperado. Neste caso, considere o uso dos termos {cssxref("inherit")}}, {{cssxref("unset")}}, ou {{cssxref("revert")}}.

+
+ +

Exemplo

+ +

HTML

+ +
<p>
+  <span>Este texto é vermelho.</span>
+  <em>Este texto está em sua cor inicial (normalmente preto).</em>
+  <span>Este texto está em vermelho de novo :) </span>
+</p>
+ +

CSS

+ +
p {
+  color: red;
+}
+
+em {
+  color: initial;
+}
+ +

{{EmbedLiveSample('Exemplo')}}

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSS4 Cascade', '#initial', 'initial') }}{{Spec2('CSS4 Cascade')}}No changes from Level 3.
{{ SpecName('CSS3 Cascade', '#initial', 'initial') }}{{Spec2('CSS3 Cascade')}}Initial definition.
+ +

Compatibilidade de navegadores

+ + + +

{{Compat("css.types.global_keywords.initial")}}

+ +

Veja também

+ +
    +
  • Utilize {{cssxref("unset")}} para definir uma propriedade para o seu valor herdado caso haja herança, ou para o seu valor inicial, caso não haja..
  • +
  • Utilize {{cssxref("revert")}} para redefinir uma propriedade ao valor estabelecido pela folha de estilo user-agent  (ou por seus estilos de usuário, se existir algum).
  • +
  • Utilize {{cssxref("inherit")}} para fazer uma propriedade de elemento a mesma de seu elemento pai.
  • +
  • A propriedade {{cssxref("all")}} permite que você redefina todas as propriedades para os seus estados initial, inherited, reverted, or unset de uma vez.
  • +
diff --git a/files/pt-br/web/css/inline-size/index.html b/files/pt-br/web/css/inline-size/index.html new file mode 100644 index 0000000000..0d8dcb62a1 --- /dev/null +++ b/files/pt-br/web/css/inline-size/index.html @@ -0,0 +1,93 @@ +--- +title: inline-size +slug: Web/CSS/inline-size +translation_of: Web/CSS/inline-size +--- +
{{CSSRef}}{{SeeCompatTable}}
+ +

A propriedade do CSS inline-size define o tamanho horizontal e vertical de um elemento bloco. Ele é correspondente a cada propriedade {{cssxref("width")}} ou a {{cssxref("height")}}, dependendo do valor de {{cssxref("writing-mode")}}.

+ +
/* <length> values */
+inline-size: 300px;
+inline-size: 25em;
+
+/* <percentage> values */
+inline-size: 75%;
+
+/* Keyword values */
+inline-size: 25em border-box;
+inline-size: 75% content-box;
+inline-size: max-content;
+inline-size: min-content;
+inline-size: available;
+inline-size: fit-content;
+inline-size: auto;
+
+/* Global values */
+inline-size: inherit;
+inline-size: initial;
+inline-size: unset;
+
+ +

Se o writing mode é orientado verticalmente, o valor de inline-size relaciona a altura do elemento; ao contrário, está relacionado a largura do elemento. A propriedade relacionada é a {{cssxref("block-size")}}, no qual define a outra dimensão do elemento.

+ +

{{cssinfo}}

+ +

Sintaxe

+ +

Valores

+ +

A propriedade inline-size aproveita os mesmos valores que as propriedades {{cssxref("width")}} e {{cssxref("height")}}.

+ +

Sintaxe formal

+ +
{{csssyntax}}
+ +

Exemplo

+ +

HTML

+ +
<p class="exampleText">Texto de Exemplo</p>
+
+ +

CSS

+ +
.exampleText{
+  writing-mode: vertical-rl;
+  background-color: yellow;
+  inline-size: 110px;
+}
+ +

{{EmbedLiveSample("Example")}}

+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName("CSS Logical Properties", "#logical-dimension-properties", "inline-size")}}{{Spec2("CSS Logical Properties")}}Definição Inicial
+ +

Compatibilidade com Navegador

+ + + +

{{Compat("css.properties.inline-size")}}

+ +

Veja também

+ +
    +
  • As propriedades físicas mapeadas: {{cssxref("width")}} e {{cssxref("height")}}
  • +
  • {{cssxref("writing-mode")}}
  • +
diff --git a/files/pt-br/web/css/isolation/index.html b/files/pt-br/web/css/isolation/index.html new file mode 100644 index 0000000000..49c169d491 --- /dev/null +++ b/files/pt-br/web/css/isolation/index.html @@ -0,0 +1,154 @@ +--- +title: isolation +slug: Web/CSS/isolation +translation_of: Web/CSS/isolation +--- +
{{CSSRef}}
+ +

A propriedade CSS isolation define se o elemento deve criar um novo {{glossary("stacking context")}}.

+ +
/* Keyword values */
+isolation: auto;
+isolation: isolate;
+
+/* Global values */
+isolation: inherit;
+isolation: initial;
+isolation: unset;
+
+ +

É especialmente útil em conjunto com {{cssxref("background-blend-mode")}} que mistura os fundos em um dado stacking context: ela permite isolar grupos de elementos dos seus fundos e misturar as suas cores.

+ +

{{cssinfo}}

+ +

Sintaxe

+ +

Uma das palavras-chave listadas abaixo.

+ +

Valores

+ +
+
auto
+
É uma palavra-chave indicando que um novo stacking context deve ser criado somente se uma das propriedades aplicadas ao elemento requererem.
+
isolate
+
É uma palavra-chave indicando que um novo stacking context deve ser criado.
+
+ +

Sintaxe formal

+ +
{{csssyntax}}
+ +

Exemplos

+ +
<div id="b" class="a">
+  <div id="d">
+    <div class="a c">auto</div>
+  </div>
+  <div id="e">
+    <div class="a c">isolate</div>
+  </div>
+</div>
+
+ +
.a {
+  background-color: rgb(0,255,0);
+}
+#b {
+  width: 200px;
+  height: 210px;
+}
+.c {
+  width: 100px;
+  height: 100px;
+  border: 1px solid black;
+  padding: 2px;
+  mix-blend-mode: difference;
+}
+#d {
+  isolation: auto;
+}
+#e {
+  isolation: isolate;
+}
+ +

{{ EmbedLiveSample('Examples', "230", "230") }}

+ +

Especificações

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('Compositing', '#isolation', 'Isolation') }}{{ Spec2('Compositing') }}Initial definition
+ +

Compatibilidade com navegadores

+ +

{{CompatibilityTable()}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support +

{{CompatChrome(41.0)}}

+
{{CompatGeckoDesktop('36')}}{{CompatNo()}}307.1
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support +

{{CompatChrome(41.0)}}

+
{{CompatGeckoMobile('36')}}{{CompatNo()}}368.0
+
+ +

Veja também

+ +
    +
  • {{cssxref("<blend-mode>")}}
  • +
  • {{cssxref("mix-blend-mode")}}, {{cssxref("background-blend-mode")}}
  • +
diff --git a/files/pt-br/web/css/layout_cookbook/breadcrumb_navigation/index.html b/files/pt-br/web/css/layout_cookbook/breadcrumb_navigation/index.html new file mode 100644 index 0000000000..6f478482a9 --- /dev/null +++ b/files/pt-br/web/css/layout_cookbook/breadcrumb_navigation/index.html @@ -0,0 +1,57 @@ +--- +title: Navegação "Migalha de Pão" +slug: Web/CSS/Layout_cookbook/Breadcrumb_Navigation +tags: + - CSS + - Layout + - Migalha de pão + - Navegação + - cookbook + - flexbox +translation_of: Web/CSS/Layout_cookbook/Breadcrumb_Navigation +--- +
{{CSSRef}}
+ +

A navegação "migalha de pão" ajuda o usuário a enteder sua localização no site, fornecendo uma trilha de navegação de volta à pagina inicial.

+ +

Links displayed inline with separators

+ +

Exigências

+ +

Os itens tipicamente são exibidos em linha com um separador para indicar uma hierarquia entre páginas individuais.

+ +

Receita

+ +

{{EmbedGHLiveSample("css-examples/css-cookbook/breadcrumb-navigation.html", '100%', 530)}}

+ + + +

Faça escolhas

+ +

Esse padrão é apresentado usando um layout flexível simples demonstrando como uma linha de CSS pode nos fornecer nossa navegação. Os separadores são adicionados usando o conteúdo gerado por CSS. Você pode alterá-las para qualquer separador que desejar.

+ +

Preocupações com acessibilidade

+ +

Eu utilizei os atributos aria-label e aria-current para ajudar os usuários a entender o que é essa navegação e onde a página atual está na estrutura. Veja os links relacionados para mais informações.

+ +

Compatibilidade com navegadores

+ +

Os vários métodos de layout têm diferente suporte para o navegador. Veja os gráficos abaixo para obter detalhes sobre o suporte básico para as propriedades usadas.

+ + + +

Flexbox

+ +

{{Compat("css.properties.flex")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/css/layout_cookbook/index.html b/files/pt-br/web/css/layout_cookbook/index.html new file mode 100644 index 0000000000..c829a8e4d3 --- /dev/null +++ b/files/pt-br/web/css/layout_cookbook/index.html @@ -0,0 +1,85 @@ +--- +title: CSS Layout cookbook +slug: Web/CSS/Layout_cookbook +tags: + - CSS + - Layout + - livro de receitas + - receitas +translation_of: Web/CSS/Layout_cookbook +--- +
{{CSSRef}}
+ +

O livro de receitas (Cookbook) de layout CSS visa reunir receitas para padrões de layout comuns, coisas que você pode precisar implementar em seus próprios sites. Além de fornecer código que você pode usar como ponto de partida em seus projetos, essas receitas destacam as diferentes maneiras pelas quais as especificações de layout podem ser usadas e as escolhas que você pode fazer como desenvolvedor.

+ +
+

Note: Se você é novo no layout CSS, então primeiro você pode dar uma olhada em nosso módulo de aprendizado de layout CSS, pois isso lhe dará o básico de que você precisa para usar as receitas aqui.

+
+ +

As Receitas

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
RecipeDescriptionLayout Methods
Media objectsUma caixa de duas colunas com uma imagem de um lado e um texto descritivo do outro, por ex. um post no facebook ou um tweet.CSS Grid, {{cssxref("float")}} fallback, {{cssxref("fit-content")}} sizing
ColumnsQuando escolher layout de múltiplas colunas, flexbox ou grid para suas colunas.CSS Grid, Multicol, Flexbox
Center an elementComo centralizar um item horizontalmente e verticalmente.Flexbox, Box Alignment
Sticky footersCriando um rodapé que fica na parte inferior do contêiner ou viewport quando o conteúdo é menor.CSS Grid, Flexbox
Split navigationUm padrão de navegação em que alguns links são visualmente separados dos outros.Flexbox, {{cssxref("margin")}}
Breadcrumb navigationCriando uma lista de links para permitir que o visitante navegue de volta pela hierarquia da página.Flexbox
List group with badgesUma lista de itens com um acessório para exibir uma contagem.Flexbox, Box Alignment
PaginationLinks para páginas de conteúdo (como resultados de pesquisa).Flexbox, Box Alignment
CardUm componente de notas/cartão, exibido em uma grade de notas/cartão.Grid Layout
Grid wrapperPara alinhar o conteúdo da grade em um wrapper central, ao mesmo tempo em que permite que os itens sejam quebrados.CSS Grid
+ +

Contribuir com uma receita

+ +

Como com todo o MDN, gostaríamos que você contribuísse com uma receita no mesmo formato que os mostrados acima. Veja esta página para um modelo e diretrizes para escrever seu próprio exemplo.

diff --git a/files/pt-br/web/css/layout_cookbook/media_objects/index.html b/files/pt-br/web/css/layout_cookbook/media_objects/index.html new file mode 100644 index 0000000000..d62d36fb4e --- /dev/null +++ b/files/pt-br/web/css/layout_cookbook/media_objects/index.html @@ -0,0 +1,80 @@ +--- +title: 'Recipe: Media objects' +slug: Web/CSS/Layout_cookbook/Media_objects +translation_of: Web/CSS/Layout_cookbook/Media_objects +--- +
{{CSSRef}}
+ +

Media Object (Objeto de Mídia) é um padrão que vemos em toda web. Nomeado por Nicole Sullivan refere-se a uma caixa de duas colunas com uma imagem de um lado e texto descritivo do outro, por ex. uma postagem no facebook ou tweet.

+ +

+ +

Exigências

+ +

O Padrão Media Object precisa de algumas ou todas as seguintes características:

+ +
    +
  • Empilhados no Celular, duas colunas no Computador.
  • +
  • A imagem pode estar à esquerda ou à direita.
  • +
  • A imagem pode ser pequena ou grande.
  • +
  • Media Objects (Objetos de Mídia) podem ser aninhados.
  • +
  • O Media Object deve limpar o conteúdo, não importando o tamanho.
  • +
+ +

A receita

+ +

{{EmbedGHLiveSample("css-examples/css-cookbook/media-objects.html", '100%', 1200)}}

+ + + +

Escolhas feitas

+ +

Eu escolhi usar o Layout de Grade para o Media Object (Objeto de Layout), pois ele permite controlar o layout em duas dimensões quando preciso. Isso significa que, quando temos um rodapé, com conteúdo curto acima, o rodapé pode ser empurrado para a parte inferior do Media Object (Objeto de Layout).

+ +

Outro motivo para usar o Layout de Gride é para que eu possa usar {{cssxref("fit-content")}} para o tamanho da faixa de imagem. Usando fit-content com um tamanho máximo de 200 pixels, quando temos uma imagem pequena como o ícone, a faixa fica tão grande quanto o tamanho dessa imagem — o tamanho max-content. Se a imagem for maior, a faixa para de crescer em 200 pixels e, como a imagem possui {{cssxref("max-width ")}} de 100% aplicado, ele diminui para que continue a caber dentro da coluna.

+ +

Usando {{cssxref("grid-template-areas")}} para alcançar o layout, eu posso ver o padrão no CSS. Eu defino minha grade quando tivermos uma largura máxima de 500 pixels, em dispositivos menores o Media Object empilha.

+ +

Uma opção para o padrão é girá-lo para mudar a imagem para o outro lado — isso é feito adicionando a classe media-flip, que define um modelo de grade invertida, fazendo com que o layout seja espelhado.

+ +

Quando aninhamos um media object (Objeto de Layout) dentro do outro, precisamons colocá-lo na segunda faixa no layout regular, e na primeira faixa quando invertida.

+ +

Fallbacks (Alternativas, Plano B)

+ +

Existem várias alternativas possíveis para esse padrão, dependendo dos navegadores que você deseja oferecer suporte. Um bom exemplo seria flutuar a imagem para a esquerda e adicionar uma correção clara à caixa para garantir que ela contivesse as flutuações.

+ +

{{EmbedGHLiveSample("css-examples/css-cookbook/media-objects-fallback.html", '100%', 1200)}}

+ + + +

Depois que os elementos flutuantes se tornam itens da grade, o flutuador não se aplica mais; portanto, você não precisa fazer nada de especial para limpá-lo.

+ +

O que você precisará fazer é remover as margens aplicadas ao item e as larguras que não precisamos em um contexto de grade (nós temos o {{cssxref("gap")}} propriedade para controlá-lo em grades, e a faixa assume o controle do dimensionamento).

+ +

Recursos relevantes no MDN

+ + + +

Compatibilidade do Navegador

+ +

Os vários métodos de layout tem suporte diferente para os navegadores. Veja os gráficos abaixo para obter detalhes sobre o suporte básico para as propriedades usadas.

+ +

A tabela de compatibilidade nesta página é gerada a partir de dados estruturados. Se você deseja contribuir com os dados, confira https://github.com/mdn/browser-compat-data e envie-nos uma solicitação de recebimento.

+ +

Áreas de Modelo de Grade

+ +

{{Compat("css.properties.grid-template-areas")}}

+ +

Flutuador

+ +

{{Compat("css.properties.float")}}

diff --git a/files/pt-br/web/css/letter-spacing/index.html b/files/pt-br/web/css/letter-spacing/index.html new file mode 100644 index 0000000000..11ae4a85d0 --- /dev/null +++ b/files/pt-br/web/css/letter-spacing/index.html @@ -0,0 +1,118 @@ +--- +title: letter-spacing +slug: Web/CSS/letter-spacing +translation_of: Web/CSS/letter-spacing +--- +
{{CSSRef}}
+ +

A propriedade CSS letter-spacing específica o comportamento do espaçamento entre caracteres de texto.

+ +
{{EmbedInteractiveExample("pages/css/letter-spacing.html")}}
+ + + +

Syntax

+ +
/* Keyword value */
+letter-spacing: normal;
+
+/* <length> values */
+letter-spacing: 0.3em;
+letter-spacing: 3px;
+letter-spacing: .3px;
+
+/* Global values */
+letter-spacing: inherit;
+letter-spacing: initial;
+letter-spacing: unset;
+
+ +

Values

+ +
+
normal
+
O espaçamento de letras normal para a fonte atual. Ao contrário de um valor de 0, essa palavra-chave permite que o {{glossary("agente do usuário")}} altere o espaço entre os caracteres para justificar o texto.
+
{{cssxref("<length>")}}
+
Especifica o espaço adicional entre caracteres, além do espaço padrão entre os caracteres. Os valores podem ser negativos, mas pode haver limites específicos da implementação. Os agentes de usuário podem não aumentar ou diminuir o espaço inter-personagem para justificar o texto.
+
+ +

Formal syntax

+ +
{{csssyntax}}
+ +

Examples

+ +

HTML

+ +
<p class="normal">letter spacing</p>
+<p class="em-wide">letter spacing</p>
+<p class="em-wider">letter spacing</p>
+<p class="em-tight">letter spacing</p>
+<p class="px-wide">letter spacing</p>
+
+ +

CSS

+ +
.normal   { letter-spacing: normal; }
+.em-wide  { letter-spacing: 0.4em; }
+.em-wider { letter-spacing: 1em; }
+.em-tight { letter-spacing: -0.05em; }
+.px-wide  { letter-spacing: 6px; }
+
+ +

Result

+ +

{{ EmbedLiveSample('Examples', 440, 185) }}

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Text', '#letter-spacing-property', 'letter-spacing')}}{{Spec2('CSS3 Text')}}No change.
{{SpecName('CSS3 Transitions', '#animatable-css', 'letter-spacing')}}{{Spec2('CSS3 Transitions')}}Defines letter-spacing as animatable.
{{SpecName('CSS2.1', 'text.html#propdef-letter-spacing', 'letter-spacing')}}{{Spec2('CSS2.1')}}No change.
{{SpecName('SVG1.1', 'text.html#LetterSpacingProperty', 'letter-spacing')}}{{Spec2('SVG1.1')}}Initial SVG definition.
{{SpecName('CSS1', '#letter-spacing', 'letter-spacing')}}{{Spec2('CSS1')}}Initial definition.
+ +

{{cssinfo}}

+ +

Browser compatibility

+ + + +

{{Compat("css.properties.letter-spacing")}}

+ +

See also

+ +
    +
  • {{cssxref("font-kerning")}}
  • +
diff --git a/files/pt-br/web/css/line-break/index.html b/files/pt-br/web/css/line-break/index.html new file mode 100644 index 0000000000..5a66eb6999 --- /dev/null +++ b/files/pt-br/web/css/line-break/index.html @@ -0,0 +1,64 @@ +--- +title: line-break +slug: Web/CSS/line-break +translation_of: Web/CSS/line-break +--- +
{{CSSRef}}{{SeeCompatTable}}
+ +

A propriedade CSS line-break é usada para especificar como (ou se) quebrar linhas.

+ +

Sintaxe

+ +
/* Keyword values */
+line-break: auto;
+line-break: loose;
+line-break: normal;
+line-break: strict;
+
+/* Valores Globais */
+line-break: inherit;
+line-break: initial;
+line-break: unset;
+
+ +

Valores

+ +
+
auto
+
quebra o texto usando a regra padrão de quebra de linha.
+
loose
+
quebra o texto usando a regra de quebra de linha que é mais curta, como um jornal.
+
normal
+
quebra o texto usando a regra padrão de quebra de linha.
+
strict
+
quebra o texto usando uma regra rigorosa para a quebra de linha.
+
+ +

Sintaxe formal

+ +
{{csssyntax}}
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçõesStatusComentário
{{SpecName('CSS3 Text', '#line-break-property', 'line-break')}}{{Spec2('CSS3 Text')}}Definição inicial
+ +

{{cssinfo}}

+ +

Compatibilidade entre Navegadores

+ +

{{Compat("css.properties.line-break")}}

diff --git a/files/pt-br/web/css/margin-bottom/index.html b/files/pt-br/web/css/margin-bottom/index.html new file mode 100644 index 0000000000..a2990e2ba6 --- /dev/null +++ b/files/pt-br/web/css/margin-bottom/index.html @@ -0,0 +1,135 @@ +--- +title: margin-bottom +slug: Web/CSS/margin-bottom +translation_of: Web/CSS/margin-bottom +--- +
{{CSSRef}}
+ +

A propriedade CSS  margin-bottom  define a margin area na parte inferior de um elemento. Um valor positivo coloca o valor mais longe de outros elementos vizinhos, enquanto um valor negativo, aproxima.

+ +
{{EmbedInteractiveExample("pages/css/margin-bottom.html")}}
+ + + +

The effect of the CSS margin-bottom property on the element box

+ +

A propriedade não tem efeito em non-replaced elementos inline, como {{HTMLElement("span")}} ou {{HTMLElement("code")}}.

+ +

Sintaxe

+ +
/* <length> values */
+margin-bottom: 10px;  /* Um tamanho absoluto */
+margin-bottom: 1em;   /* relativo ao tamanho do texto */
+margin-bottom: 5%;    /* relativo à largura do container do bloco mais próximo */
+
+/* Keyword values */
+margin-bottom: auto;
+
+/* Global values */
+margin-bottom: inherit;
+margin-bottom: initial;
+margin-bottom: unset;
+
+ +

A propriedade margin-bottom é especificada como a palavra chave auto, ou a <length>, ou a<percentage>. Esse valor pode ser positivo, zero ou negativo

+ +

Values

+ +
+
{{cssxref("<length>")}}
+
O tamanho de uma margin com um valor fixo
+
{{cssxref("<percentage>")}}
+
O tamanho de uma margin como porcentagem, é relativa com o tamanho do bloco pai.
+
auto
+
O navegador seleciona um valor adequado para usar. Veja {{cssxref("margin")}}.
+
+ +

Sintaxe formal

+ +
{{csssyntax}}
+ +

Exemplo

+ +

HTML

+ +
<div class="container">
+<div class="box0">Box 0</div>
+<div class="box1">Box 1</div>
+<div class="box2">Box one's negative margin pulls me up</div>
+</div>
+ +

CSS

+ +

CSS para definir margin-bottom e height

+ +
.box0 {
+    margin-bottom:1em;
+    height:3em;
+}
+.box1 {
+    margin-bottom:-1.5em;
+    height:4em;
+}
+.box2 {
+    border:1px dashed black;
+    border-width:1px 0;
+    margin-bottom:2em;
+}
+
+
+ +

Algumas definições para container e divs, para que o os efeitos de margin possam ser vistos com mais clareza

+ +
.container {
+    background-color:orange;
+    width:320px;
+    border:1px solid black;
+}
+div {
+    width:320px;
+    background-color:gold;
+}
+ +

{{ EmbedLiveSample('Example',350,200) }}

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('CSS3 Box', '#margin-bottom', 'margin-bottom')}}{{Spec2('CSS3 Box')}}Nenhuma mudança significativa
{{SpecName('CSS3 Transitions', '#animatable-css', 'margin-bottom')}}{{Spec2('CSS3 Transitions')}}Definir o margin-bottom como "animavel"
{{SpecName('CSS2.1', 'box.html#margin-properties', 'margin-bottom')}}{{Spec2('CSS2.1')}}Remove seu efeito nos elementos in-line.
{{SpecName('CSS1', '#margin-bottom', 'margin-bottom')}}{{Spec2('CSS1')}}Definição inicial
+ +

{{cssinfo}}

+ +

Compatibilidade dos Browsers

+ + + +

{{Compat("css.properties.margin-bottom")}}

diff --git a/files/pt-br/web/css/margin-top/index.html b/files/pt-br/web/css/margin-top/index.html new file mode 100644 index 0000000000..5151416465 --- /dev/null +++ b/files/pt-br/web/css/margin-top/index.html @@ -0,0 +1,145 @@ +--- +title: margin-top +slug: Web/CSS/margin-top +translation_of: Web/CSS/margin-top +--- +
{{CSSRef}}
+ +

Sumário

+ +

The effect of the CSS margin-top property on the element boxA propriedade CSS margin-top de um elemento indica o espaço acima do elemento. Valores negativos são aceitos.

+ +

Essa propriedade não tem efeito em elementos non-replaced inline elements, como {{HTMLElement("tt")}} ou {{HTMLElement("span")}}.

+ +

{{cssinfo}}

+ +

Sintaxe

+ +
/* Valores <length> */
+margin-top: 10px;        /* An absolute length */
+margin-top: 1em;         /* A length relative to the text size */
+margin-top: 5%;          /* A margin relative to the nearest block container's width */
+
+/* Valores padrão */
+margin-top: auto;
+
+/* Valores globais */
+margin-top: inherit;
+margin-top: initial;
+margin-top: unset;
+
+ +

Valores

+ +
+
<length>
+
Especifica um tamanho fixo. Veja {{cssxref("<length>")}} para possíveis valores.
+
<porcentagem>
+
Um {{cssxref("<percentage>")}} sempre relativo ao width do bloco.
+
auto
+
Veja {{cssxref("margin")}}.
+
+ +

Sintaxe formal

+ +
{{csssyntax}}
+ +

Exemplos

+ +
.content { margin-top:   5%; }
+.sidebox { margin-top: 10px; }
+.logo    { margin-top: -5px; }
+#footer  { margin-top:  1em; }
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('CSS3 Box', '#the-margin', 'margin-top')}}{{Spec2('CSS3 Box')}}Sem mudança significativa.
{{SpecName('CSS3 Transitions', '#animatable-css', 'margin-top')}}{{Spec2('CSS3 Transitions')}}Define margin-top como animável.
{{SpecName('CSS2.1', 'box.html#margin-properties', 'margin-top')}}{{Spec2('CSS2.1')}}Remove esse efeito em elementos inline.
{{SpecName('CSS1', '#margin-top', 'margin-top')}}{{Spec2('CSS1')}}Definição inicial.
+ +

Compatibilidade de navegadores

+ +

{{CompatibilityTable()}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico1.0{{CompatGeckoDesktop("1")}}3.03.51.0 (85)
Valor auto1.0{{CompatGeckoDesktop("1")}}6.0 (strict mode)3.51.0 (85)
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Suporte básico1.0{{CompatGeckoMobile("1")}}6.06.01.0
+
diff --git a/files/pt-br/web/css/margin/index.html b/files/pt-br/web/css/margin/index.html new file mode 100644 index 0000000000..037d22b5b0 --- /dev/null +++ b/files/pt-br/web/css/margin/index.html @@ -0,0 +1,172 @@ +--- +title: margin +slug: Web/CSS/margin +tags: + - CSS + - CSS Property + - Reference +translation_of: Web/CSS/margin +--- +
{{CSSRef}}
+ +

A propriedade margin do CSS define a área de margem nos quatro lados do elemento. É uma abreviação que define todas as margens individuais de uma só vez: {{cssxref("margin-top")}}, {{cssxref("margin-right")}}, {{cssxref("margin-bottom")}}, e {{cssxref("margin-left")}}.

+ +
{{EmbedInteractiveExample("pages/css/margin.html")}}
+ + + +

Sintaxe

+ +
/* Aplica para todos os quatro lados */
+margin: 1em;
+
+/* vertical | horizontal */
+margin: 5% auto;
+
+/* topo | horizontal | inferior */
+margin: 1em auto 2em;
+
+/* topo | direita | inferior | esquerda */
+margin: 2px 1em 0 auto;
+
+/* Valores globais */
+margin: inherit;
+margin: initial;
+margin: unset;
+
+ +

A propriedade margin pode ser especificada usando um, dois, três ou quatro valores. Cada valor deve ser um <length>, uma <percentage>, ou a palavra-chave auto. Cada valor pode ser positivo, zero ou negativo.

+ +
    +
  • Quando um valor é especificado, a mesma margem é aplicada para todos os quatro lados.
  • +
  • Quando dois valores são especificados, a primeira margem é aplicada aos lados superior e inferior, e a segunda aos lados esquerdo e direito.
  • +
  • Quando três valores são especificados, a primeira margem é apliacada ao topo, a segunda aos lados esquerdo e direito, e a terceira ao lado inferior.
  • +
  • Quando quatro valores são especificados, as margens são aplicadas aos lados superior, direito, inferior e esquerdo, nesta ordem (sentido horário).
  • +
+ +

Valores

+ +
+
{{cssxref("length")}}
+
O tamanho da margem como um valor fixo.
+
{{cssxref("percentage")}}
+
O tamanho da margem como um percetual, relativo à largura do bloco em que o elemento está contido.
+
auto
+
O navegador seleciona uma margem adequada para utilizar. Por exemplo, em alguns casos este valor pode ser utilizado para centralizar o elemento.
+
+ +

Sintaxe formal

+ +
{{csssyntax}}
+ +

Exemplos

+ +

Exemplo simples

+ +

HTML

+ +
<div class="center">Este elemento está centralizado.</div>
+
+<div class="outside">Este elemento está posicionado fora de seu bloco recipiente.</div>
+ +

CSS

+ +
.center {
+  margin: auto;
+  background: lime;
+  width: 66%;
+}
+
+.outside {
+  margin: 3rem 0 0 -3rem;
+  background: cyan;
+  width: 66%;
+}
+ +

{{ EmbedLiveSample('Simple_example','100%',120) }}

+ +

Mais exemplos

+ +
margin: 5%;                 /* todos os lados: margem de 5% */
+
+margin: 10px;               /* todos os lados: margem de 10px */
+
+margin: 1.6em 20px;         /* topo e inferior:    margem de 1.6em */
+                            /* esquerda e direita: margem de 20px  */
+
+margin: 10px 3% 1em;        /* topo:               margem de 10px */
+                            /* esquerda e direita: margem de 3%   */
+                            /* inferior:           margem de 1em  */
+
+margin: 10px 3px 30px 5px;  /* topo:     margem de 10px */
+                            /* direita:  margem de 3px  */
+                            /* inferior: margem de 30px */
+                            /* esquerda: margem de 5px  */
+
+margin: 2em auto;           /* topo e inferior: margem de 2em          */
+                            /* caixa está horizontalmente centralizada */
+
+margin: auto;               /* topo e inferior: margem de 0            */
+                            /* caixa está horizontalmente centralizada */
+
+ +

Notas

+ +

Centralização horizontal

+ +

Para centralizar algo horizontalmente em navegadores modernos, você pode utilizar display: flex; justify-content: center;

+ +

Contudo, em navegadores antigos, como IE8-9 que não suporta layout flexbox, estes não estão disponíveis. Para centralizar um elemento dentro de seu pai, use margin: 0 auto; .

+ +

Colapso de margens

+ +

Às vezes, as margens superior e inferior de elementos são colapsadas em uma única margem que é igual à maior das duas margens. Veja Dominando margin collapsing para mais informações.

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{ SpecName('CSS3 Box', '#margin', 'margin') }}{{ Spec2('CSS3 Box') }}Nenhuma mudança significativa.
{{ SpecName('CSS3 Transitions', '#animatable-css', 'margin') }}{{ Spec2('CSS3 Transitions') }}Define margin como animável.
{{ SpecName('CSS2.1', 'box.html#margin-properties', 'margin') }}{{ Spec2('CSS2.1') }}Remove seu efeito em elementos inline.
{{ SpecName('CSS1', '#margin', 'margin') }}{{ Spec2('CSS1') }}Definição inicial.
+ +

{{cssinfo}}

+ +

Compatibilidade de navegadores

+ + + +

{{Compat("css.properties.margin")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/css/max-width/index.html b/files/pt-br/web/css/max-width/index.html new file mode 100644 index 0000000000..b734872b64 --- /dev/null +++ b/files/pt-br/web/css/max-width/index.html @@ -0,0 +1,200 @@ +--- +title: max-width +slug: Web/CSS/max-width +tags: + - CSS + - Dimensões + - Layout + - Limites + - Máximo + - Propriedade CSS + - Referencia + - largura + - max-width + - 'receita:propriedade-css' + - tamanho +translation_of: Web/CSS/max-width +--- +
{{CSSRef}}
+ +
A propriedade max-width do CSS estabelece a largura máxima de um elemento. Ele evita que o valor usado da propriedade {{ cssxref("width") }} se torne maior que o valor especificado por max-width.
+ +
{{EmbedInteractiveExample("pages/css/max-width.html")}}
+ + + +

max-width substitui {{cssxref("width")}}, mas {{cssxref("min-width")}} substitui max-width.

+ +

Sintaxe

+ +
/* <length> valor */
+max-width: 3.5em;
+
+/* <porcentagem> valor */
+max-width: 75%;
+
+/* Valores de keyword */
+max-width: none;
+max-width: max-content;
+max-width: min-content;
+max-width: fit-content;
+max-width: fill-available;
+
+/* Valores Globais */
+max-width: inherit;
+max-width: initial;
+max-width: unset;
+
+ +

Valores

+ +
+
{{cssxref("<length>")}}
+
Define a max-width como um valor absoluto.
+
{{cssxref("<percentage>")}}
+
Define a max-width como uma porcentagem da largura do bloco que o contém.
+
+ +

Valores Keyword

+ +
+
none
+
A largura não possui valor máximo. (padrão)
+
max-content{{experimental_inline()}}
+
A max-width intrínseca preferida.
+
min-content{{experimental_inline()}}
+
O mínimo max-width intrínseco.
+
fit-content({{cssxref("<length-percentage>")}})
+
Use a fórmula fit-content com o espaço disponível substituído pelo argumento especificado, i.e. min(max-content, max(min-content, argumento)).
+
+ +

Preocupações de Acessibilidade

+ +

Certifique-se que os elementos definidos com max-width não sejam truncados e/ou não obscureçam outros conteúdos quando a página for ampliada para aumentar o tamanho do texto.

+ +
+
fill-available{{experimental_inline()}}
+
A largura contida do bloco sem o margin, border e padding horizontal. (Note que alguns navegadores implementaram um nome antigo para essa keyword, available.)
+
fit-content{{experimental_inline()}}
+
O mesmo que max-content.
+
+ +

Sintaxe formal

+ +
{{csssyntax}}
+ +

Exemplos

+ +

Definindo a largura máxima em pixels

+ +

Neste exemplo, o "filho" terá 150 pixels de largura ou a largura do "pai", o que for menor:

+ +
+
<div id="pai">
+  <div id="filho">
+    Fusce pulvinar vestibulum eros, sed luctus ex lobortis quis.
+  </div>
+</div>
+
+ +
#pai {
+  background: lightblue;
+  width: 300px;
+}
+
+#filho {
+  background: gold;
+  width: 100%;
+  max-width: 150px;
+}
+
+
+ +

Resultado

+ +

{{EmbedLiveSample("Setting_max_width_in_pixels", 350, 100)}}

+ + + + + + + +

O valor de fit-content pode ser usado para atribuir o comprimento de um elemento no tamanho intrínseco necessário pelo seu conteúdo:

+ +
+ + +
#parent {
+  background: lightblue;
+  width: 300px;
+}
+
+#child  {
+  background: gold;
+  width: 100%;
+  max-width: -moz-fit-content;
+  max-width: -webkit-fit-content;
+}
+
+
+ +

{{EmbedLiveSample("fit-content-demo", 400, 100)}}

+ +

Preocupações de acessibilidade

+ +

Garantir que os elementos atribuidos com max-width não estejam cortados e/ou não obscureça outro conteúdo quando a página é ampliada para aumentar o tamanho do texto. 

+ + + +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{ SpecName('CSS3 Sizing', '#width-height-keywords', 'max-width') }}{{ Spec2('CSS3 Sizing') }}Adiciona o max-content, min-content, fit-content, e fill-available keywords. (Ambos CSS3 Box e CSS3 Writing Modes são rascunhos usados para definir essas keywords, mas foram substituídas por essa especificação.)
{{ SpecName('CSS3 Transitions', '#animatable-css', 'max-width') }}{{ Spec2('CSS3 Transitions') }}Define max-width como animável.
{{ SpecName('CSS2.1', 'visudet.html#min-max-widths', 'max-width') }}{{ Spec2('CSS2.1') }}Definição inicial.
+ +

{{cssinfo}}

+ +

Compatibilidade com navegador

+ + + +

{{Compat("css.properties.max-width")}}

+ +

Veja também

+ +
    +
  • {{ Cssxref("width") }}, {{ Cssxref("min-width") }}, {{ Cssxref("max-height") }}
  • +
  • The box model, {{ Cssxref("box-sizing") }}
  • +
diff --git a/files/pt-br/web/css/media_queries/index.html b/files/pt-br/web/css/media_queries/index.html new file mode 100644 index 0000000000..6cdfdb621f --- /dev/null +++ b/files/pt-br/web/css/media_queries/index.html @@ -0,0 +1,118 @@ +--- +title: Media queries +slug: Web/CSS/Media_Queries +tags: + - CSS + - Design Responsivo + - Media Queries + - Referencia + - media query +translation_of: Web/CSS/Media_Queries +--- +
{{CSSRef}}
+ +

Media Queries (consultas de mídia ) são um módulo de CSS que definem expressões, permitindo ajustar visualizações a uma variedade específica de dispositivos de saída sem mudar o conteúdo.

+ +

Referências

+ +

At-rules

+ +
+
    +
  • {{cssxref("@import")}}
  • +
  • {{cssxref("@media")}}
  • +
+
+ +

Guides

+ +
+
Usando Media Queries
+
Apresenta o que fazem as media queries (consultas de mídia) e explica as possíveis expressões.
+
Testing media queries
+
Explains how to test a media query programmatically, from JavaScript.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{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')}}Initial definition
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1.0{{CompatGeckoDesktop(1.7)}}9.09.21.3
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support1.0{{CompatGeckoMobile(1.7)}}9.09.03.1
+
diff --git a/files/pt-br/web/css/microsoft_extensions/index.html b/files/pt-br/web/css/microsoft_extensions/index.html new file mode 100644 index 0000000000..5779ec6065 --- /dev/null +++ b/files/pt-br/web/css/microsoft_extensions/index.html @@ -0,0 +1,114 @@ +--- +title: Extensões CSS da Microsoft +slug: Web/CSS/Microsoft_Extensions +translation_of: Web/CSS/Microsoft_Extensions +--- +
{{CSSRef}}
+ +

Aplicativos da Microsoft, como Edge e Internet Explorer, suportam uma série de extensões especiais da Microsoft para css. Essas extensões são prefixadas com .-ms-

+ +

Propriedades somente para Microsoft (evite usar em sites)

+ +
+

Nota: Essas propriedades funcionarão apenas em aplicativos da Microsoft e não estão em uma faixa de padrões.

+
+ +
+
    +
  • {{CSSxRef("-ms-acelerador")}}
  • +
  • {{CSSxRef("-ms-block-progression")}}
  • +
  • {{CSSxRef("-ms-content-zoom-chaining")}}
  • +
  • {{CSSxRef("-ms-content-zooming")}}
  • +
  • {{CSSxRef("-ms-content-zoom-limit")}}
  • +
  • {{CSSxRef("-ms-content-zoom-limit-max")}}
  • +
  • {{CSSxRef("-ms-content-zoom-limit-min")}}
  • +
  • {{CSSxRef("-ms-content-zoom-snap")}}
  • +
  • {{CSSxRef("-ms-content-zoom-snap-points")}}
  • +
  • {{CSSxRef("-ms-content-zoom-snap-type")}}
  • +
  • {{CSSxRef("-ms-filter")}} {{Obsolete_Inline}}
  • +
  • {{CSSxRef("-ms-flow-from")}}
  • +
  • {{CSSxRef("-ms-flow-into")}}
  • +
  • {{CSSxRef("-ms-high-contrast-adjust")}}
  • +
  • {{CSSxRef("-ms-hifenate-limit-chars")}}
  • +
  • {{CSSxRef("-ms-hifenate-limit-lines")}}
  • +
  • {{CSSxRef("-ms-hifenate-limit-zone")}}
  • +
  • {{CSSxRef("-ms-ime-align")}}
  • +
  • {{CSSxRef("-ms-overflow-style")}}
  • +
  • {{CSSxRef("-ms-scrollbar-3dlight-color")}} {{Obsolete_Inline}}
  • +
  • {{CSSxRef("-ms-scrollbar-seta-cor")}} {{Obsolete_Inline}}
  • +
  • {{CSSxRef("-ms-scrollbar-base-cor")}} {{Obsolete_Inline}}
  • +
  • {{CSSxRef("-ms-scrollbar-darkshadow-color")}} {{Obsolete_Inline}}
  • +
  • {{CSSxRef("-ms-scrollbar-face-color")}} {{Obsolete_Inline}}
  • +
  • {{CSSxRef("-ms-scrollbar-highlight-color")}} {{Obsolete_Inline}}
  • +
  • {{CSSxRef("-ms-scrollbar-shadow-color")}} {{Obsolete_Inline}}
  • +
  • {{CSSxRef("-ms-scrollbar-track-color")}} {{Obsolete_Inline}}
  • +
  • {{CSSxRef("-ms-scroll-chaining")}}
  • +
  • {{CSSxRef("-ms-scroll-limit")}}
  • +
  • {{CSSxRef("-ms-scroll-limit-x-max")}}
  • +
  • {{CSSxRef("-ms-scroll-limit-x-min")}}
  • +
  • {{CSSxRef("-ms-scroll-limit-y-max")}}
  • +
  • {{CSSxRef("-ms-scroll-limit-y-min")}}
  • +
  • {{CSSxRef("-ms-scroll-rails")}}
  • +
  • {{CSSxRef("-ms-scroll-snap-points-x")}}
  • +
  • {{CSSxRef("-ms-scroll-snap-points-y")}}
  • +
  • {{CSSxRef("-ms-scroll-snap-x")}}
  • +
  • {{CSSxRef("-ms-scroll-snap-y")}}
  • +
  • {{CSSxRef("-ms-scroll-translation")}}
  • +
  • {{CSSxRef("-ms-text-autospace")}}
  • +
  • {{CSSxRef("-ms-touch-select")}}
  • +
  • {{CSSxRef("-ms-wrap-flow")}}
  • +
  • {{CSSxRef("-ms-wrap-margin")}}
  • +
  • {{CSSxRef("-ms-wrap-through")}}
  • +
  • {{CSSxRef("zoom")}}
  • +
+
+ +

Pseudo-elements

+ +
+
    +
  • {{CSSxRef("::-ms-browse")}}
  • +
  • {{CSSxRef("::-ms-check")}}
  • +
  • {{CSSxRef("::-ms-clear")}}
  • +
  • {{CSSxRef("::-ms-expand")}}
  • +
  • {{CSSxRef("::-ms-fill")}}
  • +
  • {{CSSxRef("::-ms-fill-lower")}}
  • +
  • {{CSSxRef("::-ms-fill-upper")}}
  • +
  • {{CSSxRef("::-ms-reveal")}}
  • +
  • {{CSSxRef("::-ms-thumb")}}
  • +
  • {{CSSxRef("::-ms-ticks-after")}}
  • +
  • {{CSSxRef("::-ms-ticks-before")}}
  • +
  • {{CSSxRef("::-ms-tooltip")}}
  • +
  • {{CSSxRef("::-ms-track")}}
  • +
  • {{CSSxRef("::-ms-value")}}
  • +
+
+ +

Media features

+ +
+
    +
  • {{CSSxRef("@media/-ms-high-contrast","-ms-high-contrast")}}
  • +
+
+ + + +
+
    +
  • {{DOMxRef("msContentZoomFactor")}}
  • +
  • {{DOMxRef("msGetPropertyEnabled")}}
  • +
  • {{DOMxRef("msGetRegionContent")}}
  • +
  • {{DOMxRef("MSRangeCollection")}}
  • +
  • {{DOMxRef("msRegionOverflow")}}
  • +
+
+ +

See also

+ + diff --git a/files/pt-br/web/css/min-height/index.html b/files/pt-br/web/css/min-height/index.html new file mode 100644 index 0000000000..7b1a9b36f2 --- /dev/null +++ b/files/pt-br/web/css/min-height/index.html @@ -0,0 +1,181 @@ +--- +title: min-height +slug: Web/CSS/min-height +translation_of: Web/CSS/min-height +--- +

{{ CSSRef() }}

+ +

Sumário

+ +

A propriedade min-height do CSS é usado para definir a altura mínima de um determinado elemento. Ele impede que o valor usado da propriedade {{ Cssxref("height") }} se torne menor que o valor especificado para min-height.
+ O valor de  {{ Cssxref("min-height") }} substitui os dois {{ Cssxref("max-height") }} e {{ Cssxref("height") }}.

+ +

{{cssinfo}}

+ +

Sintaxe

+ +
sintaxe forma: {{csssyntax("min-height")}}
+
+ +
min-height: 3.5em
+min-height: 10%
+min-height: max-content
+min-height: min-content
+min-height: fit-content
+min-height: fill-available
+
+min-height: inherit
+
+ +

Valores

+ +
+
<length>
+
O valor fixo mínimo da altura. Veja {{cssxref("<length>")}} para possíveis unidades. Valores negativos fazem da declaração inválida.
+
<percentage>
+
O valor fixo mínimo da altura expressado como uma {{cssxref("<percentage>")}} do conteúdo da altura do bloco. Valores negativos fazem da declaração inválida.
+
max-content {{ experimental_inline() }}
+
The intrinsic preferred height.
+
min-content {{ experimental_inline() }}
+
The intrinsic minimum height.
+
fill-available{{ experimental_inline() }}
+
The containing block height minus horizontal margin, border and padding. Some browsers implement an ancient name for this keyword, available.
+
fit-content {{ experimental_inline() }}
+
According CSS3 Box, this is a synonym of min-content. CSS3 Sizing defines a more complex algorithm, but no browser implements it, even in an experimental way.
+
+ +

Exemplos

+ +
table { min-height: 75%; }
+
+form { min-height: 0; }
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{ SpecName('CSS3 Sizing', '#width-height-keywords', 'min-height') }}{{ Spec2('CSS3 Sizing') }}Adds the max-content, min-content, fit-content, and fill-available keywords.
+ Both CSS3 Box and CSS3 Writing Modes drafts defined at some point these keywords. These drafts are superseded by this spec.
{{ SpecName('CSS3 Flexbox', '#min-auto', 'min-height') }}{{ Spec2('CSS3 Flexbox') }}An earlier revision of the spec added the auto keyword and used it as the initial value. The CSSWG subsequently resolved to revert this change, however. As of March 29, 2013, the latest Editor's Draft doesn't modify the min-width property anymore (i.e. it no longer introduces the auto value).
{{ SpecName('CSS3 Transitions', '#animatable-css', 'min-height') }}{{ Spec2('CSS3 Transitions') }}Defines min-height as animatable.
{{ SpecName('CSS2.1', 'visudet.html#min-max-heights', 'min-height') }}{{ Spec2('CSS2.1') }}Initial definition.
+ + + +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support1.0{{ CompatGeckoDesktop("1.9") }}7.04.01.0
+ 2.0.2 (416) for positioned elements
applies to <table> [1]{{ CompatNo() }}{{ CompatVersionUnknown() }}{{ CompatNo() }}{{ CompatVersionUnknown() }}{{ CompatNo() }}
max-content, min-content, fit-content, and fill-available {{ experimental_inline() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
auto{{obsolete_inline(22)}}21.0{{ CompatGeckoDesktop("16.0") }}{{ CompatNo() }}12.10{{ CompatNo() }}
auto as initial value{{obsolete_inline(22)}}21.0{{ CompatGeckoDesktop("18.0") }}{{ CompatNo() }}12.10{{ CompatNo() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

Notas

+ +

[1] CSS 2.1 explicitly leaves the behavior of min-height with {{ HTMLElement("table") }} undefined. Therefore any behavior is CSS2.1-compliant; newer CSS specifications may define this behavior, so Web developers shouldn't rely on a specific one now.

+ +

[2] Due to bug ({{bug("307866")}}) Firefox doesn't hande min-height on elements with display: table-*.

+ +

Ver também

+ +
    +
  • {{ Cssxref("width") }}, {{ Cssxref("height") }}, {{ Cssxref("max-height") }}
  • +
  • The box model, {{ Cssxref("min-width") }}, {{ Cssxref("box-sizing") }}, {{ Cssxref("height") }}, {{ Cssxref("max-height") }}
  • +
diff --git a/files/pt-br/web/css/mix-blend-mode/index.html b/files/pt-br/web/css/mix-blend-mode/index.html new file mode 100644 index 0000000000..c8677e6545 --- /dev/null +++ b/files/pt-br/web/css/mix-blend-mode/index.html @@ -0,0 +1,164 @@ +--- +title: mix-blend-mode +slug: Web/CSS/mix-blend-mode +tags: + - CSS + - Propriedade CSS +translation_of: Web/CSS/mix-blend-mode +--- +

{{CSSRef}}

+ +

Resumo

+ +

A propriedade mix-blend-mode descreve como um elemento de conteúdo deve ser mesclado com os elementos abaixo dele no background.

+ +

{{cssinfo}}

+ +

Sintaxe

+ +
/* Valores para esta propriedade */
+mix-blend-mode: normal;
+mix-blend-mode: multiply;
+mix-blend-mode: screen;
+mix-blend-mode: overlay;
+mix-blend-mode: darken;
+mix-blend-mode: lighten;
+mix-blend-mode: color-dodge;
+mix-blend-mode: color-burn;
+mix-blend-mode: hard-light;
+mix-blend-mode: soft-light;
+mix-blend-mode: difference;
+mix-blend-mode: exclusion;
+mix-blend-mode: hue;
+mix-blend-mode: saturation;
+mix-blend-mode: color;
+mix-blend-mode: luminosity;
+
+/* Valores globais */
+mix-blend-mode: initial;
+mix-blend-mode: inherit;
+mix-blend-mode: unset;
+
+ +

Valores

+ +
+
<blend-mode>
+
É uma {{cssxref("<blend-mode>")}} que descreve qual mesclagem deve ser aplicada. Podem ser descritos vários valores, separados por vírgula.
+
+ +

Sintaxe formal

+ +
{{csssyntax}}
+ +

Exemplos

+ +
<svg>
+  <circle cx="40" cy="40" r="40" fill="red"/>
+  <circle cx="80" cy="40" r="40" fill="lightgreen"/>
+  <circle cx="60" cy="80" r="40" fill="blue"/>
+</svg>
+ +
circle { mix-blend-mode: screen; }
+ +

Resultado

+ +

{{EmbedLiveSample("Examples", "100%", "180")}}

+ +

Especificações

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('Compositing', '#mix-blend-mode', 'mix-blend-mode') }}{{ Spec2('Compositing') }}Initial specification.
+ +

Compatibilidade de navegadores

+ +

{{CompatibilityTable()}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support +

{{CompatChrome(41.0)}}

+
{{CompatGeckoDesktop('32.0')}}{{CompatUnknown()}}{{CompatVersionUnknown()}}8.0
SVG{{CompatNo}}{{CompatGeckoDesktop('32.0')}}{{CompatUnknown()}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support +

{{CompatChrome(41.0)}}

+
{{CompatGeckoMobile('32.0')}}{{CompatUnknown()}}{{CompatUnknown()}}8.0
SVG{{CompatNo}}{{CompatGeckoMobile('32.0')}}{{CompatUnknown()}}{{CompatNo}}{{CompatNo}}
+
+ +

 

+ +

Veja também

+ +
    +
  • {{cssxref("<blend-mode>")}}
  • +
  • {{cssxref("background-blend-mode")}}
  • +
diff --git a/files/pt-br/web/css/modelo_layout/index.html b/files/pt-br/web/css/modelo_layout/index.html new file mode 100644 index 0000000000..883cdbd4a4 --- /dev/null +++ b/files/pt-br/web/css/modelo_layout/index.html @@ -0,0 +1,25 @@ +--- +title: Modelo de layout +slug: Web/CSS/Modelo_layout +translation_of: Web/CSS/Layout_mode +--- +

O modelo de layout CSS, às vezes abreviado por layout, é um algoritimo que determina a posição e tamanho dos boxes baseado em como estes interagem com os boxes filhos e boxe ancestral. Há vários layouts:

+ +
    +
  • Block layout, designed for laying out documents. The block layout contains document-centric features, like the ability to float elements or to lay them out over multiple columns.
  • +
  • Inline layout, designed for laying out text.
  • +
  • Table layout, designed for laying out tables.
  • +
  • Positioned layout, designed for positioning elements without much interaction with other elements.
  • +
  • Flexible box layout, designed for laying out complex pages that can be resized smoothly.
  • +
  • Grid layout, designed for laying out elements relative to a fixed grid.
  • +
+ +
+

Note: Not all CSS properties apply to all layout modes. Most of them apply to one or two of them and have no effect if they are set on an element participating in another layout mode.

+
+ +

Veja Também

+ +
    +
  • {{CSS_key_concepts}}
  • +
diff --git a/files/pt-br/web/css/modelo_visual/index.html b/files/pt-br/web/css/modelo_visual/index.html new file mode 100644 index 0000000000..a37a0cc7b0 --- /dev/null +++ b/files/pt-br/web/css/modelo_visual/index.html @@ -0,0 +1,227 @@ +--- +title: Modelo de formatação visual +slug: Web/CSS/Modelo_Visual +tags: + - CSS + - CSS conceitos basicos + - Intermediário +translation_of: Web/CSS/Visual_formatting_model +--- +

{{CSSRef}}

+ +

The CSS visual formatting model is an algorithm that processes a document and displays it on visual media. This model is a basic concept of CSS.

+ +

The visual formatting model transforms each element of the document and generates zero, one, or several boxes that conform to the CSS box model. The layout of each box is defined by:

+ +
    +
  • The dimensions of the box: precisely defined or constrained, or not.
  • +
  • The type of box: inline, inline-level, atomic inline-level, block.
  • +
  • The positioning scheme: in the normal flow, a float, or absolute positioning.
  • +
  • The other elements in the tree: its children and neighbors.
  • +
  • The {{glossary("viewport")}} size and position.
  • +
  • Intrinsic dimensions of contained images.
  • +
  • Other external information.
  • +
+ +

The model renders a box, in relation to the edge of its containing block. Usually, a box establishes the containing block for its descendants. However, a box is not constrained by its containing block; when a box's layout goes outside the containing block, it is said to overflow.

+ +

 Gerando um Box

+ +

Box generation is the part of the CSS visual formatting model that creates boxes from the document's elements. Generated boxes are of different types, which affect how the visual formatting is done. The type of the box generated depends on the value of the {{ cssxref("display") }} CSS property.

+ +

Block-level elements and block boxes

+ +

An element is said to be block-level when the calculated value of its {{ cssxref("display") }} CSS property is: block, list-item, or table. A block-level element is visually formatted as a block (e.g., paragraph), intended to be vertically stacked.

+ +

Each block-level box participates in a block formatting context. Each block-level element generates at least one block-level box, called the principal block-level box. Some elements, like a list-item element, generating further boxes to handle bullets and other typographic elements introducing the list item, may generate more boxes. Most generate only the principal, block-level box.

+ +

The principal block-level box contains descendant-generated boxes and generated content. It is also the box involved in the positioning scheme.

+ +

venn_blocks.pngA block-level box may also be a block container box. A block container box is a box that contains only other block-level boxes, or creates an inline formatting context, thus containing only inline boxes.

+ +

It is important to note that the notions of a block-level box and block container box are disjoined. The first, describes how the box behaves with its parents and sibling. The second, how it interacts with its descendants. Some block-level boxes, like tables, aren't block container boxes. Reciprocally, some block container boxes, like non-replaced inline blocks and non-replaced table cells, aren't block-level boxes.

+ +

Block-level boxes that also are block container boxes are called block boxes.

+ +

Anonymous block boxes

+ +

In some cases, the visual formatting algorithm needs to add supplementary boxes. Because CSS selectors cannot style or name these boxes, they are called anonymous boxes.

+ +

Because selectors do not work with anonymous boxes, they cannot be styled via a stylesheet. This means that all inheritable CSS properties have the inherit value, and all non-inheritable CSS properties, have the initial value.

+ +

Block containing boxes contain only inline-level boxes, or only block-level boxes. But often the document contains a mix of both. In that case, anonymous block boxes are created around adjacent inline-level boxes.

+ +

Exemplo

+ +

If we take the following HTML code (with default styling applied to it, that is {{ HTMLElement("div") }} and {{ HTMLElement("p") }} elements have display:block :

+ +
<div>Some inline text <p>followed by a paragraph</p> followed by more inline text.</div>
+ +

Two anonymous block boxes are created: one for the text before the paragraph (Some inline text), and another for the text after it (followed by more inline text). This builds the following block structure:

+ +

anonymous_block-level_boxes.png

+ +

Leading to:

+ +
Some inline text
+followed by a paragraph
+followed by more inline text.
+
+ +

Unlike the {{ HTMLElement("p") }} element's box, Web developers cannot control the style of the two anonymous boxes. Inheritable properties take the value from the {{ HTMLElement("div") }}'s property value, like {{ cssxref("color") }} to define the color of the text, and set the others to the initial value. For example, they won't have a specific {{ cssxref("background-color") }}, it is always transparent, the initial value for that property, and thus the background of the <div> is visible. A specific background color can be applied to the <p> box. Similarly, the two anonymous boxes always use the same color for their text.

+ +

Another case that leads to the creation of anonymous block boxes, is an inline box that contains one or several block boxes. In that case, the box containing the block box is split into two inline boxes: one before, and one after the block box. All the inline boxes before the block box are then enclosed into an anonymous block box, so are the inline boxes following the block box. Therefore, the block box becomes the sibling of the two anonymous block boxes containing the inline elements.

+ +

If there are several block boxes, without inline content in-between, the anonymous block boxes are created before, and after the set of boxes.

+ +

Exemplo

+ +

If we take the following HTML code, with {{ HTMLElement("p") }} have display:inline and {{ HTMLElement("span") }} have display:block :

+ +
<p>Some <em>inline</em> text <span>followed by a paragraph</span> followed by more inline text.</p>
+ +

Two anonymous block boxes are created, one for the text before the span Element (Some inline text) and one for the text after it (followed by more inline text), which gives the following block structure:

+ +

+ +

Which leads to:

+ +
Some inline text
+followed by a paragraph
+followed by more inline text.
+
+ +

Inline-level elements and inline boxes

+ +

An element is said to be inline-level when the calculated value of its {{ cssxref("display") }} CSS property is: inline, inline-block or inline-table. Visually, it doesn't constitute blocks of contents, but is distributed in lines with other inline-level content. Typically, the content of a paragraph with different formatting, like emphasis or images, is made from inline-level elements.

+ +

venn_inlines.png

+ +
+

This diagram uses outdated terminology; see note below. Besides that, it is incorrect because the yellow ellipsis on the right side is per definition either identical to the one on the left side, or bigger than that (it could be a mathematical superset), because the spec says "Inline-level elements generate inline-level boxes, which are boxes that participate in an inline formatting context", see CSS 2.2, chapter 9.2.2

+
+ +

Inline-level elements generate inline-level boxes that are defined as boxes participating to an inline formatting context. Inline boxes are both inline-level boxes and boxes, whose contents participate in their container's inline formatting context. This is the case, for example, for all non-replaced boxes with display:inline. Inline-level boxes, whose contents do not participate in an inline formatting context, are called atomic inline-level boxes. These boxes, generated by replaced inline-level elements or by elements with a calculated {{ cssxref("display") }} value of inline-block or inline-table, are never split into several boxes, as is possible with inline boxes.

+ +
Note: Initially, atomic inline-level boxes were called atomic inline boxes. This was unfortunate, as they are not inline boxes. This was corrected in an erratum to the spec. Nevertheless, you can harmlessly read atomic inline-level box each time you meet atomic inline box in the literature, as this is only a name change.
+ +
Atomic inline boxes cannot be split into several lines in an inline formatting context. +
+
<style>
+  span {
+    display:inline; /* default value*/
+  }
+</style>
+<div style="width:20em;">
+   The text in the span <span>can be split in several
+   lines as it</span> is an inline box.
+</div>
+
+ +

which leads to:

+ +
The text in the span can be split into several lines as it is an inline box.
+ +
<style>
+  span {
+    display:inline-block;
+  }
+</style>
+<div style="width:20em;">
+   The text in the span <span>cannot be split in several
+   lines as it</span> is an inline-block box.
+</div>
+
+ +

which leads to:

+ +
The text in the span cannot be split into several lines as it is an inline-block box.
+
+
+ +

Anonymous inline boxes

+ +

As for block boxes, there are a few cases where inline boxes are created automatically by the CSS engine. These inline boxes are also anonymous as they cannot be named by selectors; they inherit the value of all inheritable properties, setting it to initial for all others.

+ +

The most common case where an anonymous inline box is created, is when some text is found as a direct child of a block box creating an inline formatting context. In that case, this text is included in the largest possible anonymous inline box. Also, space content, which would be removed by the behavior set in the {{ cssxref("white-space") }} CSS property, does not generate anonymous inline boxes because they would end empty.

+ +
Example TBD
+ +

Outros tipos de boxes

+ +

Line boxes

+ +

Line boxes are generated by the inline formatting context to represent a line of text. Inside a block box, a line box extends from one border of the box to the other. When there are floats, the line box starts at the rightmost border of the left floats and ends at the leftmost border of the right floats.

+ +

These boxes are technical, and Web authors do not usually have to bother with them.

+ +

Run-in boxes

+ +

Run-in boxes, defined using display:run-in, are boxes that are either block boxes or inline boxes, depending on the type of the following box. They can be used to create a title that runs inside its first paragraph when possible.

+ +
Note: Run-in boxes were removed from the CSS 2.1 standard, as they were insufficiently specified to allow for interoperable implementation. They may reappear in CSS3, but meanwhile, are considered experimental. They should not be used in production.
+ +

Model-induced boxes

+ +

Besides the inline and block formatting contexts, CSS specifies several additional content models that may be applied to elements. These additional models, used to describe specific layouts, may define additional box types:

+ +
    +
  • The table content model may create a table wrapper box and a table box, but also specific boxes like caption boxes.
  • +
  • The multi-column content model may create column boxes between the container box and the content.
  • +
  • The experimental grid, or flex-box content models, also create additional types of boxes.
  • +
+ +

Positioning schemes

+ +

Once boxes are generated, the CSS engine needs to position them on the layout. To do that, it uses one of the following algorithms:

+ +
    +
  • The normal flow - positions each box one after the other.
  • +
  • The floats algorithm - extracts the box from the normal flow and put it to the side of the containing box.
  • +
  • The absolute positioning scheme - positions a box within an absolute coordinate system that is established by its containing element. An absolutely positioned element can cover other elements.
  • +
+ +

Normal flow

+ +

In the normal flow, boxes are laid out one after the other. In a block formatting context, they are laid out vertically; in an inline formatting context, they are laid out horizontally. The normal flow is triggered when the CSS {{ cssxref("position") }} is set to the value static or relative, and if the CSS {{ cssxref("float") }} is set to the value none.

+ +

Exemplo

+ +
When in the normal flow, in a block formatting context, boxes are laid vertically one after the other out:
+
+[image]
+
+When in the normal flow, in an inline formatting context, boxes are laid horizontally one after the other out:
+
+[image]
+ +

There are two sub-cases of the normal flow: static positioning and relative positioning:

+ +
    +
  • In static positioning, triggered by the value static of the {{ cssxref("position") }} property, the boxes are drawn at the exact position defined by the normal flow layout.
    + [image]
  • +
  • In relative positioning, triggered by the value relative of the {{ cssxref("position") }} property, the boxes are drawn with an offset defined by the {{ cssxref("top") }}, {{ cssxref("bottom") }}, {{ cssxref("left") }} and {{ cssxref("right") }} CSS properties.
  • +
+ +

Floats

+ +

In the float positioning scheme, specific boxes (called floating boxes or simply floats) are positioned at the beginning, or end of the current line. This leads to the property that text (and more generally anything within the normal flow) flows along the edge of the floating boxes, except if told differently by the {{ cssxref("clear") }} CSS property.

+ +

The float positioning scheme for a box is selected, by setting the {{ cssxref("float") }} CSS property on that box to a value different than none and {{ cssxref("position") }} to static or relative. If {{ cssxref("float") }} is set to left, the float is positioned at the beginning of the line box. If set to right, the float is positioned at the end of the line box. In either case, the line box is shrunk to fit alongside the float.

+ +

[image]

+ +

Absolute positioning

+ +

In the absolute positioning scheme, boxes are entirely removed from the flow and don't interact with it at all. They are positioned relative to their containing block using the {{ cssxref("top") }}, {{ cssxref("bottom") }}, {{ cssxref("left") }} and {{ cssxref("right") }} CSS properties.

+ +

An element is absolutely positioned if the {{ cssxref("position") }} is set to absolute or fixed.

+ +

With a fixed positioned element, the containing block is the viewport. The position of the element is absolute within the viewport. Scrolling does not change the position of the element.

+ +

Veja Também

+ + diff --git a/files/pt-br/web/css/number/index.html b/files/pt-br/web/css/number/index.html new file mode 100644 index 0000000000..dd5297f721 --- /dev/null +++ b/files/pt-br/web/css/number/index.html @@ -0,0 +1,92 @@ +--- +title: +slug: Web/CSS/number +tags: + - CSS + - Layout + - Referencia CSS + - Tipo de Dado Númerico + - Tipo de dado CSS + - Tipos de Dados CSS + - Web +translation_of: Web/CSS/number +--- +

{{CSSRef}}

+ +

O tipo de dado CSS <number> representa um número, sendo esse ou um inteiro ou um componente fracional.

+ +

Sintaxe

+ +

A sintaxe de <number> estende a sintaxe de {{CSSxRef("<integer>")}}. Um valor fracional é representado por um . seguido de um ou mais dígitos decimais e pode ser anexado a número inteiro. Não existe uma unidade associada aos números.

+ +

Interpolação

+ +

Quando animado, os valores de <number> são interpolados como números reais e de ponto flutuante. A velocidade da interpolação é determinada pelo tempo da função associada à animação.

+ +

Exemplos

+ +

Números Válidos

+ +
12          Um <integer> puro é também um <number>.
+4.01        Fração positiva
+-456.8      Fração negativa
+0.0         Zero
++0.0        Zero inciado por um +
+-0.0        Zero iniciado por um -
+.60         Um número fracional sem ser iniciado por zero
+10e3        Notação científica
+-3.4e-2     Notação científica complexa
+
+ +

Números Inválidos

+ +
12.         Números decimais devem ser seguidos por pelo menos um dígito.
++-12.2      Só um sinal +/- é permitido.
+12.1.1      Só um ponto decimal é permitido.
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçõesStatusComentário
{{SpecName("CSS4 Values", "#numbers", "<number>")}}{{Spec2("CSS4 Values")}}Nenhuma mudança significante.
{{SpecName("CSS3 Values", "#numbers", "<number>")}}{{Spec2("CSS3 Values")}}Nenhuma mudança significante.
{{SpecName("CSS2.1", "syndata.html#numbers", "<number>")}}{{Spec2("CSS2.1")}}Definição explícita.
{{SpecName("CSS1", "", "<number>")}}{{Spec2("CSS1")}}Definição implícita..
+ +

Compatibilidade entre Navegadores

+ + + +

{{Compat("css.types.number")}}

+ +

Veja também

+ +
    +
  • {{CSSxRef("<integer>")}}
  • +
diff --git a/files/pt-br/web/css/object-fit/index.html b/files/pt-br/web/css/object-fit/index.html new file mode 100644 index 0000000000..261e5585e9 --- /dev/null +++ b/files/pt-br/web/css/object-fit/index.html @@ -0,0 +1,206 @@ +--- +title: object-fit +slug: Web/CSS/object-fit +translation_of: Web/CSS/object-fit +--- +
{{ CSSRef }}
+ +

Resumo

+ +

A propriedade CSS object-fit especifica como o conteúdo de um elemento substituído deve ser ajustado à caixa estabelecida pela altura e largura usadas.

+ +

{{cssinfo}}

+ +

Syntax

+ +
{{csssyntax}}
+ +
object-fit: fill
+object-fit: contain
+object-fit: cover
+object-fit: none
+object-fit: scale-down
+
+ +

Valores

+ +
+
fill
+
O conteúdo substituído é dimensionado para preencher a caixa de conteúdo do elemento: o tamanho concreto do objeto é a largura e a altura usadas do elemento.
+
contain
+
O conteúdo substituído é dimensionado para manter sua proporção enquanto se encaixa na caixa de conteúdo do elemento: seu tamanho de objeto concreto é resolvido como uma restrição de restrição em relação à largura e altura usadas do elemento.
+
cover
+
O conteúdo substituído é dimensionado para manter sua proporção e preencher toda a caixa de conteúdo do elemento: seu tamanho de objeto concreto é resolvido como uma restrição de capa contra a largura e a altura usadas do elemento.
+
none
+
O conteúdo substituído não é redimensionado para caber dentro da caixa de conteúdo do elemento: o tamanho do objeto concreto do objeto é determinado usando o algoritmo de tamanho padrão sem tamanho especificado e um tamanho de objeto padrão igual à largura e altura usadas do elemento substituído.
+
scale-down
+
O conteúdo é dimensionado se none ou contain for especificado, o que resultaria em um tamanho menor de objeto concreto.
+
+ +

Exemplos

+ +

HTML Content

+ +
<div>
+  <h2>object-fit: fill</h2>
+  <img src="https://mdn.mozillademos.org/files/6457/mdn_logo_only_color.png" alt="MDN Logo" class="fill"/>
+
+  <img src="https://mdn.mozillademos.org/files/6457/mdn_logo_only_color.png" alt="MDN Logo" class="fill narrow"/>
+
+  <h2>object-fit: contain</h2>
+  <img src="https://mdn.mozillademos.org/files/6457/mdn_logo_only_color.png" alt="MDN Logo" class="contain"/>
+
+  <img src="https://mdn.mozillademos.org/files/6457/mdn_logo_only_color.png" alt="MDN Logo" class="contain narrow"/>
+
+  <h2>object-fit: cover</h2>
+  <img src="https://mdn.mozillademos.org/files/6457/mdn_logo_only_color.png" alt="MDN Logo" class="cover"/>
+
+  <img src="https://mdn.mozillademos.org/files/6457/mdn_logo_only_color.png" alt="MDN Logo" class="cover narrow"/>
+
+  <h2>object-fit: none</h2>
+  <img src="https://mdn.mozillademos.org/files/6457/mdn_logo_only_color.png" alt="MDN Logo" class="none"/>
+
+  <img src="https://mdn.mozillademos.org/files/6457/mdn_logo_only_color.png" alt="MDN Logo" class="none narrow"/>
+
+  <h2>object-fit: scale-down</h2>
+  <img src="https://mdn.mozillademos.org/files/6457/mdn_logo_only_color.png" alt="MDN Logo" class="scale-down"/>
+
+  <img src="https://mdn.mozillademos.org/files/6457/mdn_logo_only_color.png" alt="MDN Logo" class="scale-down narrow"/>
+
+</div>
+ +

CSS Content

+ +
h2 {
+  font-family: Courier New, monospace;
+  font-size: 1em;
+  margin: 1em 0 0.3em;
+}
+
+div {
+  display: flex;
+  flex-direction: column;
+  flex-wrap: wrap;
+  align-items: flex-start;
+  height: 940px;
+}
+
+img {
+  width: 150px;
+  height: 100px;
+  border: 1px solid #000;
+}
+
+.narrow {
+  width: 100px;
+  height: 150px;
+  margin-top: 10px;
+}
+
+.fill {
+  object-fit: fill;
+}
+
+.contain {
+  object-fit: contain;
+}
+
+.cover {
+  object-fit: cover;
+}
+
+.none {
+  object-fit: none;
+}
+
+.scale-down {
+  object-fit: scale-down;
+}
+
+ +

Output

+ +

{{ EmbedLiveSample('Example', 500, 450) }}

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS4 Images', '#the-object-fit', 'object-fit')}}{{Spec2('CSS4 Images')}}The from-image and flip keywords have been added.
{{SpecName('CSS3 Images', '#the-object-fit', 'object-fit')}}{{Spec2('CSS3 Images')}}Initial specification
+ +

Browser compatibility

+ +

{{ CompatibilityTable }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support31.0{{ CompatGeckoDesktop("36") }}{{CompatNo}}11.60{{ property_prefix("-o") }}
+ 19.0
{{ CompatVersionUnknown }}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support4.4.4{{ CompatGeckoDesktop("36") }}{{CompatNo}}11.5{{ property_prefix("-o") }}
+ 24
{{ CompatVersionUnknown }}
+
+ +

See also

+ +
    +
  • Other image-related CSS properties: {{cssxref("object-position")}}, {{cssxref("image-orientation")}}, {{cssxref("image-rendering")}}, {{cssxref("image-resolution")}}.
  • +
  • An object-fit polyfill for browsers not supporting it.
  • +
diff --git a/files/pt-br/web/css/offset/index.html b/files/pt-br/web/css/offset/index.html new file mode 100644 index 0000000000..5bf849fdda --- /dev/null +++ b/files/pt-br/web/css/offset/index.html @@ -0,0 +1,158 @@ +--- +title: offset +slug: Web/CSS/offset +tags: + - CSS + - Experimental + - Não-padrão + - Precisa de Conteúdo + - Propriedade CSS + - Racunho + - Referencia +translation_of: Web/CSS/offset +--- +
{{SeeCompatTable}}{{CSSRef}}{{draft}}
+ +

A propriedade CSS offset é uma propriedade abreviada para animar um elemento ao longo de um caminho definido.

+ +
+

As primeiras versões da especificação chamam essa propriedade de motion.

+
+ +

{{cssinfo}}

+ +

Sintaxe

+ +
/* Posição do offset */
+offset: auto
+offset: 10px 30px;
+offset: none;
+
+/* Caminho do offset */
+offset: ray(45deg closest-side);
+offset: path(M 100 100 L 300 100 L 200 300 z);
+offset: url(arc.svg);
+
+/* Caminho do offset com distância e/ou rotação */
+offset: url(circle.svg) 100px;
+offset: url(circle.svg) 40%;
+offset: url(circle.svg) 30deg;
+offset: url(circle.svg) 50px 20deg;
+
+/* Incluindo âncora no offset */
+offset: ray(45deg closest-side) / 40px 20px;
+offset: url(arc.svg) 2cm / 0.5cm 3cm;
+offset: url(arc.svg) 30deg / 50px 100px;
+
+ +

Sintaxe formal

+ +
{{csssyntax}}
+ +

Examplo

+ +

HTML

+ +
<div id="offsetElement"></div>
+
+ +

CSS

+ +
@keyframes move {
+  from {
+    offset-distance: 0%;
+  }
+
+  to {
+    offset-distance: 100%;
+  }
+}
+
+#offsetElement {
+  width: 50px;
+  height: 50px;
+  background-color: blue;
+  offset: path("M 100 100 L 300 100 L 200 300 z") auto;
+  animation: move 3s linear infinite;
+}
+
+ +

Resultado

+ +

{{EmbedLiveSample("Example", 350, 350)}}

+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('Motion Path Level 1', '#offset-shorthand', 'offset')}}{{Spec2('Motion Path Level 1')}}Definição inicial
+ +

Compatibilidade do navegador

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico{{CompatChrome(46.0)}} (as motion)
+ {{CompatChrome(55.0)}} (as offset)
{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Suporte básico{{CompatNo}}{{CompatChrome(46.0)}} (as motion)
+ {{CompatChrome(55.0)}} (as offset)
{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatChrome(46.0)}} (as motion)
+ {{CompatChrome(55.0)}} (as offset)
+
diff --git a/files/pt-br/web/css/opacity/index.html b/files/pt-br/web/css/opacity/index.html new file mode 100644 index 0000000000..41afe896ae --- /dev/null +++ b/files/pt-br/web/css/opacity/index.html @@ -0,0 +1,212 @@ +--- +title: opacity +slug: Web/CSS/opacity +translation_of: Web/CSS/opacity +--- +
{{CSSRef}}
+ +

Sumário

+ +

A propriedade CSS opacity especifica a transparência de um elemento, isto é, o grau no qual o background atrás do elemento é sobreposto.

+ +

O valor aplica-se ao elemento como um todo, incluindo seu conteúdo, apesar de o valor não ser herdado por elementos filhos. Assim, um elemento e seus elementos filhos têm todos a mesma opacidade relativa ao background do elemento, mesmo se o elemento e seus elementos filhos tiverem opacidades diferentes entre si.

+ +

Se você não quer aplicar a opacidade ao elemento filho - use isto:

+ +
background: rgba(0, 0, 0, 0.4);
+ +

Usando essa propriedade com um valor diferente de 1, o elemento é colocado em um novo contexto de empilhamento.

+ +

{{cssinfo}}

+ +

Sintaxe

+ +
/* Totalmente opaco */
+opacity: 1;
+opacity: 1.0;
+
+/* Translúcido */
+opacity: 0.6;
+
+/* Totalmente transparente */
+opacity: 0.0;
+opacity: 0;
+
+/* Valores globais */
+opacity: inherit;
+opacity: initial;
+opacity: unset;
+
+ +

Valores

+ +
+
<number>
+
É um {{cssxref("number")}} no intervalo de 0.0 a 1.0, sendo estes incluídos, representando a opacidade do canal, que é o valor de seu canal alfa. Qualquer valor fora do intervalo, apesar de válido, é aproximado ao valor mais próximo dentro do intervalo.
+
+ + + + + + + + + + + + + + + + + + + +
ValorSignificado
0O elemento é totalmente transparente (isto é, invisível).
Qualquer {{cssxref("number")}} entre 0 e 1O elemento é translúcido (isto é, o background é visível).
1O elemento é totalmente opaco (sólido).
+
+
+ +

Sintaxe formal

+ +
{{csssyntax}}
+ +

Exemplos

+ +

Exemplo básico

+ +
div { background-color: yellow; }
+.light {
+  opacity: 0.2; /* Mal consegue ver o texto acima do background */
+}
+.medium {
+  opacity: 0.5; /* Vê o texto mais claramente acima do background */
+}
+.heavy {
+  opacity: 0.9; /* Vê o texto muito claramente acima do background */
+}
+
+ +
<div class="light">Você mal vê isso.</div>
+<div class="medium">Isso é mais fácil de ver.</div>
+<div class="heavy">Isso é muito fácil de ver.</div>
+
+ +

{{EmbedLiveSample('Basic_example', '640', '64')}}

+ +

Opacidade diferente com :hover

+ +
img.opacity {
+  opacity: 1;
+  filter: alpha(opacity=100); /* IE8 e anteriores */
+  zoom: 1; /* Ativa "hasLayout" no IE 7 e anteriores */
+}
+
+img.opacity:hover {
+  opacity: 0.5;
+  filter: alpha(opacity=50);
+  zoom: 1;
+}
+ +
<img src="//developer.mozilla.org/media/img/mdn-logo.png"
+     alt="MDN logo" width="128" height="146"
+     class="opacity">
+
+
+ +

{{EmbedLiveSample('Different_opacity_with_hover', '150', '175')}}

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('CSS3 Transitions', '#animatable-css', 'opacity')}}{{Spec2('CSS3 Transitions')}}Define opacity como animável.
{{SpecName('CSS3 Colors', '#opacity', 'opacity')}}{{Spec2('CSS3 Colors')}}Definição inicial.
+ +

Compatibilidade com browsers

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico1.0{{CompatGeckoDesktop("1.7")}}[1]9.0[2]
+ 8.0
+ 4.0
9.01.2 (125)[3]
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico1.0{{CompatGeckoMobile("1.7")}}[1]9.0[2]
+ 8.0
+ 4.0
9.03.2
+
+ +

 

+ +

[1] Anterior ao Gecko 1.7 (Firefox 0.9) , a propriedade -moz-opacity foi implementada de uma maneira não-padronizada (herdada). Com o Firefox 0.9, o comportamento mudou e a propriedade foi renomeada para opacity. Desde então, -moz-opacity foi suportada somente como um alias para opacity.

+ +

Gecko 1.9.1 {{geckoRelease("1.9.1")}} e posteriores não suportam  -moz-opacity e o suporte para MozOpacity no JavaScript foi removido no Gecko 13 {{geckoRelease("13")}}. A partir de agora, você deve simplesmente usar opacity.

+ +

[2] Anterior à versão 9, Internet Explorer não suporta opacity, em vez disso ele suporta uma propriedade filter com alpha(opacity=xx) ou "alpha(opacity=xx)" como valor (ambas são sinônimos). Do IE4 até o IE9 foi suportado a forma extendida progid:DXImageTransform.Microsoft.Alpha(Opacity=xx). IE8introduziu -ms-filter, a qual é sinônimo de filter. Ambas foram removidas no IE10.

+ +

[3] Similar à -moz-opacity, -khtml-opacity tem estado morta desde o início de 2004 (lançamento do Safari 1.2).
+ Konqueror nunca teve suporte para -khtml-opacity e tem suportado a propriedade opacity desde a versão 4.0.

+ +

Veja também

+ + diff --git a/files/pt-br/web/css/outline/index.html b/files/pt-br/web/css/outline/index.html new file mode 100644 index 0000000000..905cf7315a --- /dev/null +++ b/files/pt-br/web/css/outline/index.html @@ -0,0 +1,135 @@ +--- +title: outline +slug: Web/CSS/outline +translation_of: Web/CSS/outline +--- +
{{CSSRef}}
+ +

Sumário

+ +

A propriedade CSS outline é uma propriedade abreviada para configurar uma ou mais das propriedades de contorno {{cssxref("outline-style")}}, {{cssxref("outline-width")}} e {{cssxref("outline-color")}} em uma única declaração. Na maioria dos casos o uso abreviado é preferível e mais conveniente.

+ +

Contornos se diferenciam de bordas das seguintes maneiras:

+ +
    +
  • Contornos não ocupam espaços, eles são desenhados acima do conteúdo.
  • +
  • Contornos podem não ser retangulares. Eles são retangulares no Gecko/Firefox. Mas por exemplo, Opera desenha uma forma não retangular em torno de uma construção como este:
    + TEXTTEXTTEXT
  • +
+ +
{{cssinfo}}
+ +

Sintaxe

+ +
/* largura | estilo | cor */
+outline: 1px solid white;
+
+/* Valores globais */
+outline: inherit;
+outline: initial;
+outline: unset;
+
+ +

Valores

+ +

Um, dois ou três valores, dada em ordem arbitrária:

+ +
+
<'outline-width'>
+
Veja {{Cssxref("outline-width")}}.
+
<'outline-style'>
+
Veja {{Cssxref("outline-style")}}.
+
<'outline-color'>
+
Desde Gecko 1.9 (Firefox 3), o valor da propriedade {{Cssxref("color")}}  (cor de primeiro plano) é usado. Veja {{Cssxref("outline-color")}}.
+
+ +

Sintaxe completa

+ +
{{csssyntax}}
+ +

Exemplos

+ +

outline: solid; | outline: dashed red; | outline: dotted 1px; | outline: ridge thick violet; | outline: custom 5px;

+ +
/* duas declarações identicas */
+
+:link:hover { outline: 1px solid #000; }
+:link:hover { outline: solid black 1px; }
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('CSS3 Basic UI', '#outline', 'outline')}}{{Spec2('CSS3 Basic UI')}}No change
{{SpecName('CSS2.1', 'ui.html#propdef-outline', 'outline')}}{{Spec2('CSS2.1')}}Initial definition
+ +

Compatibilidade de Navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support1.01.5 (1.8)[1]8.07.01.2 (125)
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support1.0{{CompatGeckoMobile(1.8)}} [1]8.06.03.1
+
+ +

[1] Em navegadores anteriores à Gecko 1.8 (Firefox 1.5) um efeito semelhante pode ser conseguido utilizando Mozilla CSS Extension {{Cssxref("-moz-outline")}}.

+ +

Firefox inclui elementos posicionados absolutamente dentro do contorno ({{bug("687311")}}).

diff --git a/files/pt-br/web/css/overflow/index.html b/files/pt-br/web/css/overflow/index.html new file mode 100644 index 0000000000..1bcf5b2865 --- /dev/null +++ b/files/pt-br/web/css/overflow/index.html @@ -0,0 +1,166 @@ +--- +title: overflow +slug: Web/CSS/overflow +translation_of: Web/CSS/overflow +--- +
{{ CSSRef() }}
+ +

Resumo

+ +

A propriedade overflow especifica quando o conteúdo de um elemento de nível de bloco deve ser cortado, exibido com barras de rolagem ou se transborda do elemento.

+ +

O uso da propriedade overflow com valor diferente de visible (seu valor padrão), criará um novo contexto de formatação de bloco. Isto é tecnicamente necessário para evitar que um conteúdo flutuante que entre em contato com o objeto dentro da área de rolamento e quebre as linhas do conteúdo para ajustar a disposição do texto. A quebra das linhas ocorre sempre que a barra de rolagem é utilizada, tornando a experiência de rolagem lenta.

+ +
+

Nota: Ao definir a propredade scrollTop para o elemento HTML relevante, mesmo que o valor de overflow seja hidden, o conteúdo ainda pode precisar rolar.

+
+ +

{{cssinfo}}

+ +

Sintaxe

+ +
overflow:  visible | hidden | scroll | {{ cssxref("auto") }} | {{ cssxref("inherit") }}
+ +

Valores

+ +
+
visible
+
Valor padrão. O conteúdo não é cortado e pode ser renderizado para fora da caixa de conteúdo.
+
hidden
+
O conteúdo é cortado e nenhuma barra de rolagem é exibida.
+
scroll
+
O conteúdo é acessível através de barras de rolagem que são exibidas mesmo que o conteúdo não precise. Isso evita o problema de barras de rolagem aparecendo e desaparecendo quando o conteúdo é dinâmico. Impressoras podem imprimir o conteúdo vazado.
+
auto
+
Depende do navegador utilizado. Navegadores desktop como o Firefox geralmente exibem barras de rolagem apenas quando necessário.
+
+ +

Extensões da Mozilla

+ +
+
-moz-scrollbars-none {{ obsolete_inline() }}
+
Use overflow:hidden no lugar.
+
-moz-scrollbars-horizontal {{ Deprecated_inline() }}
+
O uso de {{ Cssxref("overflow-x") }} e {{ Cssxref("overflow-y") }} é preferido.
+
-moz-scrollbars-vertical {{ Deprecated_inline() }}
+
O uso de {{ Cssxref("overflow-x") }} e {{ Cssxref("overflow-y") }} é preferido.
+
-moz-hidden-unscrollable {{ non-standard_inline() }}
+
É mantido principalmente para uso interno e por temas. Desabilita o rolamento de elementos raiz de XML e <html>, <body> mediante o uso das setas do teclado ou scroll do mouse.
+
+ +

Exemplos

+ +
p {
+     width: 12em;
+     border: dotted;
+     overflow: visible;   /* Exibe o conteúdo de forma vazada, fora da caixa de conteúdo */
+}
+
+ +

visible (default)
+ Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium.

+ +
p { overflow: hidden; /* Esconde o conteúdo excedente */ }
+
+ +

overflow: hidden
+ Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium.

+ +
p { overflow: scroll; /* Sempre exibe barras de rolagem */ }
+
+ +

overflow: scroll
+ Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium.

+ +
p { overflow: auto; /* Exibe barras de rolagem apenas se necessário */ }
+
+ +

overflow: auto
+ Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium.

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComment
{{ SpecName('CSS3 Box', '#overflow1', 'overflow') }}{{ Spec2('CSS3 Box') }}Sem alteração.
{{ SpecName('CSS2.1', 'visufx.html#overflow', 'overflow') }}{{ Spec2('CSS2.1') }} 
+ +

Compatibilidade entre navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico1.0{{ CompatGeckoDesktop("1") }}4.07.01.0 (85)
+
+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Suporte básico{{ CompatUnknown() }}{{ CompatGeckoMobile("1") }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

Notas sobre o Firefox (Gecko)

+ +

Até o Firefox 3.6 (Gecko 1.9.2), a propriedade overflow é incorretamente aplicada para elementos de grupo de tabela (<thead> , <tbody> , <tfoot>). Este comportamento foi corrigido em versões posteriores.

+ +

Notas sobre o Internet Explorer

+ +

Internet Explorer 4 até 6 torna mais largos elementos com overflow:visible (valor padrão) para acomodar todo o conteúdo. height/width comportam-se como min-height/min-width.

+ +

Veja também

+ +
    +
  • Propriedades CSS relacionadas: {{ cssxref("text-overflow") }}, {{ cssxref("white-space") }}, {{ Cssxref("overflow-x") }}, {{ Cssxref("overflow-y") }}, {{ Cssxref("clip") }}, {{ Cssxref("display") }}
  • +
diff --git a/files/pt-br/web/css/padding-left/index.html b/files/pt-br/web/css/padding-left/index.html new file mode 100644 index 0000000000..22eb78adac --- /dev/null +++ b/files/pt-br/web/css/padding-left/index.html @@ -0,0 +1,147 @@ +--- +title: padding-left +slug: Web/CSS/padding-left +tags: + - CSS + - CSS Padding + - La + - Reference + - Referencia + - Web +translation_of: Web/CSS/padding-left +--- +

{{ CSSRef() }}

+ +

Resumo

+ +

A propriedade CSS padding-left é um elemento que define o espaço de preenchimento obrigatório no lado esquerdo de um elemento. padding area é o espaço entre o conteúdo do elemento e a borda. Um valor negativo não é permitido.

+ +

{{cssinfo}}

+ +

Syntax

+ +
Syntax formal: {{csssyntax("padding-left")}}
+
+ +
padding-left: 0.5em;
+padding-left: 0;
+padding-left: 2cm;
+padding-left: 10%
+
+padding-left: inherit
+
+ +

Valores

+ +
+
<length>
+
+
+
Especifica uma largura fixa positiva. Consulte {{cssxref("<length>")}} para obter detalhes.
+
+
+
<percentage>
+
Um percentual em relação a largura do bloco.
+
+ +

Exemplos

+ +
.content { padding-left: 5%; }
+.sidebox { padding-left: 10px; }
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{ SpecName('CSS3 Box', '#the-padding', 'padding-left') }}{{ Spec2('CSS3 Box') }} +
+
Nenhuma mudança.
+
+
{{ SpecName('CSS3 Transitions', '#animatable-css', 'padding-left') }}{{ Spec2('CSS3 Transitions') }}Define padding-left como animatable.
{{ SpecName('CSS2.1', 'box.html#padding-properties', 'padding-left') }}{{ Spec2('CSS2.1') }} +
+
Nenhuma mudança.
+
+
{{ Specname('CSS1', '#padding-left', 'padding-left') }}{{ Spec2('CSS1') }} +
+
Definição inicial.
+
+
+ +

Compatibilidade do Navegador

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
RecursoChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte Básico1.01.0 (1.0)4.03.51.0 (85)
+
+ +
+ + + + + + + + + + + + + + + + + + + +
RecursoAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Suporte básico{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
diff --git a/files/pt-br/web/css/padding/index.html b/files/pt-br/web/css/padding/index.html new file mode 100644 index 0000000000..dc89652bd8 --- /dev/null +++ b/files/pt-br/web/css/padding/index.html @@ -0,0 +1,189 @@ +--- +title: padding +slug: Web/CSS/padding +translation_of: Web/CSS/padding +--- +
{{CSSRef}}
+ +

A propriedade padding define uma a distância entre o conteúdo de um elemento e suas bordas. É um atalho que evita definir uma distância para cada lado separadamente (padding-top, padding-right, padding-bottom, padding-left).

+ +
/* Aplica-se à todas as bordas */
+padding: 1em;
+
+/* vertical | horizontal */
+padding: 5% 10%;
+
+/* superior | horizontal | inferior */
+padding: 1em 2em 2em;
+
+/* superior | direita | inferior | esquerda */
+padding: 2px 1em 0 1em;
+
+/* Valores globais */
+padding: inherit;
+padding: initial;
+padding: unset;
+
+ +

{{cssinfo}}

+ +

Sintaxe

+ +

A propriedade padding pode ser utilizada usando um, dois, três ou todos os quatro valores. Cada valor é um <comprimento> ou uma <porcentagem>.

+ +
    +
  • Quando um único é valor utilizado, ele se aplica a todos os quatro lados.
  • +
  • Se Dois valores forem utilizados o primeiro se aplica às bordas verticais (superior e inferior) e o segundo se aplica às bordas horizontais (esquerda e direita).
  • +
  • Quando Três valores são utilizados o primeiro se aplica à borda superior, o segundo será utilizado tanto para a borda esquerda quanto para a borda direita. O terceiro será aplicado à borda inferior.
  • +
  • Com Quatro valores a ordem de aplicação é: superior, direita, inferior e esquerda (de acordo com o movimento dos ponteiros do relógio).
  • +
+ +

Valores

+ +
+
<comprimento>
+
Media do comprimento. Não pode ser negativo. Veja {{cssxref("<length>")}} para maiores detalhes.
+
<porcentagem>
+
Valor percentual que é aplicado em relação à largura do bloco contido.
+
+ +

Sintaxe formal

+ +
{{csssyntax}}
+ +

Exemplos

+ +
 padding: 5%;                /* padding 5% em todos os lados */
+
+ +
 padding: 10px;              /* padding 10px em todos os lados */
+
+ +
 padding: 10px 20px;         /*  10px acima e abaixo  */
+                             /*  20px esquerda e direita  */
+
+ +
 padding: 10px 3% 20px;      /*  10px acima          */
+                             /*  3% esquerda e direita */
+                             /*  20px abaixo       */
+
+ +
 padding: 1em 3px 30px 5px;  /*  acima    1em  padding  */
+                             /*  direita  3px  padding  */
+                             /*  abaixo   30px padding  */
+                             /*  esquerda 5px  padding  */
+
+ +

border:outset; padding:5% 1em;

+ +

Amostra

+ +

HTML

+ +
<h4>Hello world!</h4>
+<h3>O padding é diferente nesta linha.</h3>
+
+ +

CSS

+ +
h4{
+  background-color: green;
+  padding: 50px 20px 20px 50px;
+}
+
+h3{
+  background-color: blue;
+  padding: 400px 50px 50px 400px;
+}
+
+ +

{{ LiveSampleLink('Live_Sample', 'Amostra') }}

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusObservações
{{ SpecName('CSS3 Box', '#the-padding', 'padding') }}{{ Spec2('CSS3 Box') }}Sem alteração
{{ SpecName('CSS2.1', 'box.html#propdef-padding', 'padding') }}{{ Spec2('CSS2.1') }}Sem alteração
{{ Specname('CSS1', '#padding', 'padding') }}{{ Spec2('CSS1') }}Definição inicial
+ +

Compatibilidade

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support1.0{{CompatVersionUnknown}}1.0 (1.0)4.03.51.0 (85)
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}{{CompatVersionUnknown}}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/css/page-break-before/index.html b/files/pt-br/web/css/page-break-before/index.html new file mode 100644 index 0000000000..7aabf15439 --- /dev/null +++ b/files/pt-br/web/css/page-break-before/index.html @@ -0,0 +1,142 @@ +--- +title: page-break-before +slug: Web/CSS/page-break-before +translation_of: Web/CSS/page-break-before +--- +
{{CSSRef}}
+ +
Esta propriedade foi substituída pela propriedade {{cssxref("break-before")}}.
+ +

A propriedade CSS page-break-before ajusta as "quebras de páginas" antes do elemento atual.

+ +

Esta propriedade aplica-se para elementos em bloco (block) que geram uma caixa. Não será aplicada em uma {{ HTMLElement("div") }} vazia que não irá gerar uma caixa (box).

+ +
/* Keyword values */
+page-break-before: auto;
+page-break-before: always;
+page-break-before: avoid;
+page-break-before: left;
+page-break-before: right;
+page-break-before: recto;
+page-break-before: verso;
+
+/* Global values */
+page-break-before: inherit;
+page-break-before: initial;
+page-break-before: unset;
+
+ +

{{cssinfo}}

+ +

Page break aliases

+ +

A propriedade page-break-before agora é uma propriedade legada, substituída por {{cssxref("break-before")}}.

+ +

Por motivos de compatibilidade, page-break-before é tratada pelos navegadores como um alias de break-before. Isso garante que sites usando page-break-before continuem a funcionar. Um subconjunto de valores deve manter aliases como a seguir:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
page-break-beforebreak-before
autoauto
leftleft
rightright
avoidavoid
alwayspage
+ +

Syntax

+ +

Values

+ +
+
auto
+
Initial value. Automatic page breaks (neither forced nor forbidden).
+
always
+
Always force page breaks before the element.
+
avoid
+
Avoid page breaks before the element.
+
left
+
Force page breaks before the element so that the next page is formatted as a left page.
+
right
+
Force page breaks before the element so that the next page is formatted as a right page.
+
recto {{experimental_inline}}
+
If pages progress left-to-right, then this acts like right. If pages progress right-to-left, then this acts like left.
+
verso {{experimental_inline}}
+
If pages progress left-to-right, then this acts like left. If pages progress right-to-left, then this acts like right.
+
+ +

Formal syntax

+ +
{{csssyntax}}
+ +

Examples

+ +
/* avoid page break before the div */
+div.note {
+    page-break-before: avoid;
+}
+
+ +

Specification

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS Logical Properties', '#page', 'recto and verso')}}{{Spec2('CSS Logical Properties')}}Adds the values recto and verso.
{{SpecName('CSS3 Paged Media', '#page-break-before', 'page-break-before')}}{{Spec2('CSS3 Paged Media')}}Extends the element that this property applies to table rows and table row groups.
{{SpecName('CSS2.1', 'page.html#propdef-page-break-before', 'page-break-before')}}{{Spec2('CSS2.1')}}Initial definition
+ +

Browser compatibility

+ + + +

{{Compat("css.properties.page-break-before")}}

+ +

See also

+ +
    +
  • {{cssxref("break-before")}}, {{cssxref("break-after")}}, {{cssxref("break-inside")}}
  • +
  • {{cssxref("page-break-after")}}, {{cssxref("page-break-inside")}}
  • +
  • {{cssxref("orphans")}}, {{cssxref("widows")}}
  • +
diff --git a/files/pt-br/web/css/pointer-events/index.html b/files/pt-br/web/css/pointer-events/index.html new file mode 100644 index 0000000000..4d04ba119b --- /dev/null +++ b/files/pt-br/web/css/pointer-events/index.html @@ -0,0 +1,178 @@ +--- +title: pointer-events +slug: Web/CSS/pointer-events +translation_of: Web/CSS/pointer-events +--- +
{{CSSRef}}
+ +

Resumo

+ +

A propriedade CSS pointer-events permite autores controlarem sob qualquer circustancia(se houver) um elemento gráfico particular podendo ser o alvo do evento do mouse. Quando essa propriedade não é especificada, as mesmas características do valor  visiblePainted é aplicada no conteúdo SVG.

+ +

Além de indicar que este elemento não é o alvo do evento do mouse, o valor none instrui o evento do mouse a "passar" o elemento e tudo que está "abaixo" deste elemento.

+ +

{{cssinfo}}

+ +

Sintaxe

+ +
pointer-events: auto;
+pointer-events: none;
+pointer-events: visiblePainted;
+pointer-events: visibleFill;
+pointer-events: visibleStroke;
+pointer-events: visible;
+pointer-events: painted;
+pointer-events: fill;
+pointer-events: stroke;
+pointer-events: all;
+
+pointer-events: inherit;
+
+ +

Valores

+ +
+
auto
+
O elemento se comporta como  se a propriedade pointer-events não fosse especificada. Em conteúdo SVG, esse valor e o valor  visiblePainted tem o mesmo efeito.
+
none
+
O elemento nunca é o alvo de eventos do mouse; contudo, o evento do mouse pode direcionar seus elementos descendentes se esses descendentes tiverem algum outro valor configurado no pointer-events. Nessas circunstâncias, os eventos do mouse vão acionar eventos de escuta em seus elementos pai conforme apropriado no seu caminho de/para o descendente, durante as fases do evento captura/borbulha.
+
visiblePainted
+
Apenas SVG. O elemento pode apenas ser alvo de um evento de mouse quando a propriedade visibility é definida como visible e quando o cursor do mouse estiver sobre o interior (exemplo: “preenchimento”) do elemento e a propriedade fill tiver um valor exceto none, ou quando o cursor do mouse estiver sobre o perímetro(exemplo: “linha”) do elemento e a propriedade stroke estiver definida com um valor exceto none.
+
visibleFill
+
Apenas SVG. O elemento apenas pode ser o alvo de um evento mouse quando a propriedade visibility é definida como visible e quando o cursor do mouse estiver sobre o interior (exemplo: “preenchimento”) do elemento. O valor da propriedade fill não afeta o processamento dos eventos.
+
visibleStroke
+
Apenas SVG. O elemento apenas pode ser o alvo de um evento do mouse quando a propriedade visibility é definida como visible e quando o cursor do mouse estiver sobre o perímetro (exemplo: "linha") do elemento. O valor da propriedade stroke não afeta o processamento do evento.
+
visible
+
Apenas SVG. O elemento pode ser o alvo de um evento de mouse quando a propriedade visibility é definida como visible e o cursor do mouse estiver sobre ou no interior (exemplo: preenchimento) ou perímetro (exemplo: linha) do elemento. O valor do fill e stroke não afeta o processamento do evento.
+
painted
+
Apenas SVG. O elemento apenas pode ser o alvo de um evento do mouse quando o cursor do mouse estiver sobre o interior (exemplo: “preenchimento”) do elemento e a propriedade fill definida com valor diferente de none, ou quando o cursor do mouse estiver no perímetro(exemplo: “linha”) do elemento e a propriedade stroke definida com valor diferente de none. O valor da propriedade visibility não afeta o processamento do evento.
+
fill
+
Apenas SVG. O elemento apenas pode ser o alvo de um evento do mouse quando o ponteiro estiver sobre o interior (exemplo: preenchimento) do elemento.  Os valores das propriedades fill e visibility não afetam o processamento do evento.
+
stroke
+
Apenas SVG. O elemento apenas pode ser o alvo de um evento do mouse quando o ponteiro estiver sobre o perímetro (exemplo: linha) do elemento. Os valores das propriedades stroke e visibility  não afetam o processamento do evento.
+
all
+
Apenas SVG. O elemento apenas pode ser alvo do evento do mouse quando o ponteiro estiver sobre o interior (exemplo: preenchimento) ou perímetro (exemplo: linha) do elemento. Os valores das propriedades fill, stroke e visibility não afetam o processamento do evento.
+
+ +

Sintaxe formal

+ +
{{csssyntax("pointer-events")}}
+ +

Exemplos

+ +

Exemplo 1

+ +
/* Exemplo 1: Fazer todas img não reagir a qualquer evento de mouse tal como arrastar, passar sobre, clique etc */
+img {
+  pointer-events: none;
+}
+ +

Exemplo 2

+ +

Makes the link to http://example.com non-reactive.

+ +
<ul>
+  <li><a href="https://developer.mozilla.org">MDN</a></li>
+  <li><a href="http://example.com">example.com</a></li>
+</ul>
+ +
a[href="http://example.com"] {
+  pointer-events: none;
+}
+ +
{{EmbedLiveSample('Example_2', "500", "100")}}
+ +

Notas

+ +

Note que previnir um elemento de ser o alvo de eventos de mouse usando pointer-events não necessariamente quer dizer que o evento ouvinte do mouse desde elemento não pode ou não vai se desencadeado. Se um dos elementos filhos tem pointer-events explicitamente definidos para permitir que o filho seja o alvo do evento do mouse, então qualquer evento direcionado para este filho vai passar através do pai como o evento se deslocando ao longo da cadeia pai, e os ouvintes do evento gatilho do pai conforme o caso. Claro que qualquer atividade do mouse em um ponto da tela que é coberto pelo pai, mas não pelo filho, não será capturado por qualquer filho ou pai (isso vai “através” do pai e qualquer alvo que está abaixo).

+ +

Nós gostaríamos de fornecer um controle de textura mais refinado (do que apenas auto e none) em HTML para que partes de um elemento fizessem com que os eventos mouse “capturem” , e quando. Para nos ajudar a decidir como pointer-events devem ser estendido para HTML, se você tem qualquer coisa particular que você gostaria de fazer com essa propriedade, então por favor adicione na seção Caso de Uso dessa wiki page (não se preocupe sobre ficar organizado ).

+ +

Esta propriedade pode também ser usada para alcançar melhores taxas de quadros durante a rolagem. De fato, enquanto rola a página, o mouse passa sobre alguns elementos, então efeitos hover se aplicam. Contudo, esses efeitos são muitas vezes despercebidas pelo usuário e principalmente resultam em uma rolagem ruim. Aplicar pointer-events: none no body desabilita eventos de mouse incluindo hover que resultam em uma performance melhor de rolagem.

+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçõesStatusComentário
{{SpecName('SVG1.1', 'interact.html#PointerEventsProperty', 'pointer-events')}}{{Spec2('SVG1.1')}} 
+ +

Se extende para elementos HTML, embora presente nos primeiros rascunhos do Módulo Básico de Interface do Usuário do CSS nivel 3, foi empurrado para o nível 4.

+ +

Compatibilidade do navegador

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte SVG1.0{{CompatGeckoDesktop("1.8")}}9.09.0 (2.0)3.0 (522)
Conteúdo HTML/XML2.0{{CompatGeckoDesktop("1.9.2")}}11.015.04.0 (530)
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Suporte básico{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/css/position/index.html b/files/pt-br/web/css/position/index.html new file mode 100644 index 0000000000..92f398b013 --- /dev/null +++ b/files/pt-br/web/css/position/index.html @@ -0,0 +1,319 @@ +--- +title: position +slug: Web/CSS/position +translation_of: Web/CSS/position +--- +
{{CSSRef}}
+ +
A propriedade position, encontrada no CSS, define como um elemento pode ser posicionado (renderizado) no documento (página). Essa propriedade (position) pode ser acompanhada de outras, tais como, {{Cssxref("top")}}, {{Cssxref("right")}}, {{Cssxref("bottom")}}, and {{Cssxref("left")}}, que determinam como ficará a localização final do objeto, permitindo seu deslocamento, como será apresentado adiante.
+ +
+ +
{{EmbedInteractiveExample("pages/css/position.html")}}
+ + + +

Tipos de posicionamentos

+ +
    +
  • Um elemento posicionado é um elemento cujo valor de sua posição pode ser computado (calculado) como relative, absolute, fixed, or sticky. ( Em outras palavras, são todos esses, com excessão do static, sendo estático o valor como padrão do elemento.)
  • +
  • Um elemento denominado com posicionamento relativo, ou relatively positioned element, é um elemento cuja função é calculada ao ser definida a position como valor relative. Com isso, a propriedade {{Cssxref("top")}} e {{Cssxref("bottom")}} determinam o deslocamento ou projeção vertical a posição padrão do elemento que estava definida por static; Não sendo outro, o {{Cssxref("left")}} e o {{Cssxref("right")}}, por sua vez, determinam o deslocamento horizontal.
  • +
  • Um elemento denominado com posicionamento absoluto, ou absolutely positioned element,  é um elemento determinado e calculado ao atribuir ao position o valor absolute ou fixed. Com {{Cssxref("top")}}, {{Cssxref("right")}}, {{Cssxref("bottom")}}, and {{Cssxref("left")}} é possível especificar o deslocamento das laterais (bordas) dos blocos que contém (containing block) os elementos.  (O containing block, ou blocos que envolvem um elemento é definido como um antecessor relativo ao qual o elemento está posicionado, acomplado ou englobado.  Se por ventura o elemento tiver definido margens (margin), ele são adicionados ao deslocamento (offset). O elemento estabelecerá um novo contexto de formatação do bloco (BFC) para seus conteúdos.
  • +
  • Um elemento denominado com posicionamento adesivo ( ! ), ou stickily positioned element, é um elemento determinado e calculado ao atribuir ao position como valor sticky. Sendo tratado como um posicionamento relativo até que ultrapasse (atinja) os limites do bloco no qual está contido.  (Se assemelha a configurar a propriedade {{Cssxref("top")}} com um valor diferente de automatático (auto)) Dentro do seu fluxo principal (fluxo raiz, ou o contêiner no qual ele desloca-se),  No momento que há o deslocamento da página o elemento é tratado como "preso" ou "stuck" até encontrar-se com as paredes opostas do bloco no qual esteja contido.
  • +
+ +

Maior parte do tempo, um elemento de posicionamento absoluto que tem {{Cssxref("height")}} e {{Cssxref("width")}} configurados como auto são dimensionados de acordo com seu conteúdo interno. However, non-replaced, absolutely positioned elements can be made to fill the available vertical space by specifying both {{Cssxref("top")}} and {{Cssxref("bottom")}} and leaving {{Cssxref("height")}} unspecified (that is, auto). They can likewise be made to fill the available horizontal space by specifying both {{Cssxref("left")}} and {{Cssxref("right")}} and leaving {{Cssxref("width")}} as auto.

+ +

Exceto para esses casos descritos abaixo (para elementos de posicionamento absoluto que preenchem o espaço disponível):

+ +
    +
  • Se ambos top e bottom são definidos (tecnicamento não sendo auto), top prevalece.
  • +
  • Se ambos left e right são definidos, left prevalece quando {{Cssxref("direction")}} é ltr (Direção da escrita Portuguesa, Japonês na horizontal, etc.) e right prevalece quando {{Cssxref("direction")}} for configurado rtl ( Padrão de escrita em idiomas como Persa, Arabe, Hebraico, etc.).
  • +
+ +

Sintáxe

+ +

A propriedade position é definida com apenas uma palavra-chave da lista abaixo.

+ +

Valores

+ +
+
static
+
The element is positioned according to the normal flow of the document. The {{cssxref("top")}}, {{cssxref("right")}}, {{cssxref("bottom")}}, {{cssxref("left")}}, and {{cssxref("z-index")}} properties have no effect. This is the default value.
+
relative
+
The element is positioned according to the normal flow of the document, and then offset relative to itself based on the values of top, right, bottom, and left. The offset does not affect the position of any other elements; thus, the space given for the element in the page layout is the same as if position were static.
+
This value creates a new stacking context when the value of z-index is not auto. Its effect on table-*-group, table-row, table-column, table-cell, and table-caption elements is undefined.
+
absolute
+
The element is removed from the normal document flow, and no space is created for the element in the page layout. It is positioned relative to its closest positioned ancestor, if any; otherwise, it is placed relative to the initial containing block. Its final position is determined by the values of top, right, bottom, and left.
+
This value creates a new stacking context when the value of z-index is not auto. The margins of absolutely positioned boxes do not collapse with other margins.
+
fixed
+
The element is removed from the normal document flow, and no space is created for the element in the page layout. It is positioned relative to the initial containing block established by the {{glossary("viewport")}}, except when one of its ancestors has a transform, perspective, or filter property set to something other than none (see the CSS Transforms Spec), in which case that ancestor behaves as the containing block. (Note that there are browser inconsistencies with perspective and filter contributing to containing block formation.) Its final position is determined by the values of top, right, bottom, and left.
+
This value always creates a new stacking context. In printed documents, the element is placed in the same position on every page.
+
sticky
+
The element is positioned according to the normal flow of the document, and then offset relative to its nearest scrolling ancestor and containing block (nearest block-level ancestor), including table-related elements, based on the values of top, right, bottom, and left. The offset does not affect the position of any other elements.
+
This value always creates a new stacking context. Note that a sticky element "sticks" to its nearest ancestor that has a "scrolling mechanism" (created when overflow is hidden, scroll, auto, or overlay), even if that ancestor isn't the nearest actually scrolling ancestor. This effectively inhibits any "sticky" behavior (see the Github issue on W3C CSSWG).
+
+ +

Sintáxe formal

+ +
{{csssyntax}}
+ +

Exemplos

+ +

Posicionamento relativo

+ +

Relatively positioned elements are offset a given amount from their normal position within the document, but without the offset affecting other elements. In the example below, note how the other elements are placed as if "Two" were taking up the space of its normal location.

+ +

HTML

+ +
<div class="box" id="one">One</div>
+<div class="box" id="two">Two</div>
+<div class="box" id="three">Three</div>
+<div class="box" id="four">Four</div>
+
+ +

CSS

+ +
.box {
+  display: inline-block;
+  width: 100px;
+  height: 100px;
+  background: red;
+  color: white;
+}
+
+#two {
+  position: relative;
+  top: 20px;
+  left: 20px;
+  background: blue;
+}
+
+ +

{{ EmbedLiveSample('Relative_positioning', '600px', '200px') }}

+ +

Posicionamento absoluto

+ +

Elements that are relatively positioned remain in the normal flow of the document. In contrast, an element that is absolutely positioned is taken out of the flow; thus, other elements are positioned as if it did not exist. The absolutely positioned element is positioned relative to its nearest positioned ancestor (i.e., the nearest ancestor that is not static). If a positioned ancestor doesn't exist, it is positioned relative to the ICB (initial containing block — see also the W3C definition), which is the containing block of the document's root element.

+ +

A simple example follows:

+ +
<h1>Absolute positioning</h1>
+
+<p>I am a basic block level element. My adjacent block level elements sit on new lines below me.</p>
+
+<p class="positioned">By default we span 100% of the width of our parent element, and we are as tall as our child content. Our total width and height is our content + padding + border width/height.</p>
+
+<p>We are separated by our margins. Because of margin collapsing, we are separated by the width of one of our margins, not both.</p>
+
+<p>inline elements <span>like this one</span> and <span>this one</span> sit on the same line as one another, and adjacent text nodes, if there is space on the same line. Overflowing inline elements <span>wrap onto a new line if possible — like this one containing text</span>, or just go on to a new line if not, much like this image will do: <img src="https://mdn.mozillademos.org/files/13360/long.jpg"></p>
+ +
body {
+  width: 500px;
+  margin: 0 auto;
+}
+
+p {
+  background: aqua;
+  border: 3px solid blue;
+  padding: 10px;
+  margin: 10px;
+}
+
+span {
+  background: red;
+  border: 1px solid black;
+}
+
+.positioned {
+  position: absolute;
+  background: yellow;
+  top: 30px;
+  left: 30px;
+}
+ +

{{ EmbedLiveSample('Absolute_positioning', '100%', 420) }}

+ +

Posicionamento fixo

+ +

Fixed positioning is similar to absolute positioning, with the exception that the element's containing block is the initial containing block established by the viewport, unless any ancestor has transform, perspective, or filter property set to something other than none (see CSS Transforms Spec), which then causes that ancestor to take the place of the elements containing block. This can be used to create a "floating" element that stays in the same position regardless of scrolling. In the example below, box "One" is fixed at 80 pixels from the top of the page and 10 pixels from the left. Even after scrolling, it remains in the same place relative to the viewport.

+ +

HTML

+ +
<div class="outer">
+  <p>
+    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam congue tortor eget pulvinar lobortis.
+    Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nam ac dolor augue.
+    Pellentesque mi mi, laoreet et dolor sit amet, ultrices varius risus. Nam vitae iaculis elit.
+    Aliquam mollis interdum libero. Sed sodales placerat egestas. Vestibulum ut arcu aliquam purus viverra dictum vel sit amet mi.
+    Duis nisl mauris, aliquam sit amet luctus eget, dapibus in enim. Sed velit augue, pretium a sem aliquam, congue porttitor tortor.
+    Sed tempor nisl a lorem consequat, id maximus erat aliquet. Sed sagittis porta libero sed condimentum.
+    Aliquam finibus lectus nec ante congue rutrum. Curabitur quam quam, accumsan id ultrices ultrices, tempor et tellus.
+  </p>
+  <p>
+    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam congue tortor eget pulvinar lobortis.
+    Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nam ac dolor augue.
+    Pellentesque mi mi, laoreet et dolor sit amet, ultrices varius risus. Nam vitae iaculis elit.
+    Aliquam mollis interdum libero. Sed sodales placerat egestas. Vestibulum ut arcu aliquam purus viverra dictum vel sit amet mi.
+    Duis nisl mauris, aliquam sit amet luctus eget, dapibus in enim. Sed velit augue, pretium a sem aliquam, congue porttitor tortor.
+    Sed tempor nisl a lorem consequat, id maximus erat aliquet. Sed sagittis porta libero sed condimentum.
+    Aliquam finibus lectus nec ante congue rutrum. Curabitur quam quam, accumsan id ultrices ultrices, tempor et tellus.
+  </p>
+  <div class="box" id="one">One</div>
+</div>
+
+ +

CSS

+ +
.box {
+  width: 100px;
+  height: 100px;
+  background: red;
+  color: white;
+}
+
+#one {
+  position: fixed;
+  top: 80px;
+  left: 10px;
+  background: blue;
+}
+
+.outer {
+  width: 500px;
+  height: 300px;
+  overflow: scroll;
+  padding-left: 150px;
+}
+
+ +

{{ EmbedLiveSample('Fixed_positioning', '800px', '300px') }}

+ +

Posicionamento Adesivo

+ +

Sticky positioning can be thought of as a hybrid of relative and fixed positioning. A stickily positioned element is treated as relatively positioned until it crosses a specified threshold, at which point it is treated as fixed until it reaches the boundary of its parent. For instance...

+ +
#one { position: sticky; top: 10px; }
+ +

...would position the element with id one relatively until the viewport were scrolled such that the element would be less than 10 pixels from the top. Beyond that threshold, the element would be fixed to 10 pixels from the top.

+ +

A common use for sticky positioning is for the headings in an alphabetized list. The "B" heading will appear just below the items that begin with "A" until they are scrolled offscreen. Rather than sliding offscreen with the rest of the content, the "B" heading will then remain fixed to the top of the viewport until all the "B" items have scrolled offscreen, at which point it will be covered up by the "C" heading, and so on.

+ +

You must specify a threshold with at least one of top, right, bottom, or left for sticky positioning to behave as expected. Otherwise, it will be indistinguishable from relative positioning.

+ +

HTML

+ +
<dl>
+  <div>
+    <dt>A</dt>
+    <dd>Andrew W.K.</dd>
+    <dd>Apparat</dd>
+    <dd>Arcade Fire</dd>
+    <dd>At The Drive-In</dd>
+    <dd>Aziz Ansari</dd>
+  </div>
+  <div>
+    <dt>C</dt>
+    <dd>Chromeo</dd>
+    <dd>Common</dd>
+    <dd>Converge</dd>
+    <dd>Crystal Castles</dd>
+    <dd>Cursive</dd>
+  </div>
+  <div>
+    <dt>E</dt>
+    <dd>Explosions In The Sky</dd>
+  </div>
+  <div>
+    <dt>T</dt>
+    <dd>Ted Leo &amp; The Pharmacists</dd>
+    <dd>T-Pain</dd>
+    <dd>Thrice</dd>
+    <dd>TV On The Radio</dd>
+    <dd>Two Gallants</dd>
+  </div>
+</dl>
+
+ +

CSS

+ +
* {
+  box-sizing: border-box;
+}
+
+dl > div {
+  background: #FFF;
+  padding: 24px 0 0 0;
+}
+
+dt {
+  background: #B8C1C8;
+  border-bottom: 1px solid #989EA4;
+  border-top: 1px solid #717D85;
+  color: #FFF;
+  font: bold 18px/21px Helvetica, Arial, sans-serif;
+  margin: 0;
+  padding: 2px 0 0 12px;
+  position: -webkit-sticky;
+  position: sticky;
+  top: -1px;
+}
+
+dd {
+  font: bold 20px/45px Helvetica, Arial, sans-serif;
+  margin: 0;
+  padding: 0 0 0 12px;
+  white-space: nowrap;
+}
+
+dd + dd {
+  border-top: 1px solid #CCC;
+}
+
+ +

{{ EmbedLiveSample('Sticky_positioning', '500px', '300px') }}

+ +

Accessibility concerns

+ +

Ensure that elements positioned with an absolute or fixed value do not obscure other content when the page is zoomed to increase text size.

+ + + +

Performance & Accessibility

+ +

Scrolling elements containing fixed or sticky content can cause performance and accessibility issues. As a user scrolls, the browser must repaint the sticky or fixed content in a new location. Depending on the content needing to be repainted, the browser performance, and the device's processing speed, the browser may not be able to manage repaints at 60 fps, causing accessibility concerns for people with sensitivities and jank for everyone. One solution is to add {{cssxref("will-change", "will-change: transform")}} to the positioned elements to render the element in its own layer, improving repaint speed and therefore improving performance and accessibility.

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS2.1', 'visuren.html#propdef-position', 'position')}}{{Spec2('CSS2.1')}}
{{SpecName('CSS3 Positioning','#position-property','position')}}{{Spec2('CSS3 Positioning')}}Adds sticky property value.
+ +

{{cssinfo}}

+ +

Compatibilidade do navegador

+ + + +

{{Compat("css.properties.position")}}

diff --git a/files/pt-br/web/css/privacidade_e_o_seletor__colon_visited/index.html b/files/pt-br/web/css/privacidade_e_o_seletor__colon_visited/index.html new file mode 100644 index 0000000000..273c7765e3 --- /dev/null +++ b/files/pt-br/web/css/privacidade_e_o_seletor__colon_visited/index.html @@ -0,0 +1,76 @@ +--- +title: 'Privacidade e o seletor :visited' +slug: 'Web/CSS/Privacidade_e_o_seletor_:visited' +tags: + - CSS + - Guía + - Pseudo-classe + - Referencia + - Segurança + - Seletores +translation_of: 'Web/CSS/Privacy_and_the_:visited_selector' +--- +
{{cssref}}
+ +

Antes de 2010, o seletor CSS {{ cssxref(":visited") }} permitia que websites descobrissem o histórico de navegação dos usuários e quais sites estes haviam visitado. Isto foi feito por meio do {{domxref("window.getComputedStyle")}} e outras tecnicas. Este processo era fácil de ser feito, e tornou possível não somente determinar onde os usuários estiveram na internet, mas também poderia ser usado para descobrir um monte de informação sobre a identidade destes.

+ +

Para contornar este problema, {{ Gecko("2") }} implementou atualizações de privacidade para limitar a quantidade de informações que poderiam ser obtidas através dos links visitados. Outros navegadores também fizeram mudanças similares.

+ +

Pequenas mentiras brancas

+ +

Para preservar a privacidade dos usuários, Firefox e outros navegadores irão mentir para aplicações webs sob certas circustâncias:

+ +
    +
  • O método window.getComputedStyle, e funções similares tal como {{ domxref("element.querySelector") }}, sempre retornarão valores indicando que os usuários nunca visitaram quaisquer links em uma página.
  • +
  • Se você usa seletores como seletores de irmãos como :visited + span, o elemento imediato (span neste exemplo) será estilizado como se o link não houvesse sido visitado.
  • +
  • Em raros casos, se você está utilizando elementos de links aninhados e o elemento que está sendo correspondido é diferente do link cuja presença no histórico está sendo testado, o elemento também será renderizado como se o link não houvesse sido visitado.
  • +
+ + + +

Você pode estilizar links visitados, porém existem limites de quais estilos você pode usar. Somente os seguintes estilos podem ser aplicados para links visitados:

+ +
    +
  • {{ cssxref("color") }}
  • +
  • {{ cssxref("background-color") }}
  • +
  • {{ cssxref("border-color") }} (e suas subpropriedades)
  • +
  • {{ cssxref("column-rule-color") }}
  • +
  • {{ cssxref("outline-color") }}
  • +
  • As partes de cor dos atributos {{SVGAttr("fill")}} e {{SVGAttr("stroke")}}
  • +
+ +

Em adição, mesmo para os estilos acima, você não poderá alterar a transparência entre links visitados e não visitados, ou de outra maneira você seria capaz de usar rgba(), hsla(), ou a palavra chave transparent.

+ +

Aqui está um exemplo de como estilizar com as restrições acima mencionadas:

+ +
:link {
+  outline: 1px dotted blue;
+  background-color: white;
+  /* O valor padrão de background-color é `transparent`. Você precisa
+     especificar um valor diferente, caso contrário as mudanças
+     feitas em :visited não se aplicam. */
+}
+
+:visited {
+  outline-color: orange;    /* Links visitados tem contornos laranja */
+  background-color: green;  /* Links visitados tem um fundo verde */
+  color: yellow;            /* Links visitados tem texto amarelo */
+}
+
+ +

Impacto nos desenvolvedores web

+ +

No geral, essas restrições estas restrições não deveriam afetar desenvolvedores web tão significamente. Eles poderiam, como sempre, They may, no entanto, requerer essas seguintes mudanças nos sites existentes:

+ +
    +
  • Usar imagens de fundo para estilizar links baseados se eles foram visitados não irá funcionar, desde que apenas cores podem ser usadas para estilizar links visitados.
  • +
  • As cores que são transparentes deixarão de aparecer se estilizados em seletores :visited.
  • +
+ +

Veja também

+ + diff --git a/files/pt-br/web/css/pseudo-classes/index.html b/files/pt-br/web/css/pseudo-classes/index.html new file mode 100644 index 0000000000..40cb2ea24c --- /dev/null +++ b/files/pt-br/web/css/pseudo-classes/index.html @@ -0,0 +1,143 @@ +--- +title: Pseudo-classes +slug: Web/CSS/Pseudo-classes +tags: + - CSS + - CSS Referência + - Intermediário + - Seletores +translation_of: Web/CSS/Pseudo-classes +--- +

{{ CSSRef() }}

+ +

Uma pseudo-classe CSS é uma palavra-chave adicionada a seletores que especifica um estado especial do elemento selecionado. Por exemplo, {{Cssxref(":hover")}} pode ser usado para alterar a cor de um botão quando o usuário passar o cursor sobre ele.

+ +
/*Qualquer botão sobre o qual o ponteiro do usuário esteja passando sobre*/
+button:hover {
+  color: blue;
+}
+ +

Pseudo-classes permitem que você aplique um estilo a um elemento não apenas em relação ao conteúdo da árvore do documento, mas também em relação a fatores externos como o histórico de navegação ({{CSSxRef(":visited")}}, por exemplo), o status do seu conteúdo (como {{ CSSxRef(":checked")}} em certos elementos de um formulário), ou a posição do mouse (como {{CSSxRef(":hover")}}, que permite saber se o mouse está sobre um elemento ou não).

+ +
+

Observação: Diferentemente das pseudo-classes, pseudo-elementos podem ser usados para estilizar uma parte específica de um elemento.

+
+ +

Sintaxe

+ +
seletor:pseudo-classe {
+  propriedade: valor;
+}
+
+ +

Assim como nas classes regulares, você pode encadear juntas quantas pseudo-classes você desejar em um seletor.

+ +

Índice de pseudo-classes padrão

+ +
+
    +
  • {{ Cssxref(":active") }}
  • +
  • {{ Cssxref(":checked") }}
  • +
  • {{ Cssxref(":default") }}
  • +
  • {{ Cssxref(":dir", ":dir()")}}
  • +
  • {{ Cssxref(":disabled") }}
  • +
  • {{ Cssxref(":empty") }}
  • +
  • {{ Cssxref(":enabled") }}
  • +
  • {{ Cssxref(":first") }}
  • +
  • {{ Cssxref(":first-child") }}
  • +
  • {{ Cssxref(":first-of-type") }}
  • +
  • {{ Cssxref(":fullscreen") }}
  • +
  • {{ Cssxref(":focus") }}
  • +
  • {{ Cssxref(":hover") }}
  • +
  • {{ Cssxref(":indeterminate") }}
  • +
  • {{ Cssxref(":in-range") }}
  • +
  • {{ Cssxref(":invalid") }}
  • +
  • {{ Cssxref(":lang", ":lang()") }}
  • +
  • {{ Cssxref(":last-child") }}
  • +
  • {{ Cssxref(":last-of-type") }}
  • +
  • {{ Cssxref(":left") }}
  • +
  • {{ Cssxref(":link") }}
  • +
  • {{ Cssxref(":not", ":not()") }}
  • +
  • {{ Cssxref(":nth-child", ":nth-child()") }}
  • +
  • {{ Cssxref(":nth-last-child", ":nth-last-child()") }}
  • +
  • {{ Cssxref(":nth-last-of-type", ":nth-last-of-type()") }}
  • +
  • {{ Cssxref(":nth-of-type", ":nth-of-type()") }}
  • +
  • {{ Cssxref(":only-child") }}
  • +
  • {{ Cssxref(":only-of-type") }}
  • +
  • {{ Cssxref(":optional") }}
  • +
  • {{ Cssxref(":out-of-range") }}
  • +
  • {{ Cssxref(":read-only") }}
  • +
  • {{ Cssxref(":read-write") }}
  • +
  • {{ Cssxref(":required") }}
  • +
  • {{ Cssxref(":right") }}
  • +
  • {{ Cssxref(":root") }}
  • +
  • {{ Cssxref(":scope") }}
  • +
  • {{ Cssxref(":target") }}
  • +
  • {{ Cssxref(":valid") }}
  • +
  • {{ Cssxref(":visited") }}
  • +
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{ SpecName('Fullscreen') }}{{ Spec2('Fullscreen') }}Define :fullscreen.
{{ SpecName('HTML WHATWG') }}{{ Spec2('HTML WHATWG') }}Nenhuma mudança de  {{ SpecName('HTML5 W3C') }}.
{{SpecName('CSS4 Selectors')}}{{Spec2('CSS4 Selectors')}}Define :any-link, :local-link, :scope, :active-drop-target, :valid-drop-target, :invalid-drop-target, :current, :past, :future, :placeholder-shown, :user-error, :blank, :nth-match(), :nth-last-match(), :nth-column(), :nth-last-column(), e :matches().
+ Nenhuma mudança significante das pseudo-classes definidas em {{SpecName('CSS3 Selectors')}} e {{SpecName('HTML5 W3C')}} (embora o significado semântico que não foram retomadas).
{{ SpecName('HTML5 W3C') }}{{ Spec2('HTML5 W3C') }}Define o siginificado semântico no contexto do HTML :link, :visited, :active, :enabled, :disabled, :checked, e :indeterminate.
+ Define :default, :valid, :invalid, :in-range, :out-of-range, :required, :optional, :read-only, :read-write, e :dir().
{{ SpecName('CSS3 Basic UI') }}{{ Spec2('CSS3 Basic UI') }}Define :default, :valid, :invalid, :in-range, :out-of-range, :required, :optional, :read-only, e :read-write, mas sem associar significado semântico.
{{SpecName('CSS3 Selectors')}}{{Spec2('CSS3 Selectors')}}Define :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, e :not().
+ Denife a sintaxe de :enabled, :disabled, :checked, e :indeterminate, mas sem o significado semântico associado. Nenhuma mudança significativa, para as pseudo-classes definidas em {{SpecName('CSS2.1')}}.
{{SpecName('CSS2.1')}}{{Spec2('CSS2.1')}}Define :lang(), :first-child, :hover, e :focus.
+ Nenhuma mudança significativa, para as pseudo-classes definidas em{{SpecName('CSS1')}}.
{{SpecName('CSS1')}}{{Spec2('CSS1')}}Define :link, :visited, e :active, mas sem o significado semântico associado.
+ +

Veja também

+ +
    +
  • {{ Cssxref("pseudo-elements") }}
  • +
diff --git a/files/pt-br/web/css/pseudo-elementos/index.html b/files/pt-br/web/css/pseudo-elementos/index.html new file mode 100644 index 0000000000..a457c9ac9a --- /dev/null +++ b/files/pt-br/web/css/pseudo-elementos/index.html @@ -0,0 +1,104 @@ +--- +title: Pseudo-elementos +slug: Web/CSS/Pseudo-elementos +tags: + - CSS + - Principiantes + - Pseudo-elementos + - Referencia + - Seletores +translation_of: Web/CSS/Pseudo-elements +--- +
{{ CSSRef() }}
+ +
Um pseudo-elemento CSS é uma palavra-chave adicionada a um seletor que permite que você estilize uma parte específica do elemento selecionado. Por exemplo, o pseudo-elemento {{CSSxRef("::first-line")}} aplica o estilo apenas na primeira linha de um parágrafo.
+ +
+ +
/* A primeira linha de todo elemento <p>. */
+p::first-line {
+  color: blue;
+  text-transform: uppercase;
+}
+ +
+

Observação: Diferentemente dos pseudo-elementos, {{cssxref("pseudo-classes")}} podem ser utilizadas para estilizar um elemento baseado em seu estado.

+
+ +

Sintaxe

+ +
seletor::pseudo-elemento {
+  propriedade: valor;
+}
+
+ +

Você pode utilizar apenas um pseudo-elemento em um seletor. Ele deve aparecer depois da declaração de um elemento simples.

+ +

Observação: Como regra, os dois pontos devem ser usados duas vezes  (::)  ao invés de uma única vez  (:). Isso distingue pseudo-classes de pseudo-elementos. Apesar disso, devido a essa distinção não estar presente em versões mais antigas da especificação da W3C, a maioria dos navegadores suportam ambas as sintaxes para os pseudo-elementos originais.

+ +

Índice de pseudo-elementos comuns

+ +
+
    +
  • {{ Cssxref("::after") }}
  • +
  • {{ Cssxref("::before") }}
  • +
  • {{ cssxref("::cue")}}
  • +
  • {{ Cssxref("::first-letter") }}
  • +
  • {{ Cssxref("::first-line") }}
  • +
  • {{ Cssxref("::selection") }}
  • +
  • {{ Cssxref("::slotted") }}
  • +
  • {{ Cssxref("::backdrop") }} {{experimental_inline}}
  • +
  • {{ Cssxref("::placeholder") }} {{experimental_inline}}
  • +
  • {{ Cssxref("::marker") }} {{experimental_inline}}
  • +
  • {{ Cssxref("::spelling-error") }} {{experimental_inline}}
  • +
  • {{ Cssxref("::grammar-error") }} {{experimental_inline}}
  • +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NavegadorVersão mais baixaSuporte de
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
+ +

Ver também

+ + diff --git a/files/pt-br/web/css/radial-gradient()/index.html b/files/pt-br/web/css/radial-gradient()/index.html new file mode 100644 index 0000000000..1479f4b77b --- /dev/null +++ b/files/pt-br/web/css/radial-gradient()/index.html @@ -0,0 +1,209 @@ +--- +title: radial-gradient() +slug: Web/CSS/radial-gradient() +translation_of: Web/CSS/radial-gradient() +--- +

{{ CSSRef() }}

+ +

Resumo

+ +

A função do CSS radial-gradient() cria uma {{cssxref("<image>")}} que representa um gradiente de cores irradiando de uma origem, o centro do gradiente. O resultado dessa função é um objeto do CSS do tipo {{cssxref("<gradient>")}}.

+ +

Gradientes radiais são definidos pelo seu centro, o contorno e a posição da forma de fechamento (ending shape) e as paradas de cor (color stops). O gradiente radial consiste de formas concêntricas uniformemente escaladas partindo do centro até sua forma de fechamento, indo potencialmente além, com a mesma forma da forma de fechamento. As paradas de cor são posicionadas num raio de gradiente virtual saindo do centro horizontalmente para a direita. O posicionamento das porcentagens das paradas de cor são relativas à interseção entre a forma de fechamento e esse raio de gradiente representando 100%. Cada forma é monocromática e a cor, definida pela cor no raio de gradiente que intersecta.

+ +

Formas de fechamento podem ser apenas círculo (circle) ou elipse (ellipse).

+ +

Como qualquer outro gradiente, um gradiente radial do CSS não é uma <cor> do CSS, mas uma imagem sem dimensões intrínsecas, i. e. uma imagem sem tamanho natural ou preferencial, tampouco proporção. Seu tamanho concreto será idêntico ao tamanho do elemento ao qual for aplicado.

+ +

A função radial-gradient não permite criar gradientes repetitivos. Para esse efeito, use a função do CSS {{ Cssxref("repeating-radial-gradient") }}.

+ +

Sintaxe

+ +
Gramática formal: radial-gradient( [ circle || <length> ] [ at <position> ]? ,
+| [ ellipse || [<length> | <percentage> ]{2}] [ at <position> ]? ,
+| [ [ circle | ellipse ] || <extent-keyword> ] [ at <position> ]? ,
+| at <position> ,
+<color-stop> [ , <color-stop> ]+ )
+
+ +

Valores

+ +
+
<position>
+
Uma {{cssxref("<position>")}}, interpretada da mesma forma que {{Cssxref("background-position")}} ou {{Cssxref("transform-origin")}}. Se omitida, assume o padrão center.
+
<shape>
+
A forma do gradiente. Esse valor é circle (indicando que a forma do gradiente é um círculo com raio constante) ou ellipse (indicando que a forma é uma elipse com os eixos alinhados ao elemento). O valor padrão é ellipse.
+
<size>
+
O tamanho do gradiente. Essa valor é uma das {{anch("Restrições de tamanho")}} listada abaixo.
+
<color-stop>
+
Representando uma cor fixa num determinado ponto, esse valor é composto por um valor {{cssxref("<color>")}}, seguido de uma posição de parada opcional (uma {{cssxref("<percentage>")}} ou uma {{cssxref("<length>")}} referente ao raio de gradiente virtual). Uma porcentagem de 0%, ou um tamanho de 0 representa o centro do gradiente e o valor 100% a interseção da forma de fechamento com o raio de gradiente virtual. Valores de porcentagem intermediários são posicionados linearmente no raio de gradiente.
+
<extent-keyword>
+
Palavras-chave descrevendo quão grande a forma de fechamento deve ser. Os possíveis valores são:
+
+ + + + + + + + + + + + + + + + + + + + + + + +
ConstanteDescrição
closest-sideA forma de fechamento do gradiente encontra o lado do elemento mais próximo ao seu centro (para círculos) ou encontra ambos os lados vertical e horizontal mais próximos ao centro (para elipses).
closest-cornerA forma de fechamento do gradiente tem o tamanho exato para encontrar o canto da caixa mais próximo ao seu centro.
farthest-sideSimilar ao closest-side, mas a forma de fechamento fica com o tamanho necessário para encontrar o lado do elemento mais distante do centro do gradiente (ou lados vertical e horizontal).
farthest-cornerA forma de fechamento do gradiente tem o tamanho exato para encontrar o canto da caixa mais distante de seu centro.
+ Rascunhos preliminares incluiam outras palavras-chave (cover e contain) como sinônimos dos valores do padrão farthest-corner e closest-side respectivamente. Use somente os valores do padrão, uma vez que algumas implementações podem já ter removido suporte a esses valores mais antigos.
+
+ +

Exemplos

+ +
ellipse farthest-corner
+ +
background-image: radial-gradient(ellipse farthest-corner at 45px 45px , #00FFFF 0%, rgba(0, 0, 255, 0) 50%, #0000FF 95%);
+
+ +
470px 47px
+ +
background-image: radial-gradient(ellipse farthest-corner at 470px 47px , #FFFF80 20%, rgba(204, 153, 153, 0.4) 30%, #E6E6FF 60%);
+
+ +
farthest-corner
+ +
background-image: radial-gradient(farthest-corner at 45px 45px , #FF0000 0%, #0000FF 100%);
+ +
16px radius fuzzy circle
+ +
background-image: radial-gradient(16px at 60px 50% , #000000 0%, #000000 14px, rgba(0, 0, 0, 0.3) 18px, rgba(0, 0, 0, 0) 19px);
+
+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentários
{{ SpecName('CSS3 Images', '#radial-gradients', 'radial-gradients()') }}{{ Spec2('CSS3 Images') }} 
+ +

Compatibilidade de navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Suporte básico (suporte à função radial-gradient(), mas não necessariamente com a sintaxe final){{ CompatGeckoDesktop("1.9.2") }}{{ property_prefix("-moz") }} [3]
+ {{ CompatGeckoDesktop("16") }}
10.0 (534.16){{ property_prefix("-webkit") }} [2][3]10.0 [1]11.60{{ property_prefix("-o") }}5.1{{ property_prefix("-webkit") }}[2]
Sintaxe legada do webkit {{ non-standard_inline() }}{{ CompatNo() }}3{{ property_prefix("-webkit") }} [2]{{ CompatNo() }}{{ CompatNo() }}4.0{{ property_prefix("-webkit") }} [2]
Sintaxe at (sintaxe do padrão final){{ CompatGeckoDesktop("10") }}{{ property_prefix("-moz") }} [3]
+ {{ CompatGeckoDesktop("16") }}
{{ CompatNo() }}10.011.60{{ property_prefix("-o") }} [3]
+ Presto 2.12 will remove the prefix.
{{ CompatNo() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FuncionalidadeAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Suporte básico (suporte à função radial-gradient(), mas não necessariamente com a sintaxe final){{CompatVersionUnknown}}{{ CompatGeckoMobile("1.9.2") }}{{ property_prefix("-moz") }} [3]
+ {{ CompatGeckoMobile("16") }}
{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Sintaxe legada do webkit {{ non-standard_inline() }}{{CompatUnknown}}{{ CompatNo() }}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Sintaxe at (sintaxe do padrão final){{CompatUnknown}}{{ CompatGeckoMobile("10") }}{{ property_prefix("-moz") }} [3]
+ {{ CompatGeckoMobile("16") }}
{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Internet Explorer 5.5 a 9.0 suportam a funcionalidade proprietária filter: progid:DXImageTransform.Microsoft.Gradient() filter.

+ +

[2] WebKit desde 528 suporta a função legada -webkit-gradient(radial,…). Veja também o suporte atual para gradientes radiais.

+ +

[3] Firefox 3.6 e Webkit implementaram uma sintaxe anterior, prefixada.

+ +

Veja também

+ + diff --git a/files/pt-br/web/css/repeating-linear-gradient()/index.html b/files/pt-br/web/css/repeating-linear-gradient()/index.html new file mode 100644 index 0000000000..e2be000120 --- /dev/null +++ b/files/pt-br/web/css/repeating-linear-gradient()/index.html @@ -0,0 +1,153 @@ +--- +title: repeating-linear-gradient +slug: Web/CSS/repeating-linear-gradient() +translation_of: Web/CSS/repeating-linear-gradient() +--- +

{{ CSSRef() }}

+ +

Summary

+ +

A função CSS repeating-linear-gradient cria uma {{cssxref("<image>")}} de repetidos gradientes. Isso funciona da mesma forma, e recebe os mesmos argumentos dos gradientes lineares básicos, como descrito em {{ cssxref("linear-gradient") }}, mas ele automaticamente repete as paradas das cores infinitamente em ambas as direções, com suas posições trocadas por múltiplos da diferença entre a posição da última parada de cor e a posição da primeira.

+ +

The consequence is that an end color of a gradient always coincide with a start color. If both are not identical, this will result in a sharp transition.

+ +

Like any other gradient, a repeating CSS linear gradient is not a CSS <color> but an image with no intrinsic dimensions; that is, it has no natural or preferred size, nor ratio. Its concrete size will match the one of the element it applies to.

+ +

Mozilla currently only supports CSS gradients as values of the {{ Cssxref("background-image") }} property, as well as within the shorthand {{ Cssxref("background") }}. You specify a gradient value instead of an image URL.

+ +

Syntax

+ +
Formal grammar: repeating-linear-gradient(  [ <angle> | to <side-or-corner> ,]? <color-stop> [, <color-stop>]+ )
+                                            \---------------------------------/ \----------------------------/
+                                              Definition of the gradient line         List of color stops
+
+                              where <side-or-corner> = [left | right] || [top | bottom]
+                                and <color-stop>     = <color> [ <percentage> | <length> ]?
+
+ +
repeating-linear-gradient( 45deg, blue, red );           /* A repeating gradient on 45deg axe starting blue and finishing red */
+repeating-linear-gradient( to left top, blue, red);      /* A repeating gradient going from the bottom right to the top left
+                                                            starting blue and finishing red */
+
+repeating-linear-gradient( 0deg, blue, green 40%, red ); /* A repeating gradient going from the bottom to top, starting blue,
+                                                            being green after 40% and finishing red */
+
+ +

Values

+ +
+
<side-or-corner>
+
Represents the position of the starting-point of the gradient line. It consists of two keywords: the first one indicates the horizontal side, left or right, and the second one the vertical side, top or bottom. The order is not relevant and each of the keyword is optional.
+ The values to top, to bottom, to left and to right are translated into the angles 0deg, 180deg, 270deg, 90deg respectively. The others are translated into an angle that let the starting-point to be in the same quadrant than the described corner and so that the line defined by the starting-point and the corner is perpendicular to the gradient line. That way, the color described by the <color-stop> will exactly apply to the corner point. This is sometimes called the "magic corner" property. The end-point of the gradient line is the symmetrical point of the starting-point on the other direction of the center box.
+
<angle>
+
An angle of direction for the gradient. See {{ cssxref("<angle>") }}.
+
<color-stop>
+
This value is comprised of a {{cssxref("<color>")}} value, followed by an optional stop position (either a percentage between 0% and 100% or a {{cssxref("<length>")}} along the gradient axis).
+ Rendering of color-stops in CSS gradients follows the same rules as color-stops in SVG gradients.
+
+ +

Examples

+ +
background: repeating-linear-gradient(to bottom right, red, red 5px, white 5px, white 10px);
+
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSS3 Images', '#repeating-gradients', 'repeating-linear-gradient()') }}{{ Spec2('CSS3 Images') }} 
+ +

Browser compatibility

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Basic support (on {{ cssxref("background") }} and {{ cssxref("background-image") }}){{ CompatGeckoDesktop("1.9.2") }}{{ property_prefix("-moz") }}[3]
+ {{ CompatGeckoDesktop("16") }}
10.0 (534.16){{ property_prefix("-webkit") }} [2][3]10.0 [1]11.10{{ property_prefix("-o") }} [3]5.1{{ property_prefix("-webkit") }}[2][3]
On any properties that accept {{cssxref("<image>")}}{{ CompatNo() }}{{ CompatVersionUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatVersionUnknown() }}
Legacy webkit syntax{{ non-standard_inline() }}{{ CompatNo() }}3{{ property_prefix("-webkit") }} [2]{{ CompatNo() }}{{ CompatNo() }}4.0{{ property_prefix("-webkit") }}[2]
Legacy from syntax (without to){{ non-standard_inline() }}{{ CompatGeckoDesktop("1.9.2") }}{{ property_prefix("-moz") }} [4]
+ Removed in {{ CompatGeckoDesktop("16") }}
10.0 (534.16){{ property_prefix("-webkit") }} [2]10.011.10{{ property_prefix("-o") }}[4]5.1{{ property_prefix("-webkit") }}[2]
to syntax{{ CompatGeckoDesktop("10") }}{{ property_prefix("-moz") }}[4]
+ {{ CompatGeckoDesktop("16") }}
{{ CompatNo() }}10.011.60{{ property_prefix("-o") }}[4]
+ Presto 2.12 will remove the prefix.
{{ CompatNo() }}
+ +

[1] Internet Explorer 5.5 through 9.0 supports proprietary filter: progid:DXImageTransform.Microsoft.Gradient() filter.

+ +

[2] WebKit since 528 supports the legacy -webkit-gradient(linear,…) function. As of WebKit 534.16, it also supports the standard gradient syntax. Unlike in Gecko, in legacy WebKit you cannot specify both a position and angle in -webkit-linear-gradient(). You can achieve the same effect by offsetting the color stops.

+ +

[3] Gecko, Opera & Webkit considers {{cssxref("<angle>")}} to start to the right, instead of the top. I.e. it considered an angle of to start to the right, instead of the top. I.e. it considered an angle of 0deg as a direction indicator pointing to the right. This is different from the latest specification where an angle of 0deg as a direction indicator points to the top.

+ +

[4] Firefox 3.6 and Opera 11.10 implemented, prefixed, an early syntax where the starting corner or side was indicated without the to keyword, and effectively considered as a from position. The to syntax has been added in Firefox 10 and Opera 11.60 , at first without removing the deprecated syntax and translation between the two is trivial:

+ +
-moz-repeating-linear-gradient(to top left, blue, red);
+ +

is the same as:

+ +
-moz-repeating-linear-gradient(bottom right, blue, red);
+ +

The legacy syntax, without to, is planned to go away when the prefix is removed.

+ +

See also

+ +
    +
  • Using CSS gradients, {{ cssxref("radial-gradient", "radial-gradient()") }}, {{ cssxref("linear-gradient", "linear-gradient()") }}, {{ cssxref("repeating-radial-gradient", "repeating-radial-gradient()") }};
  • +
  • Some properties where it can be used: {{ cssxref("background-image") }}, {{ cssxref("background") }}.
  • +
diff --git a/files/pt-br/web/css/ruby-align/index.html b/files/pt-br/web/css/ruby-align/index.html new file mode 100644 index 0000000000..f67cfc1262 --- /dev/null +++ b/files/pt-br/web/css/ruby-align/index.html @@ -0,0 +1,239 @@ +--- +title: ruby-align +slug: Web/CSS/ruby-align +tags: + - CSS + - Propriedade + - Referencia + - Referencia CSS +translation_of: Web/CSS/ruby-align +--- +
{{CSSRef}}{{SeeCompatTable}}
+ +

Summary

+ +

A propriedade ruby-align do CSS define a distribuição dos direfentes elementos do ruby sobre a base.

+ +

{{cssinfo}}

+ +

Sintaxe

+ +
/* Valores chave */
+ruby-align: start;
+ruby-align: center;
+ruby-align: space-between;
+ruby-align: space-around;
+
+/* Valores globais */
+ruby-align: inherit;
+ruby-align: initial;
+ruby-align: unset;
+
+ +

Values

+ +
+
start
+
É uma palavra-chave indicando que o ruby será alinhado com o início do texto base.
+
center
+
É uma palavra-chave indicando que o ruby será alinhado no meio do texto base.
+
space-between
+
É uma palavra-chave indicando que o espaço extra será distruibuído entre os elementos do ruby.
+
space-around
+
É uma palavra-chave indicando que o espaço extra será distruibuído entre os elementos do ruby e em torno deles.
+
+ +

Sintaxe formal

+ +
{{csssyntax}}
+ +

Exemplos

+ +

Esse HTML irá renderizar diferentemente com cada valor do ruby-align:

+ +
<ruby>
+  <rb>Esse é um grande texto para verificar</rb>
+  <rp>(</rp><rt>ruby curto</rt><rp>)</rp>
+</ruby>
+
+ +

Ruby alinhado no ínicio do texto base

+ + + +
ruby {
+  ruby-align:start;
+}
+ +

Isso dará o seguinte resultado:

+ +

{{EmbedLiveSample("Ruby_aligned_at_the_start_of_the_base_text", 180, 40)}}

+ +

Ruby alinhado no centro do texto base

+ + + +
ruby {
+  ruby-align:center;
+}
+ +

Isso dará o seguinte resultado:

+ +

{{EmbedLiveSample("Ruby_aligned_at_the_center_of_the_base_text", 180, 40)}}

+ +

Espaço extra distribuído entre os elementos do ruby

+ + + +
ruby {
+  ruby-align:space-between;
+}
+ +

Isso dará o seguinte resultado:

+ +

{{EmbedLiveSample("Extra_space_distributed_between_ruby_elements", 180, 40)}}

+ +

Espaço extra distribuído entre os elementos do ruby e em torno deles

+ + + +
ruby {
+  ruby-align:space-around;
+}
+ +

Isso dará o seguinte resultado:

+ +

{{EmbedLiveSample("Extra_space_distributed_between_and_around_ruby_elements", 180, 40)}}

+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('CSS3 Ruby', '#ruby-align-property', 'ruby-align')}}{{Spec2('CSS3 Ruby')}}Definição inicital
+ +

Compatilibade de Navegador

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
AspectoChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte básico{{CompatNo}}{{CompatGeckoDesktop(38)}}{{CompatNo}}[1]{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Suporte básico{{CompatNo}}{{CompatGeckoMobile(38)}}{{CompatNo}}[1]{{CompatNo}}{{CompatNo}}
+
+ +

[1] Desde a versão 9 o Internet Explorer implementa um rascunho inicial do Ruby do CSS onde o ruby-align tinha os seguintes valores: auto, left, center, right, distribute-letter, distribute-space, and line-edge. Aqui está uma simples tabela de conversão:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Sintaxe do IESintaxe padrão
autoNão usa ruby-align
leftUsa start (em scripts ltr)
centercenter
rightUsa start (em scripts rtl)
distribute-letterNenhum equivalente direto, usa space-between ou space-around
distribute-spacespace-around
line-edgeNenhum equivalente direto.
+ +

Veja também

+ +
    +
  • Elementos Ruby do HTML: {{HTMLElement("ruby")}}, {{HTMLElement("rt")}}, {{HTMLElement("rp")}}, and {{HTMLElement("rtc")}}.
  • +
  • Propriedades Ruby do CSS: {{cssxref("ruby-position")}}, {{cssxref("ruby-merge")}}.
  • +
diff --git a/files/pt-br/web/css/scroll-behavior/index.html b/files/pt-br/web/css/scroll-behavior/index.html new file mode 100644 index 0000000000..13c2ca294c --- /dev/null +++ b/files/pt-br/web/css/scroll-behavior/index.html @@ -0,0 +1,172 @@ +--- +title: scroll-behavior +slug: Web/CSS/scroll-behavior +tags: + - CSS + - CSS PROPRIEDADE SCROLL + - CSS SCROLL + - PROPRIEDADES DO CSS + - REFERENCIA DE SCROLL +translation_of: Web/CSS/scroll-behavior +--- +
{{ CSSRef }}
+ +

A propriedade css scroll-behavior especifica o comportamento de rolagem para uma caixa de scrolling, quando a rolagem acontece devido às APIs do CSSOM. Qualquer outro scroll, aqueles que são executados pelo usuário, não são afetados por esta propriedade. Quando esta propriedade é especificada no elemento raiz, ela se aplica à viewport.

+ +

User agents podem ignorar essa propriedade.

+ +
/* Valores das palavras-chave */
+scroll-behavior: auto;
+scroll-behavior: smooth;
+
+/* Valores globais */
+scroll-behavior: inherit;
+scroll-behavior: initial;
+scroll-behavior: unset;
+
+ +

Note que qualquer outro scroll, tem essa tal performace para o usuario, essa propriedade não é afetada. Quando esta propriedade é especificada na raiz do elemento então aplicamos na instancia do viewport. 

+ +

Os usuarios que agem com está propriedade pode ignora-lá.

+ +

{{cssinfo}}

+ +

Sintaxe

+ +

O scroll-behavior é uma propriedade específica, com um valor de uma palavra-chave listada abaixo.

+ +

Valores

+ +
+
auto
+
A caixa de rolagem rola instantaneamente.
+
smooth
+
A caixa de scroll rola de forma suave usando uma função de temporização definida pelo usuário em um período de tempo. Os agentes do usuário devem seguir as convenções da plataforma, se houver.
+
+ +

Sintaxe formal

+ +
{{csssyntax}}
+ +

Exemplo

+ +

HTML

+ +
<nav>
+  <a href="#page-1">1</a>
+  <a href="#page-2">2</a>
+  <a href="#page-3">3</a>
+</nav>
+<scroll-container>
+  <scroll-page id="page-1">1</scroll-page>
+  <scroll-page id="page-2">2</scroll-page>
+  <scroll-page id="page-3">3</scroll-page>
+</scroll-container>
+ +

CSS

+ +
a {
+  display: inline-block;
+  width: 50px;
+  text-decoration: none;
+}
+nav, scroll-container {
+  display: block;
+  margin: 0 auto;
+  text-align: center;
+}
+nav {
+  width: 339px;
+  padding: 5px;
+  border: 1px solid black;
+}
+scroll-container {
+  display: block;
+  width: 350px;
+  height: 200px;
+  overflow-y: scroll;
+  scroll-behavior: smooth;
+}
+scroll-page {
+  display: flex;
+  align-items: center;
+  justify-content: center;
+  height: 100%;
+  font-size: 5em;
+}
+
+ +

Saída

+ +

{{ EmbedLiveSample('Example', "100%", 250) }}

+ +

Especificações

+ + + + + + + + + + + + + + + + +
EspecificaçõesStatusComentário
{{SpecName('CSSOM View', "#propdef-scroll-behavior", 'scroll-behavior')}}{{Spec2('CSSOM View')}}Especificações inicial
+ +

Compatibilidade com navegador

+ +

{{ CompatibilityTable }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support61[1]{{ CompatGeckoDesktop("36") }}{{CompatNo}}{{CompatVersionUnknown}}[1]{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{ CompatGeckoDesktop("36") }}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] Suporte ao Chrome e Opera, habilitando "Smooth Scrolling" ou "Enable experimental web platform features".

diff --git a/files/pt-br/web/css/scrollbar-color/index.html b/files/pt-br/web/css/scrollbar-color/index.html new file mode 100644 index 0000000000..6b368ab66b --- /dev/null +++ b/files/pt-br/web/css/scrollbar-color/index.html @@ -0,0 +1,119 @@ +--- +title: scrollbar-color +slug: Web/CSS/scrollbar-color +translation_of: Web/CSS/scrollbar-color +--- +
{{CSSRef}}{{SeeCompatTable}}
+ +

A propriedade CSS scrollbar-color define as cores da barra de rolagem do navegador.

+ +

Track refere-se ao fundo da barra de rolagem, que normalmente é fixa, independente da posição da página.

+ +

Thumb refere-se a parte móvel da barra de rolagem, um botão auxiliar que flutua acima da Track.

+ +

{{CSSInfo}}

+ +

Sintaxe

+ +
/* Palavras reservadas */
+scrollbar-color: auto;
+scrollbar-color: dark;
+scrollbar-color: light;
+
+/* Nomes de <color> */
+scrollbar-color: rebeccapurple green;   /* Duas cores válidas.
+O primeiro valor aplica-se ao Thumb, o segundo ao Track */
+
+/* Valores globais */
+scrollbar-color: inherit;
+scrollbar-color: initial;
+scrollbar-color: unset;
+
+ +

Valores

+ +
+
<scrollbar-color>
+
Define a cor da scrollbar. + + + + + + + + + + + + + + + + + + + +
auto +

Valor padrão de renderização do background da scrollbar (Track), caso não sejam definidos outros valores.

+
dark +

Mostra uma scrollbar mais escura, podendo ser um estilo padrão definido pelo navegador, ou personalizado com cores escuras.

+
lightMostra uma scrollbar mais clara, podendo ser um estilo padrão definido pelo navegador, ou personalizado com cores escuras.
<color> <color>A primeira cor é aplicada à thumb, a segunda cor ao track
+ +
+

Note: User Agents must apply any scrollbar-color value set on the root element to the viewport.

+
+
+
+ +

Sintaxe formal

+ +
{{CSSSyntax}}
+ +

Exemplo

+ +

CSS

+ +
.scroller {
+  width: 300px;
+  height: 100px;
+  overflow-y: scroll;
+  scrollbar-color: rebeccapurple green;
+}
+ +

HTML

+ +
<div class="scroller">Veggies es bonus vobis, proinde vos postulo essum magis kohlrabi welsh onion daikon amaranth tatsoi tomatillo melon azuki bean garlic. Gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette tatsoi pea sprouts fava bean collard greens dandelion okra wakame tomato. Dandelion cucumber earthnut pea peanut soko zucchini.</div>
+ +

Result

+ +
{{EmbedLiveSample("Example")}}
+ +

Cuidados de acessibilidade

+ +

When using scrollbar-color property with specific color values, authors should ensure the specified colors have enough contrast between them. For keyword values, UAs should ensure the colors they use have enough contrast. See Techniques for WCAG 2.0: G183: Using a contrast ratio of 3:1.

+ +

Especificações

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("CSS Scrollbars", "#scrollbar-color", "scrollbar-color")}}{{Spec2("CSS Scrollbars")}}Initial definition.
+ +

Compatibilidade entre navegadores

+ + + +
{{Compat("css.properties.scrollbar-color")}}
diff --git a/files/pt-br/web/css/seletor_de_atributos/index.html b/files/pt-br/web/css/seletor_de_atributos/index.html new file mode 100644 index 0000000000..88881a61ea --- /dev/null +++ b/files/pt-br/web/css/seletor_de_atributos/index.html @@ -0,0 +1,158 @@ +--- +title: Seletor de atributos +slug: Web/CSS/Seletor_de_atributos +translation_of: Web/CSS/Attribute_selectors +--- +
{{CSSRef}}
+ +

seletor de atributos combina elementos baseado no valor de um atributo dado.

+ +
/* <a> elementos com um atributo de título  */
+a[title] {
+  color: purple;
+}
+
+/* <a> elementos combinando com um href "https://example.org" */
+a[href="https://example.org"] {
+  color: green;
+}
+
+/* <a> elementos com um href contendo "example" */
+a[href*="example"] {
+  font-size: 2em;
+}
+
+/* <a> elementos com href terminando em ".org" */
+a[href$=".org"] {
+  font-style: italic;
+}
+ +
+
[attr]
+
Representa um elemento com atributo de nome attr.
+
[attr=value]
+
Representa um elemento com um atributo de nome attr, o qual o valor é  exatamente  value.
+
[attr~=value]
+
Representa um elemento com um atributo de nome attr, o qual value é  uma lista de palavras separadas por espaços, e uma dessas é  exatamente  value.
+
[attr|=value]
+
Representa um elemento com um atributo de nome attr  o qual o valor pode ser exatamente value ou pode começar com value imediatamente seguido por hífen - (U+002D). Isso somente é usado para linguagens que combinam sub-códigos.
+
[attr^=value]
+
Representa um elemento com um atributo com nome attr que tem um valor prefixado (precedido) por value.
+
[attr$=value]
+
Representa um elemento com um atributo de nome attr que  tem como sufixo (seguido) por value.
+
[attr*=value]
+
Representa um elemento com um atributo de nome attr o qual valor contém ao menos uma ocorrência de value contido na string.
+
[attr operator value i]
+
Adiciona um i (ou I) antes do fechamento das chaves {}, faz com que o valor seja comparado sem levar em conta caixa alta ou caixa baixa(para caracteres dentro da faixa ASCII).
+
+ +

Exemplos

+ + + +

CSS

+ +
a {
+  color: blue;
+}
+
+/* Links internos, começando com "#" */
+a[href^="#"] {
+  background-color: gold;
+}
+
+/* Links com "example" em qualquer lugar da URL */
+a[href*="example"] {
+  background-color: silver;
+}
+
+/* Links com "insensitive" em qualquer lugar da URL,
+   independentemente da capitalização */
+a[href*="insensitive" i] {
+  color: cyan;
+}
+
+/* Links com final ".org" */
+a[href$=".org"] {
+  color: red;
+}
+
+ +

HTML

+ +
<ul>
+  <li><a href="#internal">Internal link</a></li>
+  <li><a href="http://example.com">Example link</a></li>
+  <li><a href="#InSensitive">Insensitive internal link</a></li>
+  <li><a href="http://example.org">Example org link</a></li>
+</ul>
+ +

Resultado

+ +

{{EmbedLiveSample('Links')}}

+ +

Languages

+ +

CSS

+ +
/* Todas divs com um atributo `lang` em negrito. */
+div[lang] { font-weight: bold; }
+/* Todas divs com US English em azul (blue). */
+div[lang~="en-us"] { color: blue; }
+/* Todas divs onde Portuguese esta em verde (green). */
+div[lang="pt"] { color: green; }
+/* Todas divs onde Chinese esta em vermelho (red), Simplificado para (zh-CN) ou tradicional (zh-TW). */
+div[lang|="zh"] { color: red; }
+/* Todas divs com Traditional Chinese `data-lang` que é purple. */
+/* Nota: Você também poderia usar atributos separados por hífen com aspas duplas */
+div[data-lang="zh-TW"] { color: purple; }
+
+ +

 

+ +

HTML

+ +
<div lang="en-us en-gb en-au en-nz">Hello World!</div>
+<div lang="pt">Olá Mundo!</div>
+<div lang="zh-CN">世界您好!</div>
+<div lang="zh-TW">世界您好!</div>
+<div data-lang="zh-TW">?世界您好!</div>
+ +

Resultado

+ +

{{EmbedLiveSample('Languages')}}

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS4 Selectors', '#attribute-selectors', 'attribute selectors')}}{{Spec2('CSS4 Selectors')}}Adiciona um modificador para a seleção do valor do atributo ASCII 
{{SpecName('CSS3 Selectors', '#attribute-selectors', 'attribute selectors')}}{{Spec2('CSS3 Selectors')}} 
{{SpecName('CSS2.1', 'selector.html#attribute-selectors', 'attribute selectors')}}{{Spec2('CSS2.1')}}Definição Inicial
+ +

Browser compatibilidade

+ + + +

{{Compat("css.selectors.attribute")}}

diff --git a/files/pt-br/web/css/seletor_universal/index.html b/files/pt-br/web/css/seletor_universal/index.html new file mode 100644 index 0000000000..15e64a08ca --- /dev/null +++ b/files/pt-br/web/css/seletor_universal/index.html @@ -0,0 +1,105 @@ +--- +title: Seletor universal +slug: Web/CSS/Seletor_universal +tags: + - CSS + - Referências + - Seletores +translation_of: Web/CSS/Universal_selectors +--- +
{{CSSRef}}
+ +

O seletor universal do CSS (*) aplica estilos a elementos de qualquer tipo.

+ +
/* Seleciona todos os elementos */
+* {
+  color: green;
+}
+ +

A partir do CSS3, o asterisco pode ser combinado com {{cssxref("CSS_Namespaces", "namespaces")}}:

+ +
    +
  • ns|* - aplica a todos os elementos no namespace ns
  • +
  • *|* - aplica a todos elementos
  • +
  • |* - aplica a todos os elementos que não tem namespaces declarados
  • +
+ +

Sintaxe

+ +
* { propriedades de estilo }
+ +

O asterisco é opcional para seletores simples. Por exemplo, *.atencao e .atencao são equivalentes.

+ +

Exemplos

+ +

CSS

+ +
* [lang^=pt] {
+  color: green;
+}
+
+*.atencao {
+  color: red;
+}
+
+*#conteudoprincipal {
+  border: 1px solid blue;
+}
+
+.flutuando {
+  float: left
+}
+
+/* automaticamente aplica clear ao próximo irmão após o elemento com a classe .flutuando */
+.flutuando + * {
+  clear: left;
+}
+
+ +

HTML

+ +
<p class="atencao">
+  <span lang="pt-br">Um span verde</span> em um parágrafo vermelho.
+</p>
+<p id="conteudoprincipal" lang="pt-pt">
+  <span class="atencao">Um span vermelho</span> em um parágrafo verde.
+</p>
+ +

Resultado

+ +

{{EmbedLiveSample('Exemplos')}}

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('CSS4 Selectors', '#the-universal-selector', 'Seletor universal')}}{{Spec2('CSS4 Selectors')}}Sem mudanças
{{SpecName('CSS3 Selectors', '#universal-selector', 'Seletor universal')}}{{Spec2('CSS3 Selectors')}}Define o comportamente de acordo com os namespaces e adiciona uma sugestão de que é possivel omitir o seletor em pseudo-elementos
{{SpecName('CSS2.1', 'selector.html#universal-selector', 'Seletor universal')}}{{Spec2('CSS2.1')}}Definição inicial
+ +

Compatibilidade dos Browsers

+ + + +

{{Compat("css.selectors.universal")}}

diff --git a/files/pt-br/web/css/seletores_css/index.html b/files/pt-br/web/css/seletores_css/index.html new file mode 100644 index 0000000000..644d9d87e9 --- /dev/null +++ b/files/pt-br/web/css/seletores_css/index.html @@ -0,0 +1,150 @@ +--- +title: Seletores CSS +slug: Web/CSS/Seletores_CSS +tags: + - CSS + - Referência(2) + - Seletores + - Seletores CSS +translation_of: Web/CSS/CSS_Selectors +--- +
{{CSSRef}}
+ +

Os Seletores definem quais elementos um conjunto de regras CSS se aplica.

+ +

Seletores Básicos

+ +
+
Seletor por tag
+
Este seletor básico escolhe todos os elementos que correspondem ao nome fornecido.
+ Sintaxe: nome-da-tag
+ Exemplo: input corresponderá a qualquer elemento {{HTMLElement('input')}}.
+
Seletor por classe
+
Este seletor básico escolhe elementos baseados no valor de seu atributo classe. Sintaxe: .nome-da-classe
+ Examplo: .index irá corresponder a qualquer elemento que tenha o índice de classe (provavelmente definido por um atributo class="index", ou similar).
+
Seletor por ID
+
Este seletor básico escolhe nós baseados no valor do atributo id. Deve existir apenas um elemento com o mesmo ID no mesmo documento.
+ Sintaxe: #nome-do-id
+ Exemplo: #toc irá corresponder ao elemento que possuir o id=toc (definido por um atributo id="toc", ou similar).
+
Seletores universais
+
Este seletor básico irá escolher todos os nós. Ele também existe em um namespace único e em uma variante de todo o namespace também.
+ Sintaxe: * ns|* *|*
+ Exemplo: * irá corresponder a todos os elementos do documento.
+
Seletores por atributo
+
Este seletor básico ira escolher nós baseados no valor de um de seus atributos, ou até mesmo pelo próprio atributo.
+ Sintaxe: [atrib] [atrib=valor] [atrib~=valor] [atrib|=valor] [atrib^=valor] [atrib$=valor] [atrib*=valor]
+ Exemplo: [autoplay] irá corresponder a todos os elementos que possuirem o atributo autoplay (para qualquer valor).
+
+ +

Combinadores

+ +
+
Seletores de irmãos adjacentes
+
O combinador + seleciona os nós que seguem imediatamente o elemento especificado anteriormente.
+ Sintaxe: A + B
+ Exemplo: ul + li irá corresponder a qualquer elemento {{HTMLElement('li')}} que segue imediatamente após um elemento {{HTMLElement('ul')}}.
+
Seletores gerais de irmãos
+
O combinador ~ seleciona os nós que seguem (não necessariamente imediatamente) o elemento especificado anteriormente, se ambos os elementos compartilham o mesmo pai.
+ Sintaxe: A ~ B
+ Exemplo: p ~ span irá corresponder a todo elemento {{HTMLElement('span')}} que seguir um elemento {{HTMLElement('p')}} dentro de um mesmo elemento pai.
+
Seletor de filhos
+
O combinador > selecina nós que são filhos diretos do elemento especificado anteriormente.
+ Sintaxe: A > B
+ Exemplo: ul > li irá corresponder a todo elemento {{HTMLElement('li')}} que estiver diretamente dentro de um elemento {{HTMLElement('ul')}} especificado.
+
Seletor de descendentes
+
O combinador   seleciona os nós que são filhos do elemento especificado anteriormente (não é necessário que seja um filho direto).
+ Sintaxe: A B
+ Exemplo: div span irá corresponder a todo e qualquer elemento {{HTMLElement('span')}} que estiver dentro do elemento {{HTMLElement('div')}}.
+
+ +

Pseudo-classes

+ +

Pseudo-classes permitem selecionar elementos baseados em informações que não estão contidas na árvore de documentos como um estado ou que é particularmente complexa de extrair. Por exemplo, eles correspondem se um link foi visitado anteriormente ou não.

+ +

Pseudo-elementos

+ +

Pseudo-elementos são asbtrações da árvore que representam entidades além do que o HTML faz. Por exemplo, o HTML não tem um elemento que descreva a primeira letra ou linha de um parágrafo, ou o marcador de uma lista. Os pseudo-elementos representam essas entidades e permitem que as regras CSS sejam associadas a elas. Desta forma, essas entidades podem ser denominadas independentemente.

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('CSS4 Selectors')}}{{Spec2('CSS4 Selectors')}} 
{{SpecName('CSS3 Selectors')}}{{Spec2('CSS3 Selectors')}} 
{{SpecName('CSS2.1', 'selector.html')}}{{Spec2('CSS2.1')}} 
{{SpecName('CSS1')}}{{Spec2('CSS1')}}Definição inicial
+ +

Compatibilidade de navegadores

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
RecursoChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico1{{CompatGeckoDesktop("1")}}3.03.51.0
+
+ +
+ + + + + + + + + + + + + + + + + + + +
RecursoAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico1.5{{CompatGeckoMobile("1.9.2")}}{{CompatUnknown}}{{CompatUnknown}}3.2
+
diff --git a/files/pt-br/web/css/shorthand_properties/index.html b/files/pt-br/web/css/shorthand_properties/index.html new file mode 100644 index 0000000000..f993c40fc5 --- /dev/null +++ b/files/pt-br/web/css/shorthand_properties/index.html @@ -0,0 +1,140 @@ +--- +title: Propriedades shorthand +slug: Web/CSS/Shorthand_properties +translation_of: Web/CSS/Shorthand_properties +--- +

Definição

+ +

Propriedades shorthand (tradução literal: Propriedades abreviadas) são propriedades de CSS que deixam você setar os valores de outras propriedades de CSS simultaneamente. Usando shorthand property, um desenvolvedor web pode escrever folhas de estilo mais concisas e legíveis,economizando tempo e energia.

+ +

A especificação CSS define como shorthand properties, o grupo de propriedades com o mesmo tema. Ex: a propriedade CSS {{cssxref("background")}} é uma propriedade shorthand que é capaz de definir o valor de {{cssxref("background-color")}}, {{cssxref("background-image")}}, {{cssxref("background-repeat")}}, e {{cssxref("background-position")}}. Assim também,como as propriedades comuns e relacionadas a fonte podem ser definidas e usadas com o shorthand {{cssxref("font")}},e os diferentes margins em volta de um box podem ser definidas com o shorthand {{cssxref("margin")}}.

+ +

Casos específicos

+ +

Mesmo sendo convenientes para se usar, existem alguns casos que precisam ser analisados antes de usar:

+ +
    +
  1. Um valor que não especificado é setado seu valor inicial. Isso parece uma anedota, mas realmente significa que sobrescreve valores previamente setados. Por exemplo: +
    background-color: red;
    +background: url(images/bg.gif) no-repeat top right;
    +
    + não irá setar a cor do background para vermelho, mas para {{cssxref("background-color")}}'s padrão, transparente, como a segunda regra tem precedência.
  2. +
  3. Apenas propriedades individuais são herdadas. Como valores que faltam são substituidos pelo seu valor inicial, é impossivel herdar valores individuais os omitindo. O valor inherit pode ser aplicado a uma propriedade, mas num total e não como uma palavra-chave para um valor ou outro. Isso significa que a unica forma de um valor específico ser herdado é usando a propriedade em longhand com o valor inherit.
  4. +
  5. Propriedades shorthand tentam não forçar uma ordem específica para os valores das propriedades que elas substituem. Isso funciona bem quando essas propriedades usam valores de diferentes tipos, como a ordem não tem importância, isso funciona bem quando essas propriedades usam valores de diferentes tipos, como a ordem não tem importância, mas isso não funciona tão facilmente quando várias propriedades podem ter valores idênticos. O tratamento destes casos está agrupado em várias categorias: +
      +
    1. Propriedades shorthand que lidam com valores da borda de um box, como {{cssxref("border-style")}}, {{cssxref("margin")}} or {{cssxref("padding")}}, sempre usam um consistente 1-para-4 valor de sintaxe representando essas bordas: + + + + + + + + + + + + + + + + + + + +
      border1.pngA sintaxe de um valor: border-width: 1em — O valor único representa todas as bordas
      border2.pngAs sintaxes de dois valores: border-width: 1em 2em — O primeiro valor representa a vertical, isto é, as bordas superior e inferior, a segunda as horizontais, que é a esquerda e a direita.
      border3.pngAs sintaxes de três valores: border-width: 1em 2em 3em — O primeiro valor representa a borda superior, a segunda, a horizontal, que é esquerda e direita, e o terceiro valor a borda inferior
      border4.png +

      As sintaxes de  quatro valores:border-width: 1em 2em 3em 4em — Os quatro valores representam as margens superior, direita, inferior e esquerda, respectivamente, sempre nessa ordem, que é no sentido horário começando pelo topo (a letra inicial de  Top-Right-Bottom-Left corresponde à ordem da consoante da palavra trouble: TRBL)

      +
      +
    2. +
    3. Também parecido, shorthand que lidam com os cantos de um box {{cssxref("border-radius")}}, sempre usam 1-para-4-valor de sintaxe representando esses cantos: + + + + + + + + + + + + + + + + + + + +
      corner1.pngA sintaxe de um valor: border-radius: 1em — O valor único representa todos os cantos
      corner2.pngAs sintaxes de dois valores: border-radius: 1em 2em — O primeiro valor representa o canto superior esquerdo e inferior direito, o segundo o superior direito e inferior esquerdo
      corner3.pngAs sintaxes de três valores: border-radius: 1em 2em 3em — O primeiro valor representa o canto superior esquerdo, o segundo o canto superior direito eo inferior esquerdo e o terceiro o canto inferior direito
      corner4.png +

      As sintaxes de quatro valores: border-radius: 1em 2em 3em 4em — Os quatro valores representam os cantos superior esquerdo, superior direito, inferior direito e inferior esquerdo respectivamente, sempre nessa ordem, que é no sentido horário começando no canto superior esquerdo.

      +
      +
    4. +
    +
  6. +
+ +

Propriedades de background

+ +

Um background com as seguintes declarações:

+ +
background-color: #000;
+background-image: url(images/bg.gif);
+background-repeat: no-repeat;
+background-position: top right;
+ +

Pode ser resumido em uma unica declaração:

+ +
background: #000 url(images/bg.gif) no-repeat top right;
+ +

(A forma shorthand é o equivalente as propriedades longhand acima, mais background-attachment: scroll, em CSS3, algumas propriedades adicionais.)

+ +

Propriedades de fonte

+ +

As seguintes declarações:

+ +
font-style: italic;
+font-weight: bold;
+font-size: .8em;
+line-height: 1.2;
+font-family: Arial, sans-serif;
+ +

Podem ser resumidas a:

+ +
font: italic bold .8em/1.2 Arial, sans-serif;
+ +


+ Essa declaração shorthand é o equivalente as declarações longhand acima, mais font-variant: normal e font-size-adjust: none (CSS2.0 / CSS3), font-stretch: normal (CSS3).

+ +

Propriedades de borda

+ +

Com a borda, o width (largura), color (cor), podem ser simplificados em uma declaração. Por exemplo,

+ +
border-width: 1px;
+border-style: solid;
+border-color: #000;
+ +

Podem ser escritas como

+ +
border: 1px solid #000;
+ +

Propriedades de margin e padding

+ +

As versões shorthand de margin e padding funcionam da mesma maneira. As seguintes declarações CSS:

+ +
margin-top: 10px;
+margin-right: 5px;
+margin-bottom: 10px;
+margin-left: 5px;
+ +

são as mesmas da seguinte declaração (note que os valores estão em ordem horária: top, right, bottom e left(TRBL, mesmas consoantes de TRBL "trouble"))

+ +
margin: 10px 5px 10px 5px;
+ +

Veja também

+ +
    +
  • CSS Reference
  • +
  • {{css_key_concepts}}
  • +
  • Propriedades shorthand : {{cssxref("background")}}, {{cssxref("font")}}, {{cssxref("margin")}}, {{cssxref("border")}}, {{cssxref("border-top")}}, {{cssxref("border-right")}}, {{cssxref("border-bottom")}}, {{cssxref("border-left")}}, {{cssxref("border-width")}}, {{cssxref("border-color")}}, {{cssxref("border-style")}}, {{cssxref("transition")}}, {{cssxref("animation")}}, {{cssxref("transform")}}, {{cssxref("padding")}}, {{cssxref("list-style")}}, {{cssxref("border-radius")}}.
  • +
diff --git a/files/pt-br/web/css/sintaxe/index.html b/files/pt-br/web/css/sintaxe/index.html new file mode 100644 index 0000000000..4d6ff0bf1c --- /dev/null +++ b/files/pt-br/web/css/sintaxe/index.html @@ -0,0 +1,70 @@ +--- +title: Sintaxe +slug: Web/CSS/sintaxe +translation_of: Web/CSS/Syntax +--- +

O Objetivo básico da linguagem de folhas de estilo em cascata (CSS) é permitir que um motor do navegador pinte elementos na página com características específicas como cores, posições, ou decorações. A sintaxe CSS reflete estes objetivos e seus blocos de contrução básicos são:

+ +
    +
  • A propriedade é um identificador que possui um nome legível, que define o que será considerado ou editado;
  • +
  • O valor descreve como o recurso será tratado pelo motor. Cada propriedade possui um conjunto de valores válidos, definida por uma gramática formal, bem como um significado semântico, implementado para o motor do navegador.
  • +
+ +

Declarações do CSS

+ +

A definição de propriedades CSS para um valor específico é a função principal da linguagem CSS. A propriedade e valor são chamados de declaração, e qualquer motor do CSS calcula quais declarações serão aplicadas para todos um único elemento da página em ordem adequadamente, a fim de exibí-lo com o estilo correto.

+ +

Tanto as propriedades como os valores são case-sensitive no CSS. Os pares se separam por dois pontos, ':' (U+003A COLON), e espaços em branco antes, entre e depois de propriedades e valores, porém os espaços dentro da declaração são ignorados.

+ +

css syntax - declaration.png

+ +

Existem mais de 100 propriedades diferentes no CSS e um número quase infinito de diferentes valores. Nem todos os pares de propriedades e valores são permitidos em cada propriedade define o que são valores válidos. Quando um valor não é válido para uma determinada propriedade, a declaração é considerada inválida e é totalmente ignorada pelo motor do CSS.

+ +

Blocos de declaração CSS

+ +

Declarações são agrupadas em blocos, que estão delimitados na estrutura com uma chave de abertura, '{' (U+007B LEFT CURLY BRACKET), e fechadas com outra, '}' (U+007D RIGHT CURLY BRACKET). Os blocos as vezes podem estar aninhados, a abertura e fechamento de chaves no bloco CSS deve ser realizada.

+ +

css syntax - block.png

+ +

Esses blocos são chamados de blocos de declaração e as declarações dentro deles são separadas por, ';' (U+003B SEMICOLON). Um bloco de declaração pode não conter nenhuma declaração. Espaços em branco em volta das declarações não são consideradas. Não é necessário que a última declaração possua ponto e vírgula, apesar de ser considerada uma boa prática pois previne o esquecimento de acrescê-la quando for necessário aumentar o bloco.

+ +

css syntax - declarations block.png

+ +
O conteúdo de um bloco de declaração, que é uma lista separada por pontos e vírgulas, sem as chaves, pode ser posto dentro da tag HTML style.
+ +

Regras CSS

+ +

Se as folhas de estilo pudessem apenas aplicar uma declaração para cada elemento de uma página da web, eles seriam bem limitados. O principal objetivo é aplicar diferentes declarações a diferentes partes do documento.

+ +

O CSS associa as condições com os blocos de declaração. Cada bloco (válido) é precedido por um ou mais seletores, separados por vírgula, que são condições selecionando alguns elementos da página. O grupo de seletores é chamado de regra.css syntax - ruleset.png

+ +

Um elemento pode ser modificado por diversos seletores, e por isso por diversas regras que potencialmente podem conter diversas propriedades, com diferentes valores, o CSS padrão define aquele que possui a precedência e que será aplicado: esse é o tal algoritmo em cascata.

+ +
É importante perceber que quando uma regra é caracterizada por um grupo de seletores que são algum tipo de atalho com cada um sendo um simples seletor isso não se aplica a validade da regra por si só.
+
+Isso leva a uma importante consequência: se apenas um dos seletores for inválido, como usar uma pseudo-classe ou pseudo-elemento desconhecido, todo o seletor é inválido e por isso toda a regra é ignorada (invalidada também).
+ +

CSS statements

+ +

Rulesets are the main building blocks of a style sheet, which often consists of only a big list of them. But there is other information that a Web author wants to convey in the style sheet, like the character set, other external style sheets to import, font face or list counter descriptions and many more. It will use other and specific kinds of statements to do that.

+ +

A statement is a building block that begins with any non-space characters and ends at the first closing brace or semi-colon (outside a string, non-escaped and not included into another {}, () or [] pair).

+ +

css syntax - statements Venn diag.png

+ +

There are different kinds of statements:

+ +
    +
  • Rulesets (or rules) that, as seen, associate a collection of CSS declarations to a condition described by a selector.
  • +
  • At-rules that start with an at sign, '@' (U+0040 COMMERCIAL AT), followed by an identifier and then continuing up the end of the statement, that is up to the next semi-colon (;) outside of a block, or the end of the next block. Each type of at-rules, defined by the identifier, may have its own internal syntax, and semantics of course. They are used to convey meta-data information (like {{ cssxref("@charset") }} or {{ cssxref("@import") }}), conditional information (like {{ cssxref("@media") }} or {{ cssxref("@document") }}), or descriptive information (like {{ cssxref("@font-face") }}).
  • +
+ +

Any statement which isn't a rule or an at-rule is invalid and ignored.

+ +

There is another group of statements, the nested statements, these are statements that can be used in a specific subset of at-rules, the conditional group rules. These statements only apply if a specific condition is matched: the @media at-rule content is applied only if the device on which runs the browser matches the expressed condition; the @document at-rule content is applied only if the current page matches some conditions, and so on. In CSS1 and CSS2.1, only rulesets could be used inside a conditional group rules. That was very restrictive and this restriction was lifted in CSS Conditionals Level 3. Now, though it still is experimental and not support by every browser, a conditional group rules can contain a wider range of content, rulesets but also some, but not all, at-rules.

+ +

See also

+ +
    +
  • {{ CSS_key_concepts()}}
  • +
diff --git a/files/pt-br/web/css/sintexe_valor/index.html b/files/pt-br/web/css/sintexe_valor/index.html new file mode 100644 index 0000000000..d14bcaecdf --- /dev/null +++ b/files/pt-br/web/css/sintexe_valor/index.html @@ -0,0 +1,436 @@ +--- +title: Sintexe do valor +slug: Web/CSS/Sintexe_valor +tags: + - CSS + - Guía + - Iniciante + - Web +translation_of: Web/CSS/Value_definition_syntax +--- +
{{CSSRef}}
+ +

CSS value definition syntax, a formal grammar, is used for defining the set of valid values for a CSS property or function. In addition to this syntax, the set of valid values can be further restricted by semantic constraints (for example, for a number to be strictly positive).

+ +

The definition syntax describes which values are allowed and the interactions between them. A component can be a keyword, some characters considered as a literal, or a value of a given CSS data type or of another CSS property.

+ +

Tipos de componente

+ +

Keywords

+ +

Generic keywords

+ +

A keyword with a predefined meaning appears literally, without quotation marks. For example: auto, smaller or ease-in.

+ +

The specific case of inherit, initial and unset

+ +

All CSS properties accept the keywords inherit, initial and unset, that are defined throughout CSS. They are not shown in the value definition, and are implicitly defined.

+ +

Literals

+ +

In CSS, a few characters can appear on their own, like the slash ('/') or the comma (','), and are used in a property definition to separate its parts. The comma is often used to separate values in enumerations, or parameters in mathematical-like functions; the slash often separates parts of the value that are semantically different, but have a common syntax. Typically, the slash is used in shorthand properties; to separate component that are of the same type, but belong to different properties.

+ +

Both symbols appear literally in a value definition.

+ +

Data types

+ +

Basic data types

+ +

Some kind of data are used throughout CSS, and are defined once for all values in the specification. Called basic data types, they are represented with their name surrounded by the symbol '<' and '>': {{ cssxref("<angle>") }}, {{cssxref("<string>")}}, …

+ +

Non-terminal data types

+ +

Less common data types, called non-terminal data types, are also surrounded  by '<' and '>'.

+ +

Non-terminal data types are of two kinds:

+ +
    +
  • data types sharing the same name of a property, put between quotes. In this case, the data type shares the same set of values as the property. They are often used in the definition of shorthand properties.
  • +
  • data type not sharing the same name of a property. These data types are very close to the basic data types. They only differ from the basic data types in the physical location of their definition. In this case, the definition is usually physically very close to the definition of the property using them.
  • +
+ +

Component value combinators

+ +

Brackets

+ +

Brackets enclose several entities, combinators, and multipliers, then transform them as a single component. They are used to group components to bypass the precedence rules.

+ +
bold [ thin && <length> ]
+ +

This example matches the following values:

+ +
    +
  • bold thin 2vh
  • +
  • bold 0 thin
  • +
  • bold thin 3.5em
  • +
+ +

But not:

+ +
    +
  • thin bold 3em, as bold is juxtaposed with the component defined by the brackets, it must appear before it.
  • +
+ +

Juxtaposition

+ +

Placing several keywords, literals or data types, next to one another, only separated by one or several spaces, is called juxtaposition. All juxtaposed components are mandatory and should appear in the exact order.

+ +
bold <length> , thin
+
+ +

This example matches the following values:

+ +
    +
  • bold 1em, thin
  • +
  • bold 0, thin
  • +
  • bold 2.5cm, thin
  • +
  • bold 3vh, thin
  • +
+ +

But not:

+ +
    +
  • thin 1em, bold, as the entities must be in the expressed order
  • +
  • bold 1em thin, as the entities are mandatory; the comma, a literal, must be present
  • +
  • bold 0.5ms, thin, as the ms values are not {{cssxref("<length>")}}
  • +
+ +

Double ampersand

+ +

Separating two or more components, by a double ampersand, &&, means that all these entities are mandatory but may appear in any order.

+ +
bold && <length>
+
+ +

This example matches the following values:

+ +
    +
  • bold 1em
  • +
  • bold 0
  • +
  • 2.5cm bold
  • +
  • 3vh bold
  • +
+ +

But not:

+ +
    +
  • bold, as both components must appear in the value.
  • +
  • bold 1em bold, as both components must appear only one time.
  • +
+ +
Note: juxtaposition has precedence over the double ampersand, meaning that bold thin && <length> is equivalent to [ bold thin ] && <length>. It describes bold thin <length> or <length> bold thin but not bold <length> thin.
+ +

Double bar

+ +

Separating two or more components by a double bar, ||, means that all entities are options: at least one of them must be present, and they may appear in any order. Typically this is used to define the different values of a shorthand property.

+ +
<'border-width'> || <'border-style'> || <'border-color'>
+
+ +

This example matches the following values:

+ +
    +
  • 1em solid blue
  • +
  • blue 1em
  • +
  • solid 1px yellow
  • +
+ +

But not:

+ +
    +
  • blue yellow, as a component must appear at most one single time.
  • +
  • bold, as it isn't a keyword allowed as value of any of the entity.
  • +
+ +
Note: the double ampersand has precedence over the double bar, meaning that bold || thin && <length> is equivalent to bold || [ thin && <length> ]. It describes bold, thin <length>, bold thin <length>, or thin <length> bold but not <length> bold thin as bold, if not omitted, must be placed before or after the whole thin && <length> component.
+ +

Single bar

+ +

Separating two or more entities by a single bar, |, means that all entities are exclusive options: exactly one of these options must be present. This is typically used to separate a list of possible keywords.

+ +
<percentage> | <length> | left | center | right | top | bottom
+ +

This example matches the following values:

+ +
    +
  • 3%
  • +
  • 0
  • +
  • 3.5em
  • +
  • left
  • +
  • center
  • +
  • right
  • +
  • top
  • +
  • bottom
  • +
+ +

But not:

+ +
    +
  • center 3%, as only one of the components must be present.
  • +
  • 3em 4.5em, as a component must be present at most one time.
  • +
+ +
+

Note: the double bar has precedence over the single bar, meaning that bold | thin || <length> is equivalent to bold | [ thin || <length> ]. It describes bold, thin, <length>, <length> thin, or thin <length> but not bold <length> as only one entity from each side of the | combinator can be present.

+
+ +

Component value multipliers

+ +

A multiplier is a sign that indicate how many times a preceding entity can be repeated. Without a multiplier, an entity must appear exactly one time.

+ +

Note that multipliers cannot be added and have all precedence over combinators.

+ +

Asterisk (*)

+ +

The asterisk multiplier indicates that the entity may appear zero, one or several times.

+ +
bold smaller*
+ +

This example matches the following values:

+ +
    +
  • bold
  • +
  • bold smaller
  • +
  • bold smaller smaller
  • +
  • bold smaller smaller smaller, and so on.
  • +
+ +

But not:

+ +
    +
  • smaller, as bold is juxtaposed, and must appear before any smaller keyword.
  • +
+ +

Plus (+)

+ +

The plus multiplier indicates that the entity may appear one or several times.

+ +
bold smaller+
+ +

This example matches the following values:

+ +
    +
  • bold smaller
  • +
  • bold smaller smaller
  • +
  • bold smaller smaller smaller, and so on.
  • +
+ +

But not:

+ +
    +
  • bold, as smaller must appear at least one time.
  • +
  • smaller, as bold is juxtaposed and must appear before any smaller keyword.
  • +
+ +

Question mark (?)

+ +

The question mark multiplier indicates that the entity is optional, and must appear zero or one time.

+ +
bold smaller?
+ +

This example matches the following values:

+ +
    +
  • bold
  • +
  • bold smaller
  • +
+ +

But not:

+ +
    +
  • bold smaller smaller, as smaller must appear at most one time.
  • +
  • smaller, as bold is juxtaposed and must appear before any smaller keyword.
  • +
+ +

Curly braces ({ })

+ +

The curly braces multiplier, enclosing two integers separated by a comma, A and B, indicates that the entity must appear at least A times and at most B times.

+ +
bold smaller{1,3}
+ +

This example matches the following values:

+ +
    +
  • bold smaller
  • +
  • bold smaller smaller
  • +
  • bold smaller smaller smaller
  • +
+ +

But not:

+ +
    +
  • bold, as smaller must appear at least one time.
  • +
  • bold smaller smaller smaller smaller, as smaller must appear at most three times.
  • +
  • smaller, as bold is juxtaposed and must appear before any smaller keyword
  • +
+ +

Hash mark (#)

+ +

The hash mark multiplier indicates that the entity may be repeated one or more times (for example, the plus multiplier), but each occurrence is separated by a comma (',').

+ +
bold smaller#
+ +

This example matches the following values:

+ +
    +
  • bold smaller
  • +
  • bold smaller, smaller
  • +
  • bold smaller, smaller, smaller, and so on.
  • +
+ +

But not:

+ +
    +
  • bold, as smaller must appear at least one time.
  • +
  • bold smaller smaller smaller, as the different occurrence of smaller must be separated by commas.
  • +
  • smaller, as bold is juxtaposed and must appear before any smaller keyword.
  • +
+ +

Exclamation point (!)

+ +

The exclamation point multiplier after a group indicates that the group is required, and must produce at least one value; even if the grammar of the items within the group would otherwise allow the entire contents to be omitted, at least one component value must not be omitted.

+ +
[ bold? smaller? ]!
+
+ +

This example matches the following values:

+ +
    +
  • bold
  • +
  • smaller
  • +
  • bold smaller
  • +
+ +

But not:

+ +
    +
  • neither bold nor smaller, as one of them must appear.
  • +
  • smaller bold, as bold is juxtaposed and must appear before the smaller keyword.
  • +
  • bold smaller bold, as bold and smaller may only appear once.
  • +
+ +

Summary

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SignNameDescriptionExample
Combinators
 JuxtapositionComponents are mandatory and should appear in that ordersolid <length>
&&Double ampersandComponents are mandatory but may appear in any order<length> && <string>
||Double barAt least one of the components must be present, and they may appear in any order.<'border-image-outset'> || <'border-image-slice'>
|Single barExactly one of the components must be presentsmaller | small | normal | big | bigger
[ ]BracketsGroup components to bypass precedence rulesbold [ thin && <length> ]
Multipliers
 No multiplierExactly 1 timessolid
*Asterisk0 or more timesbold smaller*
+Plus sign1 or more timesbold smaller+
?Question mark0 or 1 time (that is optional)bold smaller?
{A,B}Curly bracesAt least A times, at most B timesbold smaller{1,3}
#Hash mark1 or more times, but each occurrence separated by a comma (',')bold smaller#
!Exclamation pointGroup must produce at least 1 value[ bold? smaller? ]!
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("CSS3 Values", "#value-defs", "Value definition syntax")}}{{Spec2("CSS3 Values")}}Adds the hash mark multiplier.
{{SpecName("CSS2.1", "about.html#value-defs", "Value definition syntax")}}{{Spec2("CSS2.1")}}Adds the double ampersand combinator.
{{SpecName("CSS1", "#notation-for-property-values", "Value definition syntax")}}{{Spec2("CSS1")}}Initial definition
+ +

See also

+ +
    +
  • {{CSS_key_concepts}}
  • +
diff --git a/files/pt-br/web/css/specificity/index.html b/files/pt-br/web/css/specificity/index.html new file mode 100644 index 0000000000..f79a337e9c --- /dev/null +++ b/files/pt-br/web/css/specificity/index.html @@ -0,0 +1,121 @@ +--- +title: Especificidade +slug: Web/CSS/Specificity +translation_of: Web/CSS/Specificity +--- +

O Conceito

+ +

A especificação é a maneira de como os navegadores definem quais valores de propriedades são os mais relevantes para o elemento a ser utilizado. A especificação é baseada apenas nas regras impostas na composição de diferentes tipos de seletores.

+ +

Como isso é calculado?

+ +

A espeficicação é calculada na concatenação da contagem de cada tipo de seletor. Não é um peso aplicado na expressão correspondente.

+ +

No caso de igualdade de especificação, a última declaração encontrada no CSS é aplicada ao elemento.

+ +
Note: O fato de elementos estarem próximos na árvore do documento não tem efeito sobre a especificação.
+ +

Ordem crescente de especificação

+ +

A seguinte lista de seletores está incluida na especificação:

+ +
    +
  • Seletores Universais
  • +
  • Tipo de Seletores
  • +
  • Classes seletoras
  • +
  • Atributos Seletores
  • +
  • Pseudo-classes
  • +
  • Seletores ID
  • +
  • Estilo Inline
  • +
+ +

A exceção !important

+ +

Quando a regra !important é utilizada na declaração do estilo substitui qualquer outra declaração feita no CSS, onde quer que esteja na lista de declaração. Contudo, !important não tem nada a ver com especificação. 

+ +

A exceção :not

+ +

A pseudo-classe de negação :not não é considerada uma pseudo-classe no cálculo de especificação. Contudo, seletores colocados na pseudo-class de negação são entendidos como seletores normais.

+ +

Aqui está um trecho de CSS:

+ +
div.outer p {
+  color:orange;
+}
+div:not(.outer) p {
+  color: lime;
+}
+
+ +

Usado com o seguindo código HTML:

+ +
<div class="outer">
+  <p>Esta é a div outer.</p>
+  <div class="inner">
+    <p>Este texto está na div inner.</p>
+  </div>
+</div>
+
+ +

Irá aparecer na tela assim:

+ +

Esta é a div outer.

+ +

Este texto está na div inner.

+ +

Especificação Form-based

+ +

A especificação é baseada na forma de um seletor. No seguinte caso, o seletor contém os atributos no algoritmo de determinação de especificação, embora ele selecione um ID.

+ +

A seguir veja as declarações de estilo:

+ +
* #foo {
+  color: green;
+}
+*[id="foo"] {
+  background: purple;
+}
+
+ +

Usado com esta marcação:

+ +
<p id="foo">Eu sou um simples texto.</p>
+
+ +

Vai acabar parecendo algo como:

+ +

Eu sou um simples texto.

+ +

Porque coincide com o mesmo elemento, mas o seletor de ID tem uma especificação superior.

+ +

Estrutura aproximada

+ +

A seguir a declaração do estilo:

+ +
body h1 {
+  color: green;
+}
+html h1 {
+  color: purple;
+}
+
+ +

Com o HTML seguinte::

+ +
<html>
+<body>
+  <h1>Aqui está o título!</h1>
+</body>
+</html>
+
+ +

Vamos ter algo como:

+ +

Aqui está o título!

+ +

Veja Também

+ + diff --git a/files/pt-br/web/css/text-align/index.html b/files/pt-br/web/css/text-align/index.html new file mode 100644 index 0000000000..9789af412c --- /dev/null +++ b/files/pt-br/web/css/text-align/index.html @@ -0,0 +1,337 @@ +--- +title: text-align +slug: Web/CSS/text-align +tags: + - CSS + - Propriedade CSS + - Referencia + - Texto CSS +translation_of: Web/CSS/text-align +--- +

{{CSSRef}}

+ +

Sumário

+ +

A propriedade CSS text-align descreve como conteúdo inline, como texto, é alinhado no elemento pai em bloco. text-align não controla o alinhamento de elementos em bloco, apenas o seu conteúdo inline.

+ +

{{cssinfo}}

+ +

Sintaxe

+ +
/* Keyword values */
+text-align: left;
+text-align: right;
+text-align: center;
+text-align: justify;
+text-align: justify-all;
+text-align: start;
+text-align: end;
+text-align: match-parent;
+
+/* Block alignment values (Non-standard syntax) */
+text-align: -moz-center;
+text-align: -webkit-center;
+
+/* Global values */
+text-align: inherit;
+text-align: initial;
+text-align: unset;
+
+ +

Valores

+ +
+
start {{experimental_inline}}
+
Igual left se a direção é esquerda-para-direita e right se a direção é direita-para-esquerda.
+
end {{experimental_inline}}
+
Igual right se a direção é esquerda-para-direita e left se a direção é direita-para-esquerda.
+
left
+
O conteúdo é alinhado na borda esquerda do box.
+
right
+
O conteúdo é alinhado na borda direita do box.
+
center
+
Os conteúdos inline são centralizados entre a linha da caixa.
+
justify
+
Os conteúdos inline são justificados. Text should be spaced to line up its left and right edges to the left and right edges of the line box, except for the last line.
+
justify-all
+
Semelhante a justify, porém força a última linha a ser justificada.
+
match-parent {{experimental_inline}}
+
Similar to inherit, but the values start and end are calculated according the parent's {{cssxref("direction")}} and are replaced by the adequate left or right value.
+
+ +

Sintaxe Formal

+ +
{{csssyntax}}
+ +

Exemplos

+ +

Alinhamento Esquerdo

+ +

HTML

+ +
<p class="example">
+  Integer elementum massa at nulla placerat varius.
+  Suspendisse in libero risus, in interdum massa.
+  Vestibulum ac leo vitae metus faucibus gravida ac in neque.
+  Nullam est eros, suscipit sed dictum quis, accumsan a ligula.
+</p>
+ +

CSS

+ +
.example {
+  text-align: left;
+  border: solid;
+}
+ +

Resultado

+ +

{{EmbedLiveSample("Left_alignment","100%","100%")}}

+ +

Texto centralizado

+ +

HTML

+ +
<p class="example">
+  Integer elementum massa at nulla placerat varius.
+  Suspendisse in libero risus, in interdum massa.
+  Vestibulum ac leo vitae metus faucibus gravida ac in neque.
+  Nullam est eros, suscipit sed dictum quis, accumsan a ligula.
+</p>
+ +

CSS

+ +
.example {
+  text-align: center;
+  border: solid;
+}
+ +

Resultado

+ +

{{EmbedLiveSample("Centered_text","100%","100%")}}

+ +

Justificado

+ +

HTML

+ +
<p class="example">
+  Integer elementum massa at nulla placerat varius.
+  Suspendisse in libero risus, in interdum massa.
+  Vestibulum ac leo vitae metus faucibus gravida ac in neque.
+  Nullam est eros, suscipit sed dictum quis, accumsan a ligula.
+</p>
+ +

CSS

+ +
.example {
+  text-align: justify;
+  border: solid;
+}
+ +

Resultado

+ +

{{EmbedLiveSample("Justify","100%","100%")}}

+ +

Notas

+ +

O modo compátivel-padrão de centralizar um bloco em si sem centralizar seu conteúdo inline é setando a {{cssxref("margin")}} left e right para auto, e.g.:

+ +
.something {
+  margin: auto;
+}
+
+ +
.something {
+  margin: 0 auto;
+}
+
+ +
.something {
+  margin-left: auto;
+  margin-right: auto;
+}
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('CSS Logical Properties', '#text-align', 'text-align')}}{{Spec2('CSS Logical Properties')}}Sem mudanças
{{SpecName('CSS3 Text', '#text-align-property', 'text-align')}}{{Spec2('CSS3 Text')}}Added the start, end, and match-parent values. Changed the unnamed initial value to start (which it was).
{{SpecName('CSS2.1', 'text.html#alignment-prop', 'text-align')}}{{Spec2('CSS2.1')}}Sem mudanças
{{SpecName('CSS1', '#text-align', 'text-align')}}{{Spec2('CSS1')}}Definição iniciaç
+ +

Browser compatibilidade

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico (left, right, center and justify)1.0{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.0")}}3.03.51.0 (85)
Block alignment values {{non-standard_inline}}1.0{{property_prefix("-webkit")}}{{CompatUnknown}}{{CompatGeckoDesktop("1.0")}}{{property_prefix("-moz")}}[1]{{CompatNo}}{{CompatNo}}1.0 (85){{property_prefix("-khtml")}}
+ 1.3 (312){{property_prefix("-webkit")}} [1]
start {{experimental_inline}}1.0{{CompatUnknown}}{{CompatGeckoDesktop("1.0")}}{{CompatNo}}{{CompatVersionUnknown}}3.1 (525)
end {{experimental_inline}}1.0{{CompatUnknown}}{{CompatGeckoDesktop("1.9.2")}}{{CompatNo}}{{CompatVersionUnknown}}3.1 (525)
match-parent{{experimental_inline}}16{{CompatUnknown}}{{CompatGeckoDesktop("40")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Block alignment values {{non-standard_inline}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
start {{experimental_inline}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
end {{experimental_inline}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
match-parent{{experimental_inline}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("40")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
true(non-standard syntax){{non-standard_inline}}{{CompatNo}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] Both WebKit and Gecko support a prefixed version of left, center, and right, that applies not only to inline content but also to block elements. This is used to implement the legacy {{htmlattrxref("align", "td")}} attributes on table elements and <center>. Do not use these on production Web sites.

+ +

Veja também

+ +
    +
  • {{Cssxref("margin","margin:auto")}}, {{Cssxref("margin-left","margin-left:auto")}}, {{Cssxref("vertical-align")}}
  • +
diff --git a/files/pt-br/web/css/text-decoration-style/index.html b/files/pt-br/web/css/text-decoration-style/index.html new file mode 100644 index 0000000000..9ec4f673a5 --- /dev/null +++ b/files/pt-br/web/css/text-decoration-style/index.html @@ -0,0 +1,197 @@ +--- +title: text-decoration-style +slug: Web/CSS/text-decoration-style +translation_of: Web/CSS/text-decoration-style +--- +
{{CSSRef}}
+ +

Resumo

+ +

A propriedade CSS text-decoration-style CSS define o estilo das linhas especificadas por {{cssxref ("text-decoration-line")}}. O modelo aplica-se a todas as linhas, não há nenhuma forma de definir estilos diferentes para cada uma das linhas utilizando text-decoration-line.
+
+ Se a decoração especificada tem um significado semântico específico, como uma linha de line-through o que significa que um texto tenha sido excluído, autores são encorajados a denotar este significado usando uma tag HTML, como {{ HTMLElement("del") }} ou {{ HTMLElement("s") }}. Como os navegadores podem ser deficientes em alguns casos, o significado semântico não vai desaparecer em tal situação.

+ +

{{cssinfo}}

+ +

Syntax

+ +
/* Keyword values */
+text-decoration-style: solid;
+text-decoration-style: double;
+text-decoration-style: dotted;
+text-decoration-style: dashed;
+text-decoration-style: wavy;
+
+/* Global values */
+text-decoration-style: inherit;
+text-decoration-style: initial;
+text-decoration-style: unset;
+
+ +

Valores

+ +
+
solid double dotted dashed wavy
+
É uma das seguintes palavras-chave: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
KeywordDescriptionComment
solidDraws a single line 
doubleDraws a double line 
dottedDraws a dotted line 
dashedDraws a dashed line 
wavyDraws a wavy line 
-moz-none{{ non-standard_inline }} Do not draw a lineDo not use : use {{ cssxref("text-decoration-line") }}: none instead
+
+
inherit
+
É uma palavra-chave indicando a reutilizar o valor calculado sobre o elemento pai.
+
+ +

Syntax Formal

+ +
{{csssyntax}}
+ +

Exemplo

+ + + +
.example {
+    text-decoration-line: underline;
+    text-decoration-style: wavy;
+    text-decoration-color: red;
+}
+
+ +
<p class="example">This is how it looks.</p>
+
+ +

{{ EmbedLiveSample('Examples', '', '', '') }}

+ +

Especificações

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSS3 Text Decoration', '#text-decoration-style', 'text-decoration-style') }}{{ Spec2('CSS3 Text Decoration') }}Initial definition. The {{cssxref("text-decoration")}} property wasn't a shorthand before.
+ +

Browser compatíveis

+ +

{{ CompatibilityTable }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Basic support{{ CompatGeckoDesktop("6.0") }} - {{CompatGeckoDesktop("39.0")}}{{ property_prefix("-moz") }}
+ {{ CompatGeckoDesktop("36.0") }}
{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
wavy{{ CompatGeckoDesktop("6.0") }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatNo }}{{ CompatNo }}{{ CompatGeckoMobile("6.0") }}- {{CompatGeckoMobile("39.0")}}{{ property_prefix("-moz") }}
+ {{ CompatGeckoMobile("36.0") }}
{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
wavy{{ CompatNo }}{{ CompatNo }}{{ CompatGeckoMobile("6.0") }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
+
diff --git a/files/pt-br/web/css/text-decoration/index.html b/files/pt-br/web/css/text-decoration/index.html new file mode 100644 index 0000000000..6c4aaa93ad --- /dev/null +++ b/files/pt-br/web/css/text-decoration/index.html @@ -0,0 +1,205 @@ +--- +title: text-decoration +slug: Web/CSS/text-decoration +tags: + - CSS + - PrecisaDeCompatibilidade + - Propriedade CSS + - Referencia + - Texto CSS +translation_of: Web/CSS/text-decoration +--- +

{{CSSRef}}

+ +

Resumo

+ +

A propriedade text-decoration do CSS é usada para definir a formatação de  underline, overline, line-through ou blink. As decorações underline e overline são posicionadas abaixo e acima do texto (respectivamente), e line-through cortando-o.

+ +

A propriedade text-decoration desenha em elementos descendentes. Isso significa que não é possivel desabilitar em um descendente uma decoração que foi especificada em um de seus antecessores. Por exemplo, no markup <p>Esse texto tem <em>alguns elementos enfatizados</em> nele.</p>, a regra de estilo p { text-decoration: underline; } faria com que todo o parágrafo fosse sublinhado. A regra em { text-decoration: none; } não causaria qualquer mudanca; o parágrafo inteiro ainda estaria sublinhado. Entretanto, a regra em { text-decoration: overline; } iria decorar o trecho "alguns elementos enfatizados".

+ +
+

Nota: CSS 3 transformou a propriedade Text-Decoration para forma reduzida, usando as seguintes propriedades: {{cssxref("text-decoration-color")}}, {{cssxref("text-decoration-line")}}, e {{cssxref("text-decoration-style")}}. Como em outras propriedades reduzidas, isso significa que ele reseta o valor de cada uma para padrão se não for explicitamente especificada na forma reduzida.

+
+ +

{{cssinfo}}

+ +

Sintaxe

+ +
/* Valores Chave */
+text-decoration: none;                 /* Sem decoração */
+text-decoration: underline red;        /* Sublinhado vermelho */
+text-decoration: underline wavy red;   /* Sublinhado ondulado vermelho */
+
+/* Valores Globais */
+text-decoration: inherit;
+text-decoration: initial;
+text-decoration: unset;
+
+ +

Valores

+ +

A propriedade text-decoration é escrita de forma reduzida e pode usar os valores de cada uma das propriedades: {{cssxref("text-decoration-line")}}, {{cssxref("text-decoration-color")}}, e {{cssxref("text-decoration-style")}}

+ +

Sintaxe Formal

+ +
{{csssyntax}}
+ +

Exemplos

+ +
h1.under {
+    text-decoration: underline;
+}
+h1.over {
+    text-decoration: overline;
+}
+p.line {
+    text-decoration: line-through;
+}
+p.blink {
+    text-decoration: blink;
+}
+a.none {
+    text-decoration: none;
+}
+p.underover {
+    text-decoration: underline overline;
+}
+
+ + + +

{{EmbedLiveSample('Examples','100%','310')}}

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentários
{{SpecName('CSS3 Text Decoration', '#text-decoration-property', 'text-decoration')}}{{Spec2('CSS3 Text Decoration')}}Transformado em uma propriedade reduzida. Adicionado suporte para o valor {{cssxref('text-decoration-style')}}.
{{SpecName('CSS2.1', 'text.html#lining-striking-props', 'text-decoration')}}{{Spec2('CSS2.1')}}Sem mudanças significantes.
{{SpecName('CSS1', '#text-decoration', 'text-decoration')}}{{Spec2('CSS1')}}Definição inicial.
+ +

Compatibilidade de Browser

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Suporte básico{{CompatGeckoDesktop("1.0")}}1.03.03.51.0
Valor blink{{CompatGeckoDesktop("1.0")}}
+ {{CompatGeckoDesktop("23.0")}}[1]
{{CompatVersionUnknown}}[1]{{CompatVersionUnknown}}[1]4.0
+ 15.0[1]
{{CompatVersionUnknown}}[1]
Propriedade reduzida{{CompatGeckoDesktop("6.0")}}[3]
+ {{CompatGeckoDesktop("36.0")}}
{{CompatNo}}{{CompatNo}}{{CompatNo}}7.1[2]
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureFirefox Mobile (Gecko)AndroidIE PhoneOpera MobileSafari Mobile
Suporte básico{{CompatGeckoMobile("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Valor blink{{CompatGeckoDesktop("1.0")}}
+ {{CompatGeckoDesktop("23.0")}}[1]
{{CompatVersionUnknown}}[1]{{CompatVersionUnknown}}[1]4.0[1]{{CompatVersionUnknown}}[1]
Propriedade reduzida{{CompatGeckoMobile("6.0")}}[3]
+ {{CompatGeckoMobile("36.0")}}
{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}8[1]
+
+ +

[1] O valor blink não tem nenhum efeito.

+ +

[2] Safari não suporta {{cssxref("text-decoration-style")}}.

+ +

[3] Essa versão do Gecko tem implementação parcial.

+ +

Veja também

+ +
    +
  • O atributo {{cssxref("list-style")}} controla a aparência dos itens em listas {{HTMLElement("ol")}} e {{HTMLElement("ul")}} no HTML.
  • +
diff --git a/files/pt-br/web/css/text-overflow/index.html b/files/pt-br/web/css/text-overflow/index.html new file mode 100644 index 0000000000..e2bfb7d6d7 --- /dev/null +++ b/files/pt-br/web/css/text-overflow/index.html @@ -0,0 +1,374 @@ +--- +title: text-overflow +slug: Web/CSS/text-overflow +translation_of: Web/CSS/text-overflow +--- +

{{ CSSRef() }}

+ +

Sumário

+ +

A propriedade text-overflow do CSS determina como o conteúdo que ultrapassou a sua div e que não é mostrado ao usuário deve ser exibido. Ele pode ser cortado, mostrar reticências ou até mesmo exibir qualquer string definida pelo autor.

+ +

text-overflow.png

+ +

O corte acontece na borda da caixa; para cortar no limite de caracteres de uma string personalizada, pode-se usar ('').

+ +

Essa propriedade afeta apenas o conteúdo que está ultrapassando o bloco ou a div no sentido da linha horizontal (não corta o texto na parte de baixo de um bloco ou div, por exemplo). O texto pode ultrapassar ou transbordar quando utilizado white-space:nowrap’ ou quando uma palavra for muito grande.

+ +

Essa propriedade do CSS não força um estouro para que ele ocorra. Para que isso aconteça, é necessário que o autor utilize algumas propriedades adicionais no elemento, como setar a propriedade overflow para hidden.

+ +

{{cssinfo}}

+ +

Syntaxe

+ +
Formal syntax: {{csssyntax("text-overflow")}}
+ +
/* One-value syntax: the value describe the overflow performed at the end of the line (right end if ltr, left end if rtl) */
+text-overflow: clip
+text-overflow: ellipsis
+text-overflow: "…"
+
+/* Two-value syntax: the first value describes the overflow at the left end of the line,
+                     the second at the right end. Directionality has no influence */
+
+text-overflow: clip ellipsis
+text-overflow: "…" "…"
+
+text-overflow: inherit
+ +

Values

+ +
+
clip
+
This keyword value indicates to truncate the text at the limit of the content area, therefore the truncation can happen in the middle of a character. To truncate at the transition between two characters, the empty string value ('') must be used. The value clip is the default for this property.
+
ellipsis
+
This keyword value indicates to display ellipses ('…', U+2026 Horizontal Ellipsis) to represent clipped text. The ellipsis is displayed inside the content area, shortening more the size of the displayed text. If there is not enough place to display ellipsis, they are clipped.
+
<string> {{ experimental_inline() }}
+
The {{cssxref("<string>")}} to be used to represent clipped text. The string is displayed inside the content area, shortening more the size of the displayed text. If there is not enough place to display the string itself, it is clipped.
+
+ +

Examples

+ +
p {
+  white-space: nowrap;
+  width: 100%;
+  overflow: hidden;              /* "overflow" value must be different from "visible" */
+
+  text-overflow:    ellipsis;
+}
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CSS valuedirection: ltrdirection: rtl
Expected ResultLive resultExpected ResultLive result
visible overflow1234567890 +
1234567890
+
0987654321 +
1234567890
+
text-overflow: clipt-o_clip.png +
123456
+
t-o_clip_rtl.png +
1234567890
+
text-overflow: ''12345 +
123456
+
54321 +
1234567890
+
text-overflow: ellipsis1234… +
1234567890
+
…4321 +
1234567890
+
text-overflow: '.'1234. +
1234567890
+
.4321 +
1234567890
+
text-overflow: clip clip123456 +
1234567890
+
654321 +
1234567890
+
text-overflow: clip ellipsis1234… +
1234567890
+
6543… +
1234567890
+
text-overflow: clip '.'1234. +
1234567890
+
6543. +
1234567890
+
text-overflow: ellipsis clip…3456 +
1234567890
+
…4321 +
1234567890
+
text-overflow: ellipsis ellipsis…34… +
1234567890
+
…43… +
1234567890
+
text-overflow: ellipsis '.'…34. +
1234567890
+
…43. +
1234567890
+
text-overflow: ',' clip,3456 +
1234567890
+
,4321 +
1234567890
+
text-overflow: ',' ellipsis,34… +
1234567890
+
,43… +
1234567890
+
text-overflow: ',' '.',34. +
1234567890
+
,53. +
1234567890
+
+ +


+ Using the abbr tag of HTML5 along with text-overflow

+ +

We have the example of the use of abbr tag inside a div with width 250px;

+ +
div {
+    width: 250px;
+    display: inline-block;
+    white-space: nowrap;
+    overflow: hidden;
+    text-overflow: ellipsis;
+    direction: ltr;
+}
+ +
<div>
+    <abbr title="https://developer.mozilla.org/pt-BR/docs/Web/CSS/text-overflow">https://developer.mozilla.org/pt-BR/docs/Web/CSS/text-overflow</abbr>
+</div>
+ +

The full path of the URL will be displayed over the mouse, and the screen will be printed as follows: https://developer.mozilla.org/pt-BR/...

+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSS3 UI', '#text-overflow', 'text-overflow') }}{{ Spec2('CSS3 UI') }} 
+ +

A previous version of this interface reached the Candidate Recommendation status. As some not-listed-at-risk features needed to be removed, the spec was demoted to the Working Draft level, explaining why browsers implemented this property unprefixed, though not at the CR state.

+ +

Browser compatibility

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support1.0 (312.3){{ CompatGeckoDesktop("7.0") }} ({{ anch("Gecko notes", "See notes") }})6.0 ({{ anch("Internet Explorer notes", "See notes") }})9{{ property_prefix("-o") }} ({{ anch("Opera notes", "See notes") }})
+ 11.0
1.3 (312.3)
Two-value syntax {{ experimental_inline() }}{{ CompatNo() }}{{ CompatGeckoDesktop("9.0") }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
String value{{ experimental_inline() }}{{ CompatNo() }}{{ CompatGeckoDesktop("9.0") }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{ CompatVersionUnknown() }}{{ CompatGeckoMobile("7.0") }}{{ CompatUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
Two-value syntax {{ experimental_inline() }}{{ CompatNo() }}{{ CompatGeckoMobile("9.0") }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
String value {{ experimental_inline() }}{{ CompatNo() }}{{ CompatGeckoMobile("9.0") }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +

Gecko notes

+ +

Starting in Gecko 10.0 {{ geckoRelease("10.0") }}, handling of text-overflow on blocks with inline overflow on both horizontal sides has been corrected; previously, if you specified only one value (such as text-overflow:ellipsis;), ellipsing was happening on both sides instead of just the end edge based on the block's text direction.

+ +

Internet Explorer notes

+ +

Internet Explorer 8 introduced the prefixed version, -ms-text-overflow, synonymous with text-overflow. Do not use this prefixed version.

+ +

Opera notes

+ +

Opera 9 and 10 require the prefixed version, -o-text-overflow.

+ +

See also

+ +
    +
  • CSS Reference index
  • +
  • Related CSS properties: {{ cssxref("overflow") }}, {{ cssxref("white-space") }}
  • +
diff --git a/files/pt-br/web/css/text-rendering/index.html b/files/pt-br/web/css/text-rendering/index.html new file mode 100644 index 0000000000..8bb1230959 --- /dev/null +++ b/files/pt-br/web/css/text-rendering/index.html @@ -0,0 +1,189 @@ +--- +title: text-rendering +slug: Web/CSS/text-rendering +translation_of: Web/CSS/text-rendering +--- +

{{ CSSRef() }}

+ +

Sumário

+ +

A propriedade CSS text-rendering provê informações para o mecanismo de renderização sobre o que otimizar no momento em que ele renderiza texto. O navegador faz escolhas entre velocidade, legibilidade e precisão geométrica. A propriedade text-rendering é uma propriedade SVG que não é definida em nenhum padrão CSS. Porém, navegadores Gecko e WebKit permitem o uso da propriedade em conteúdos HTML e XML nas plataformas Windows, Mac OS X e Linux. 

+ +

Um efeito bastante visível é o optimizeLegibility, que habilita ligaduras (ff, fi, fl etc.) para algumas fontes com o texto menores que 20px como, por exemplo, fontes da Microsoft (Calibri, Candara, Constantia e Corbel ou a família de fontes DejaVu).

+ +

{{cssinfo}}

+ +

Syntax

+ +
text-rendering:  auto | optimizeSpeed | optimizeLegibility | geometricPrecision | inherit
+ +

Valores

+ +
+
auto
+
O navegador faz sugestões de quando otimizar velocidade, legibilidade e precisão geométrica enquando formata o texto. Para diferenças em como esse valor é interpretado pelo navegador, veja a tabela de compatibilidades.
+
optimizeSpeed
+
O navegador prioriza a velocidade de renderização sobre a legibilidade e precisão geométrica no momento de rederização do texto. Essa opção desabilita o kerning1 e ligatures2.
+
optimizeLegibility
+
O navegador prioriza legibilidade sobre a velocidade de renderização e precisão geométrica. Essa propriedade habilita o kerning e ligatures opcionais.
+
geometricPrecision
+
+

O browser prioriza a precisão geométrica sobre a velocidade de renderização e legibilidade. Alguns aspectos de fontes - tais como kerning - não se escala linearmente e, dessa forma, geometricPrecision pode tornar essas fontes visualmente boas.

+ +

Em SVG, quando o texto é escalado para cima ou para baixo, os navegadores calculam o tamanho final do texto (que é o tamanho de fonte específicado e a escala aplicada) e requer uma fonte de tamanho computado à partir das fontes do sistema. Mas se você requer um tamanho de fonte de, digamos, 9 com a escala de 140%, o resultado do tamanho da fonte de 12.6 não explicitamente existe no sistema, então o browser ira arredondar o tamanho da fonte para 12.

+ +

Mas a propriedade geometricPrecision - quando totalmente surpotada pelo mecanismo de renderização - deixa você escalar seu texto fluidamente. Para fatores de larga escala, você pode ver uma renderização de texto não tão bonita, mas com o tamanho esperado - nem arredondado para cima ou para baixo para o mais próximo tamanho suportado pelo sistema Windows ou Linux.

+ +

Navegadores WebKit precisamente aplicam o valor específico, mas os navegadores Gecko tratam o esse valor como optimizeLegibility.

+
+
+ +

Exemplos

+ +
/* make sure all fonts in the HTML document display in all its glory,
+   but avoid inadequate ligatures in class foo elements */
+
+body  { text-rendering: optimizeLegibility; }
+.foo  { text-rendering: optimizeSpeed; }
+ +

Live Example

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CSS codeKerningLigatures
font: 19.9px 'DejaVu Serif',Constantia;LYoWATff fi fl ffl
font: 20px 'DejaVu Serif',Constantia;LYoWATff fi fl ffl
font: 3em 'DejaVu Serif',Constantia;
+ text-rendering: optimizeSpeed;
LYoWATff fi fl ffl
font: 3em 'Dejavu Serif',Constantia;
+ text-rendering: optimizeLegibility;
LYoWATff fi fl ffl
+ +

Gecko Notes

+ +

O valor padrão de 20px para auto pode ser alterado na propriedade browser.display.auto_quality_min_font_size do navegador.

+ +

A opção optimizeSpeed não tem efeito na versão 2.0 do Gecko {{ geckoRelease("2.0") }}, devido ao código padrão de renderização de texto que já é muito rápido e não existe até o momento um código mais rápido para esse trabalho. Veja detalhes em {{ bug(595688) }}.

+ +

Especificações

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('SVG1.1', 'painting.html#TextRenderingProperty', 'text-rendering') }}{{ Spec2('SVG1.1') }} 
+ +

Essa é uma especificação SVG, e não é definida em nenhum padrão CSS. Gecko (Firefox) e WebKit aplicam a propriedade text-rendering para códigos HTML e XML.

+ +

Compatibilidade entre Navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Suporte basico para plataformas Windows e Linux +

4.0 but the implementation known bugs on Windows and Linux which can break font substitition, small-caps, letter-spacing or cause text to overlap

+
3.0 (1.9){{ CompatNo() }}{{ CompatNo() }}5.0 (532.5)
Surpote basico para outros sistemas operacionais{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
autoChrome treats this as optimizeSpeed.
+ Work is continuing on{{ Webkitbug("41363") }}
+

Se o tamanho da fonte for maior ou igual a 20px, navegadores Gecko usam o valor optimizeLegibility. Para fontes de tamanho menores que 20px, Gecko usa optimizeSpeed.

+
{{ CompatNo() }}{{ CompatNo() }}Safari treats this as optimizeSpeed.
+ Work is continuing on{{ Webkitbug("41363") }}
geometricPrecision13 supports true geometric precision, without rounding up or down to the nearest supported font size in the operating system.
+ Introduced in WebKit 535.1   {{ Webkitbug("60317") }}
Gecko trata esse valor da mesma forma que trata o valor optimizeLegibility. {{ CompatNo() }} {{ CompatNo() }} 
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
diff --git a/files/pt-br/web/css/text-shadow/index.html b/files/pt-br/web/css/text-shadow/index.html new file mode 100644 index 0000000000..6f22e7e329 --- /dev/null +++ b/files/pt-br/web/css/text-shadow/index.html @@ -0,0 +1,193 @@ +--- +title: text-shadow +slug: Web/CSS/text-shadow +translation_of: Web/CSS/text-shadow +--- +
{{ Cssref }}
+ +

Sumário

+ +

A propriedade text-shadow acrescenta sombras ao texto. Ela aceita uma lista de sombras separadas por vírgula que serão aplicados ao texto e ao {{ cssxref("text-decoration","text-decorations") }} do elemento.

+ +

Cada sombra é especificada como um deslocamento do texto, juntamente com valores opcionais de cor e raio de desfoque.

+ +

Multiplas sombras são aplicadas de frente-para-trás, com a primeira sombra especificada no topo.

+ +

Esta propriedade se aplica a ambos {{cssxref("::first-line")}} e {{cssxref("::first-letter")}} pseudo-elements.

+ +

{{cssinfo}}

+ +

Sintaxe

+ +
/* deslocamento-x | deslocamento-y | raio-de-desfoque | cor */
+text-shadow: 1px 1px 2px black;
+
+/* cor | deslocamento-x | deslocamento-y | raio-de-desfoque */
+text-shadow: #CCC 1px 0 10px;
+
+/* deslocamento-x | deslogamento-y | cor */
+text-shadow: 5px 5px #558ABB;
+
+/* cor | deslocamento-x | deslocamento-y */
+text-shadow: white 2px 5px;
+
+/* deslocamento-x | deslocamento-y
+/* Usa o padrão para cor e raio-de-desfoque */
+text-shadow: 5px 10px;
+
+/* Valores globais */
+text-shadow: inherit;
+text-shadow: initial;
+text-shadow: unset;
+
+ +

Valores

+ +
+
<cor>
+
Opcional. Pode ser especificado tanto antes quanto depois dos valores de deslocamento. Se a cor não é especificada, uma cor UA-chosen será usada.  {{ note("Se voce quer garantir a consistência entre os navegadores, especifique explicitamente uma cor.") }}
+
<offset-x> <offset-y>
+
Obrigatório. These <length> values specify the shadow's offset from the text. <offset-x> specifies the horizontal distance; a negative value places the shadow to the left of the text. <offset-y> specifies the vertical distance; a negative value places the shadow above the text. If both values are 0, then the shadow is placed behind the text (and may generate a blur effect when <blur-radius> is set).
+ To find out what units you can use, see {{ cssxref("<length>") }}.
+
<blur-radius>
+
Opcional. This is a {{ cssxref("<length>") }} value. If not specified, it defaults to 0. The higher this value, the bigger the blur; the shadow becomes wider and lighter.
+
+ +

Formal syntax

+ +
{{csssyntax}}
+ +

Exemplos

+ +
+
.red-text-shadow {
+   text-shadow: red 0 -2px;
+}
+ +
<p class="red-text-shadow">
+   Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo
+   inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.
+</p>
+
+ +

{{EmbedLiveSample('Example1', '689px', '90px')}}

+ +
+
.white-with-blue-shadow {
+   text-shadow: 1px 1px 2px black, 0 0 1em blue, 0 0 0.2em blue;
+   color: white;
+   font: 1.5em Georgia, "Bitstream Charter", "URW Bookman L", "Century Schoolbook L", serif;
+}
+ +
<p class="white-with-blue-shadow">
+   Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore
+   veritatis et quasi architecto beatae vitae dicta sunt explicabo.
+</p>
+
+ +

{{EmbedLiveSample('Example2', '689px', '180px')}}

+ +
+
.gold-on-gold {
+   text-shadow: rgba(0,0,0,0.1) -1px 0, rgba(0,0,0,0.1) 0 -1px,
+   rgba(255,255,255,0.1) 1px 0, rgba(255,255,255,0.1) 0 1px,
+   rgba(0,0,0,0.1) -1px -1px, rgba(255,255,255,0.1) 1px 1px;
+   color: gold;
+   background: gold;
+}
+ +
<p class="gold-on-gold">
+   Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore
+   veritatis et quasi architecto beatae vitae dicta sunt explicabo.
+</p>
+
+ +

{{EmbedLiveSample('Example3', '689px', '90px')}}

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{ SpecName('CSS3 Transitions', '#animatable-css', 'text-shadow') }}{{ Spec2('CSS3 Transitions') }}Lists text-shadow as animatable.
{{ SpecName('CSS3 Text Decoration', '#text-shadow', 'text-shadow') }}{{ Spec2('CSS3 Text Decoration') }}The CSS property text-shadow was improperly defined in CSS2 and dropped in CSS2 (Level 1). The CSS Text Module Level 3 spec improved and precised the syntax. Later it was moved to new working draft CSS Text Decoration Module Level 3.
+ +

Compatibilidade do navegador

+ +

{{ CompatibilityTable }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support2.0.158.0{{ CompatGeckoDesktop("1.9.1") }} [1]10 [3]9.5 [2]1.1 (100) [4]
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{ CompatUnknown }}{{ CompatUnknown }}{{ CompatUnknown }}{{ CompatUnknown }}{{ CompatUnknown }}
+
+ +

[1] Gecko (Firefox) theoretically supports infinite text-shadows (don't try it). Gecko 2 and later cap the blur radius at 300 for performance reasons. If the <color> value is unspecified, then Gecko uses the value of the element's {{ cssxref("color") }} property.

+ +

[2] Opera supports a maximum of 6-9 text-shadows for performance reasons. The blur radius is limited to 100px. Opera 9.5-10.1 adheres to the old, reverse painting order (CSS2, the first specified shadow is on the bottom).

+ +

[3] Internet Explorer 5.5 supports Microsoft's Shadow and DropShadow Filter.

+ +

[4] Safari: Any shadows that do not explicitly specify a color are transparent. Safari 1.1-3.2 only supports one text-shadow (displays the first shadow of a comma-separated list and ignores the rest). Safari 4.0 (WebKit 528) and later support multiple text-shadows. Konqueror supports text-shadow starting with version 3.4.

+ +

Veja também

+ +
    +
  • {{ cssxref("box-shadow") }}
  • +
diff --git a/files/pt-br/web/css/text-transform/index.html b/files/pt-br/web/css/text-transform/index.html new file mode 100644 index 0000000000..a32cc3fa2f --- /dev/null +++ b/files/pt-br/web/css/text-transform/index.html @@ -0,0 +1,307 @@ +--- +title: text-transform +slug: Web/CSS/text-transform +translation_of: Web/CSS/text-transform +--- +
{{CSSRef}}
+ +

A propriedade de CSS text-transform especifica como capitalizar um texto de um elemento. Pode ser usado para que o texto apareça com todas as letras maiúsculas  ou todas minúsculas, ou com cada palavra em maiúscula.

+ +
/* Keyword values */
+text-transform: capitalize;
+text-transform: uppercase;
+text-transform: lowercase;
+text-transform: none;
+text-transform: full-width;
+
+/* Global values */
+text-transform: inherit;
+text-transform: initial;
+text-transform: unset;
+
+ +

The text-transform property takes into account language-specific case mapping rules, like:

+ +
    +
  • +

    in Turkic languages, like Turkish (tr), Azerbaijani (az), Crimean Tatar (crh), Volga Tatar (tt), and Bashkir (ba), there are two kinds of i, with and without the dot, and two case pairings: i/İ and ı/I.

    +
  • +
  • +

    In German (de), the ß becomes SS in uppercase.

    +
  • +
  • +

    In Dutch (nl), the ij digraph becomes IJ, even with text-transform: capitalize, which only put the first letter of a word in uppercase.

    +
  • +
  • +

    In Greek (el), vowels lose their accent when the whole word is in uppercase (ά/Α), except for the disjunctive eta (ή/Ή). Also, diphthongs with an accent on the first vowel lose the accent and gain a diaeresis on the second vowel (άι/ΑΪ).

    +
  • +
  • +

    In Greek (el), the lowercase sigma character has two forms: σ and ς. ς is used only when sigma terminates a word. When applying text-transform: lowercase to an uppercase sigma (Σ), the browser needs to choose the right lowercase form based on context.

    +
  • +
  • in Irish (ga), certain prefixed letters remain in lowercase when the base initial is capitalised, so for example text-transform: uppercase will change ar aon tslí to AR AON tSLÍ and not, as one might expect,  AR AON TSLÍ (Firefox only).  In some cases, a hyphen is also removed upon uppercasing: an t-uisce transforms to AN tUISCE (and the hyphen is correctly reinserted by text-transform: lowercase)
  • +
+ +

The language is defined by the lang HTML attribute or the xml:lang XML attribute.

+ +

Support for these specific cases vary from one browser to the other, so check the browser compatibility table.

+ +

{{cssinfo}}

+ +

Syntax

+ +
+
capitalize
+
+

Is a keyword forcing the first letter of each word to be converted to uppercase. Other characters are unchanged; that is, they retain their original case as written in the element's text. A letter is any Unicode character part of the Letter or Number general categories {{experimental_inline}} : it excludes any punctuation marks or symbols at the beginning of the word.

+ +
Authors should not expect capitalize to follow language-specific title casing conventions (such as skipping articles in English).
+ +
The capitalize keyword was under-specified in CSS 1 and CSS 2.1. There were differences between browsers in the way the first letter was calculated (Firefox considered - and _ as letters, but not the others. Both Webkit and Gecko incorrectly considered letter-based symbols like to be real letters. Internet Explorer 9 was the closest to the CSS 2 definition, but with some weird cases). By precisely defining the correct behavior, CSS Text Level 3 cleans this mess up. The capitalize line in the browser compatibility table contains the version the different engines started to support this now precisely defined behavior.
+
+
uppercase
+
Is a keyword forcing all characters to be converted to uppercase.
+
lowercase
+
Is a keyword forcing all characters to be converted to lowercase.
+
none
+
Is a keyword preventing the case of all characters to be changed.
+
full-width {{experimental_inline}}
+
Is a keyword forcing the writing of a character — mainly ideograms and latin scripts —  inside a square, allowing them to be aligned in the usual East Asian scripts (like Chinese or Japanese).
+ +
+ +

Formal syntax

+ +
{{csssyntax}}
+ +

Examples

+ +

none

+ +
<p>Initial String
+  <strong>Lorem ipsum dolor sit amet, consectetur adipisicing elit, ...</strong>
+</p>
+<p>text-transform: none
+  <strong><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit, ...</span></strong>
+</p>
+
+ +
span {
+  text-transform: none;
+}
+strong { float: right; }
+ +

This demonstrates no text transformation.

+ +

{{ EmbedLiveSample('none', '100%', '100px') }}

+ +

capitalize (General)

+ +
<p>Initial String
+  <strong>Lorem ipsum dolor sit amet, consectetur adipisicing elit, ...</strong>
+</p>
+<p>text-transform: capitalize
+  <strong><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit, ...</span></strong>
+</p>
+ +
span {
+  text-transform: capitalize;
+}
+strong { float: right; }
+ +

This demonstrates text capitalization.

+ +

{{ EmbedLiveSample('capitalize_(General)', '100%', '100px') }}

+ +

capitalize (Punctuation)

+ +
<p>Initial String
+  <strong>(this) “is” [a] –short– -test- «for» *the* _css_ ¿capitalize? ?¡transform!</strong>
+</p>
+<p>text-transform: capitalize
+  <strong><span>(this) “is” [a] –short– -test- «for» *the* _css_ ¿capitalize? ?¡transform!</span></strong>
+</p>
+ +
span {
+  text-transform: capitalize;
+}
+strong { float: right; }
+ +

This demostrates how initial punctuations of a word are ignored. The keyword target the first letter, that is the first Unicode character part of the Letter or Number general category.

+ +

{{ EmbedLiveSample('capitalize_(Punctuation)', '100%', '100px') }}

+ +

capitalize (Symbols)

+ +
<p>Initial String
+  <strong>ⓐⓑⓒ (ⓓⓔⓕ) —ⓖⓗⓘ— ⓙkl</strong>
+</p>
+<p>text-transform: capitalize
+  <strong><span>ⓐⓑⓒ (ⓓⓔⓕ) —ⓖⓗⓘ— ⓙkl</span></strong>
+</p>
+ +
span {
+  text-transform: capitalize;
+}
+strong { float: right; }
+ +

This demonstrates how initial symbols are ignored. The keyword target the first letter, that is the first Unicode character part of the Letter or Number general category.

+ +

{{ EmbedLiveSample('capitalize_(Symbols)', '100%', '100px') }}

+ +

capitalize (Dutch ij digraph)

+ +
<p>Initial String
+  <strong lang="nl">The Dutch word: "ijsland" starts with a digraph.</strong>
+</p>
+<p>text-transform: capitalize
+  <strong><span lang="nl">The Dutch word: "ijsland" starts with a digraph.</span></strong>
+</p>
+ +
span {
+  text-transform: capitalize;
+}
+strong { float: right; }
+ +

This demonstrates how the Dutch ij digraph must be handled like one single letter.

+ +

{{ EmbedLiveSample('capitalize_(Dutch_ij_digraph)', '100%', '100px') }}

+ +

uppercase (General)

+ +
<p>Initial String
+  <strong>Lorem ipsum dolor sit amet, consectetur adipisicing elit, ...</strong>
+</p>
+<p>text-transform: uppercase
+  <strong><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit, ...</span></strong>
+</p>
+ +
span {
+  text-transform: uppercase;
+}
+strong { float: right; }
+ +

This demonstrates transforming the text to uppercase.

+ +

{{ EmbedLiveSample('uppercase_(General)', '100%', '100px') }}

+ +

uppercase (Greek Vowels)

+ +
<p>Initial String
+  <strong>Θα πάμε στο "Θεϊκό φαΐ" ή στη "Νεράιδα"</strong>
+</p>
+<p>text-transform: uppercase
+  <strong><span>Θα πάμε στο "Θεϊκό φαΐ" ή στη "Νεράιδα"</span></strong>
+</p>
+ +
span {
+  text-transform: uppercase;
+}
+strong { float: right; }
+ +

This demonstrates how Greek vowels except disjunctive eta should have no accent, and the accent on the first vowel of a vowel pair becomes a diaeresis on the second vowel.

+ +

{{ EmbedLiveSample('uppercase_(Greek_Vowels)', '100%', '100px') }}

+ +

lowercase (General)

+ +
<p>Initial String
+  <strong>Lorem ipsum dolor sit amet, consectetur adipisicing elit, ...</strong>
+</p>
+<p>text-transform: lowercase
+  <strong><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit, ...</span></strong>
+</p>
+ +
span {
+  text-transform: lowercase;
+}
+strong { float: right; }
+ +

This demonstrates transforming the text to lowercase.

+ +

{{ EmbedLiveSample('lowercase_(General)', '100%', '100px') }}

+ +

lowercase (Greek Σ)

+ +
<p>Initial String
+  <strong>Σ IS A greek LETTER that appears SEVERAL TIMES IN ΟΔΥΣΣΕΥΣ.</strong>
+</p>
+<p>text-transform: lowercase
+  <strong><span>Σ IS A greek LETTER that appears SEVERAL TIMES IN ΟΔΥΣΣΕΥΣ.</span></strong>
+</p>
+ +
span {
+  text-transform: lowercase;
+}
+strong { float: right; }
+ +

This demonstrates how the Greek character sigma (Σ) is transformed into the regular lowercase sigma (σ) or the word-final variant (ς), according the context.

+ +

{{ EmbedLiveSample('lowercase_(Greek_Σ)', '100%', '100px') }}

+ +

full-width (General)

+ +
<p>Initial String
+  <strong>0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&()*+,-./:;<=>?@{|}~</strong>
+</p>
+<p>text-transform: full-width
+  <strong><span>0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&()*+,-./:;<=>?@{|}~</span></strong>
+</p>
+ +
span {
+  text-transform: full-width;
+}
+strong { width: 100%; float: right; }
+ +

Some characters exists in two formats, normal width and a full-width, with different Unicode code points. The full-width version is used to mix them smoothly with Asian ideographic characters.

+ +

{{ EmbedLiveSample('full-width_(General)', '100%', '175px') }}

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS4 Text', '#text-transform', 'text-transform')}}{{Spec2('CSS4 Text')}}From {{SpecName('CSS3 Text', '#text-transform', 'text-transform')}}, adds the full-size-kana keyword and allows the full-width keyword to be used together with another keyword.
{{SpecName('CSS3 Text', '#text-transform', 'text-transform')}}{{Spec2('CSS3 Text')}}From {{SpecName('CSS2.1', 'text.html#caps-prop', 'text-transform')}}, extends letters to any Unicode character in the Number or Letter general category.  Modifies the behavior of capitalize to apply to the first letter of the word, ignoring initial punctuations or symbols. Adds the full-width keyword to mix smoothly ideographic characters and alphabetical characters.
{{SpecName('CSS2.1', 'text.html#caps-prop', 'text-transform')}}{{Spec2('CSS2.1')}}From {{SpecName('CSS1', '#text-transform', 'text-transform')}}, extends letters to non-latin bi-cameral scripts
{{SpecName('CSS1', '#text-transform', 'text-transform')}}{{Spec2('CSS1')}}Initial definition
+ +

Browser compatibility

+ +

 

+ + + +

{{Compat("css.properties.text-transform")}}

+ +

 

+ +

See also

+ +
    +
  • {{cssxref("font-variant")}}
  • +
diff --git a/files/pt-br/web/css/time/index.html b/files/pt-br/web/css/time/index.html new file mode 100644 index 0000000000..e0148b11df --- /dev/null +++ b/files/pt-br/web/css/time/index.html @@ -0,0 +1,89 @@ +--- +title: