From 218934fa2ed1c702a6d3923d2aa2cc6b43c48684 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:43:23 -0500 Subject: initial commit --- .../accessibility/aria/aria_techniques/index.html | 164 + .../aria/forms/basic_form_hints/index.html | 119 + .../zh-tw/web/accessibility/aria/forms/index.html | 19 + files/zh-tw/web/accessibility/aria/index.html | 142 + files/zh-tw/web/accessibility/index.html | 61 + .../mobile_accessibility_checklist/index.html | 94 + files/zh-tw/web/api/abortcontroller/index.html | 97 + .../zh-tw/web/api/ambient_light_events/index.html | 96 + .../analysernode/getbytefrequencydata/index.html | 149 + files/zh-tw/web/api/analysernode/index.html | 226 ++ files/zh-tw/web/api/animationevent/index.html | 182 ++ .../animationevent/initanimationevent/index.html | 129 + files/zh-tw/web/api/battery_status_api/index.html | 38 + files/zh-tw/web/api/blob/blob/index.html | 125 + files/zh-tw/web/api/blob/index.html | 116 + files/zh-tw/web/api/blob/size/index.html | 114 + files/zh-tw/web/api/blob/type/index.html | 114 + files/zh-tw/web/api/body/index.html | 99 + files/zh-tw/web/api/body/json/index.html | 73 + .../drawing_graphics_with_canvas/index.html | 161 + files/zh-tw/web/api/canvas_api/index.html | 158 + .../tutorial/advanced_animations/index.html | 376 +++ .../tutorial/applying_styles_and_colors/index.html | 669 ++++ .../tutorial/basic_animations/index.html | 347 +++ .../api/canvas_api/tutorial/basic_usage/index.html | 158 + .../api/canvas_api/tutorial/compositing/index.html | 207 ++ .../canvas_api/tutorial/drawing_shapes/index.html | 551 ++++ .../canvas_api/tutorial/drawing_text/index.html | 397 +++ files/zh-tw/web/api/canvas_api/tutorial/index.html | 69 + .../tutorial/optimizing_canvas/index.html | 26 + .../pixel_manipulation_with_canvas/index.html | 265 ++ .../canvas_api/tutorial/transformations/index.html | 336 ++ .../canvas_api/tutorial/using_images/index.html | 342 +++ .../canvasrenderingcontext2d/clearrect/index.html | 189 ++ .../web/api/canvasrenderingcontext2d/index.html | 459 +++ .../zh-tw/web/api/channel_messaging_api/index.html | 158 + files/zh-tw/web/api/characterdata/index.html | 156 + files/zh-tw/web/api/childnode/index.html | 182 ++ files/zh-tw/web/api/clients/index.html | 113 + files/zh-tw/web/api/clipboardevent/index.html | 119 + files/zh-tw/web/api/console/assert/index.html | 118 + files/zh-tw/web/api/console/index.html | 289 ++ .../index.html | 33 + files/zh-tw/web/api/css_object_model/index.html | 131 + .../managing_screen_orientation/index.html | 172 ++ .../using_dynamic_styling_information/index.html | 132 + files/zh-tw/web/api/cssstyledeclaration/index.html | 90 + files/zh-tw/web/api/cssstylesheet/index.html | 187 ++ .../web/api/cssstylesheet/insertrule/index.html | 219 ++ .../web/api/customevent/customevent/index.html | 90 + files/zh-tw/web/api/customevent/index.html | 88 + files/zh-tw/web/api/datatransfer/index.html | 204 ++ .../api/detecting_device_orientation/index.html | 278 ++ files/zh-tw/web/api/devicemotionevent/index.html | 116 + .../web/api/deviceorientationevent/index.html | 122 + .../web/api/document.createtreewalker/index.html | 224 ++ files/zh-tw/web/api/document/body/index.html | 128 + .../api/document/createdocumentfragment/index.html | 136 + .../web/api/document/createelement/index.html | 179 ++ .../zh-tw/web/api/document/createrange/index.html | 33 + .../web/api/document/createtextnode/index.html | 120 + .../zh-tw/web/api/document/defaultview/index.html | 94 + files/zh-tw/web/api/document/designmode/index.html | 114 + .../web/api/document/documentelement/index.html | 60 + .../zh-tw/web/api/document/execcommand/index.html | 172 ++ files/zh-tw/web/api/document/forms/index.html | 75 + .../api/document/getelementsbyclassname/index.html | 127 + files/zh-tw/web/api/document/head/index.html | 114 + files/zh-tw/web/api/document/index.html | 446 +++ .../zh-tw/web/api/document/keyup_event/index.html | 149 + .../web/api/document/queryselector/index.html | 102 + files/zh-tw/web/api/document/readystate/index.html | 108 + .../web/api/document/registerelement/index.html | 113 + .../zh-tw/web/api/document/scroll_event/index.html | 103 + files/zh-tw/web/api/document/width/index.html | 45 + .../api/document_object_model/examples/index.html | 373 +++ .../how_to_create_a_dom_tree/index.html | 145 + .../zh-tw/web/api/document_object_model/index.html | 384 +++ .../document_object_model/whitespace/index.html | 183 ++ .../\344\272\213\344\273\266/index.html" | 69 + files/zh-tw/web/api/documentfragment/index.html | 248 ++ files/zh-tw/web/api/documenttype/index.html | 200 ++ files/zh-tw/web/api/domparser/index.html | 200 ++ files/zh-tw/web/api/domstring/index.html | 50 + files/zh-tw/web/api/domtokenlist/index.html | 117 + .../web/api/dragevent/datatransfer/index.html | 118 + files/zh-tw/web/api/dragevent/index.html | 160 + files/zh-tw/web/api/element/attributes/index.html | 121 + files/zh-tw/web/api/element/classlist/index.html | 403 +++ files/zh-tw/web/api/element/click_event/index.html | 205 ++ .../zh-tw/web/api/element/clientheight/index.html | 62 + .../zh-tw/web/api/element/getattribute/index.html | 71 + files/zh-tw/web/api/element/index.html | 674 ++++ files/zh-tw/web/api/element/innerhtml/index.html | 215 ++ .../web/api/element/insertadjacenthtml/index.html | 135 + .../web/api/element/queryselectorall/index.html | 140 + .../zh-tw/web/api/element/scrollheight/index.html | 170 ++ files/zh-tw/web/api/element/scrolltop/index.html | 73 + .../web/api/element/touchcancel_event/index.html | 169 + files/zh-tw/web/api/errorevent/index.html | 148 + files/zh-tw/web/api/event/bubbles/index.html | 63 + .../event/comparison_of_event_targets/index.html | 164 + files/zh-tw/web/api/event/createevent/index.html | 29 + files/zh-tw/web/api/event/currenttarget/index.html | 70 + .../web/api/event/defaultprevented/index.html | 100 + files/zh-tw/web/api/event/event/index.html | 87 + files/zh-tw/web/api/event/eventphase/index.html | 179 ++ files/zh-tw/web/api/event/index.html | 210 ++ files/zh-tw/web/api/event/istrusted/index.html | 107 + .../zh-tw/web/api/event/preventdefault/index.html | 129 + .../api/event/stopimmediatepropagation/index.html | 94 + .../zh-tw/web/api/event/stoppropagation/index.html | 63 + files/zh-tw/web/api/event/target/index.html | 134 + files/zh-tw/web/api/event/timestamp/index.html | 54 + files/zh-tw/web/api/event/type/index.html | 97 + files/zh-tw/web/api/eventlistener/index.html | 93 + .../web/api/eventtarget/dispatchevent/index.html | 134 + files/zh-tw/web/api/eventtarget/index.html | 177 ++ .../api/eventtarget/removeeventlistener/index.html | 274 ++ files/zh-tw/web/api/fetch_api/index.html | 84 + .../zh-tw/web/api/fetch_api/using_fetch/index.html | 379 +++ files/zh-tw/web/api/file/file/index.html | 112 + files/zh-tw/web/api/file/filename/index.html | 32 + files/zh-tw/web/api/file/index.html | 121 + .../using_files_from_web_applications/index.html | 411 +++ files/zh-tw/web/api/file_handle_api/index.html | 233 ++ files/zh-tw/web/api/filelist/index.html | 149 + files/zh-tw/web/api/filereader/error/index.html | 102 + files/zh-tw/web/api/filereader/index.html | 213 ++ .../zh-tw/web/api/filereader/readystate/index.html | 98 + files/zh-tw/web/api/filesystem/index.html | 118 + files/zh-tw/web/api/formdata/get/index.html | 145 + files/zh-tw/web/api/formdata/index.html | 218 ++ .../api/formdata/using_formdata_objects/index.html | 137 + files/zh-tw/web/api/fullscreen_api/index.html | 240 ++ files/zh-tw/web/api/gainnode/gain/index.html | 113 + files/zh-tw/web/api/gainnode/index.html | 168 + .../web/api/geolocation/clearwatch/index.html | 132 + .../api/geolocation/getcurrentposition/index.html | 127 + files/zh-tw/web/api/geolocation/index.html | 118 + .../api/geolocation/using_geolocation/index.html | 251 ++ .../web/api/geolocation/watchposition/index.html | 143 + .../api/geolocationcoordinates/accuracy/index.html | 93 + .../api/geolocationcoordinates/altitude/index.html | 93 + .../altitudeaccuracy/index.html | 93 + .../api/geolocationcoordinates/heading/index.html | 93 + .../web/api/geolocationcoordinates/index.html | 113 + .../api/geolocationcoordinates/latitude/index.html | 93 + .../geolocationcoordinates/longitude/index.html | 93 + .../api/geolocationcoordinates/speed/index.html | 93 + .../web/api/geolocationposition/coords/index.html | 93 + files/zh-tw/web/api/geolocationposition/index.html | 103 + .../api/geolocationposition/timestamp/index.html | 93 + .../api/geolocationpositionerror/code/index.html | 120 + .../web/api/geolocationpositionerror/index.html | 128 + .../geolocationpositionerror/message/index.html | 93 + files/zh-tw/web/api/globaleventhandlers/index.html | 682 +++++ .../web/api/globaleventhandlers/onclick/index.html | 144 + .../web/api/globaleventhandlers/onclose/index.html | 102 + files/zh-tw/web/api/history/index.html | 183 ++ files/zh-tw/web/api/history_api/index.html | 255 ++ .../drag_operations/index.html | 336 ++ .../web/api/html_drag_and_drop_api/index.html | 249 ++ files/zh-tw/web/api/htmlcanvaselement/index.html | 262 ++ .../web/api/htmlcanvaselement/todataurl/index.html | 201 ++ files/zh-tw/web/api/htmlcollection/index.html | 95 + files/zh-tw/web/api/htmldataelement/index.html | 59 + files/zh-tw/web/api/htmldocument/index.html | 16 + files/zh-tw/web/api/htmlelement/click/index.html | 115 + files/zh-tw/web/api/htmlelement/dataset/index.html | 167 + files/zh-tw/web/api/htmlelement/index.html | 447 +++ files/zh-tw/web/api/htmlelement/lang/index.html | 59 + files/zh-tw/web/api/htmlelement/style/index.html | 79 + files/zh-tw/web/api/htmlformelement/index.html | 245 ++ .../api/htmlformelement/submit_event/index.html | 60 + files/zh-tw/web/api/htmlimageelement/index.html | 408 +++ files/zh-tw/web/api/htmlinputelement/index.html | 592 ++++ files/zh-tw/web/api/htmlmediaelement/index.html | 243 ++ .../htmlmediaelement/ratechange_event/index.html | 82 + .../web/api/htmlmediaelement/readystate/index.html | 110 + .../api/htmlselectelement/checkvalidity/index.html | 98 + files/zh-tw/web/api/htmlselectelement/index.html | 283 ++ .../htmlselectelement/setcustomvalidity/index.html | 50 + files/zh-tw/web/api/idbdatabase/index.html | 219 ++ files/zh-tw/web/api/index.html | 15 + .../basic_concepts_behind_indexeddb/index.html | 209 ++ files/zh-tw/web/api/indexeddb_api/index.html | 148 + .../api/indexeddb_api/using_indexeddb/index.html | 1085 +++++++ files/zh-tw/web/api/keyboardevent/index.html | 449 +++ .../web/api/keyboardevent/keyboardevent/index.html | 202 ++ files/zh-tw/web/api/media_streams_api/index.html | 87 + files/zh-tw/web/api/mediaquerylist/index.html | 144 + .../api/mediasource/activesourcebuffers/index.html | 126 + .../zh-tw/web/api/mediasource/duration/index.html | 149 + files/zh-tw/web/api/mediasource/index.html | 144 + .../web/api/mediasource/mediasource/index.html | 122 + .../web/api/mediasource/readystate/index.html | 136 + files/zh-tw/web/api/mouseevent/index.html | 317 ++ files/zh-tw/web/api/mutationobserver/index.html | 276 ++ files/zh-tw/web/api/namednodemap/index.html | 156 + .../zh-tw/web/api/navigator/geolocation/index.html | 96 + files/zh-tw/web/api/navigator/index.html | 154 + .../navigator/registerprotocolhandler/index.html | 170 ++ .../web-based_protocol_handlers/index.html | 28 + files/zh-tw/web/api/navigatoronline/index.html | 129 + .../online_and_offline_events/index.html | 101 + .../web/api/network_information_api/index.html | 46 + files/zh-tw/web/api/node/childnodes/index.html | 66 + files/zh-tw/web/api/node/clonenode/index.html | 160 + files/zh-tw/web/api/node/index.html | 529 ++++ files/zh-tw/web/api/node/innertext/index.html | 86 + files/zh-tw/web/api/node/insertbefore/index.html | 167 + files/zh-tw/web/api/node/nodename/index.html | 102 + files/zh-tw/web/api/node/nodetype/index.html | 171 ++ files/zh-tw/web/api/node/ownerdocument/index.html | 111 + files/zh-tw/web/api/node/removechild/index.html | 133 + files/zh-tw/web/api/node/textcontent/index.html | 158 + files/zh-tw/web/api/nodelist/index.html | 219 ++ .../web/api/nondocumenttypechildnode/index.html | 125 + files/zh-tw/web/api/notification/index.html | 355 +++ files/zh-tw/web/api/notifications_api/index.html | 198 ++ .../using_the_notifications_api/index.html | 236 ++ files/zh-tw/web/api/parentnode/children/index.html | 152 + .../api/parentnode/firstelementchild/index.html | 95 + files/zh-tw/web/api/parentnode/index.html | 166 + files/zh-tw/web/api/payment_request_api/index.html | 117 + files/zh-tw/web/api/paymentrequest/index.html | 80 + files/zh-tw/web/api/performance.timing/index.html | 56 + files/zh-tw/web/api/performance/index.html | 140 + files/zh-tw/web/api/pointer_lock_api/index.html | 285 ++ .../positionoptions/enablehighaccuracy/index.html | 93 + files/zh-tw/web/api/positionoptions/index.html | 105 + .../web/api/positionoptions/maximumage/index.html | 93 + .../web/api/positionoptions/timeout/index.html | 93 + files/zh-tw/web/api/progressevent/index.html | 161 + files/zh-tw/web/api/proximity_events/index.html | 118 + files/zh-tw/web/api/range/index.html | 249 ++ files/zh-tw/web/api/response/index.html | 120 + files/zh-tw/web/api/screen/index.html | 89 + files/zh-tw/web/api/screen/orientation/index.html | 114 + files/zh-tw/web/api/server-sent_events/index.html | 115 + .../using_server-sent_events/index.html | 202 ++ files/zh-tw/web/api/storage/index.html | 106 + files/zh-tw/web/api/touch/index.html | 207 ++ files/zh-tw/web/api/touch_events/index.html | 387 +++ files/zh-tw/web/api/touchevent/index.html | 201 ++ files/zh-tw/web/api/touchlist/index.html | 120 + files/zh-tw/web/api/uievent/index.html | 188 ++ files/zh-tw/web/api/uievent/uievent/index.html | 134 + files/zh-tw/web/api/url/createobjecturl/index.html | 137 + files/zh-tw/web/api/url/index.html | 212 ++ files/zh-tw/web/api/validitystate/index.html | 145 + files/zh-tw/web/api/vibration_api/index.html | 113 + files/zh-tw/web/api/web_audio_api/index.html | 119 + .../api/web_video_text_tracks_format/index.html | 691 +++++ files/zh-tw/web/api/web_workers_api/index.html | 215 ++ .../web_workers_api/using_web_workers/index.html | 791 +++++ files/zh-tw/web/api/webgl_api/index.html | 255 ++ .../index.html | 280 ++ .../animating_objects_with_webgl/index.html | 55 + .../tutorial/getting_started_with_webgl/index.html | 73 + files/zh-tw/web/api/webgl_api/tutorial/index.html | 41 + .../index.html | 123 + files/zh-tw/web/api/webrtc_api/index.html | 193 ++ files/zh-tw/web/api/webvr_api/index.html | 246 ++ files/zh-tw/web/api/wheelevent/index.html | 196 ++ files/zh-tw/web/api/window.history/index.html | 51 + files/zh-tw/web/api/window.onpopstate/index.html | 57 + .../api/window.requestanimationframe/index.html | 94 + .../web/api/window/getcomputedstyle/index.html | 200 ++ files/zh-tw/web/api/window/index.html | 468 +++ files/zh-tw/web/api/window/localstorage/index.html | 82 + files/zh-tw/web/api/window/location/index.html | 373 +++ files/zh-tw/web/api/window/navigator/index.html | 58 + files/zh-tw/web/api/window/opener/index.html | 30 + .../api/window/orientationchange_event/index.html | 69 + files/zh-tw/web/api/window/print/index.html | 46 + .../web/api/window/requestidlecallback/index.html | 119 + .../zh-tw/web/api/window/sessionstorage/index.html | 94 + .../index.html | 35 + files/zh-tw/web/api/window/sidebar/index.html | 56 + files/zh-tw/web/api/windowbase64/index.html | 113 + files/zh-tw/web/api/windoweventhandlers/index.html | 182 ++ .../windoweventhandlers/onbeforeunload/index.html | 153 + .../api/windoworworkerglobalscope/btoa/index.html | 136 + .../web/api/windoworworkerglobalscope/index.html | 98 + .../setinterval/index.html | 627 ++++ files/zh-tw/web/api/windowtimers/index.html | 114 + files/zh-tw/web/api/xmlhttprequest/index.html | 177 ++ .../xmlhttprequest/onreadystatechange/index.html | 113 + .../web/api/xmlhttprequest/readystate/index.html | 148 + .../api/xmlhttprequest/setrequestheader/index.html | 66 + .../zh-tw/web/api/xmlhttprequest/status/index.html | 115 + .../index.html | 260 ++ .../xmlhttprequest/using_xmlhttprequest/index.html | 766 +++++ .../api/xmlhttprequest/withcredentials/index.html | 48 + .../api/xmlhttprequest/xmlhttprequest/index.html | 50 + .../web/api/xmlhttprequesteventtarget/index.html | 111 + files/zh-tw/web/css/@font-face/index.html | 247 ++ files/zh-tw/web/css/@media/height/index.html | 77 + files/zh-tw/web/css/@media/index.html | 377 +++ files/zh-tw/web/css/@viewport/height/index.html | 120 + files/zh-tw/web/css/@viewport/index.html | 159 + files/zh-tw/web/css/_colon_first-child/index.html | 154 + .../zh-tw/web/css/_colon_first-of-type/index.html | 162 + files/zh-tw/web/css/_colon_lang/index.html | 98 + files/zh-tw/web/css/_colon_target/index.html | 275 ++ .../web/css/_doublecolon_first-letter/index.html | 206 ++ files/zh-tw/web/css/animation-fill-mode/index.html | 158 + files/zh-tw/web/css/attr()/index.html | 200 ++ .../zh-tw/web/css/background-attachment/index.html | 151 + files/zh-tw/web/css/background-color/index.html | 115 + .../web/css/border-image/border-image/index.html | 111 + files/zh-tw/web/css/border-image/index.html | 9 + files/zh-tw/web/css/border/index.html | 134 + files/zh-tw/web/css/box-shadow/index.html | 228 ++ files/zh-tw/web/css/box-sizing/index.html | 94 + files/zh-tw/web/css/clip/index.html | 174 ++ .../zh-tw/web/css/common_css_questions/index.html | 165 + files/zh-tw/web/css/css_animations/index.html | 136 + .../css_animations/using_css_animations/index.html | 334 ++ .../web/css/css_background_and_borders/index.html | 152 + .../using_css_multiple_backgrounds/index.html | 84 + files/zh-tw/web/css/css_box_model/index.html | 167 + .../mastering_margin_collapsing/index.html | 107 + .../css/css_colors/color_picker_tool/index.html | 3221 ++++++++++++++++++++ files/zh-tw/web/css/css_colors/index.html | 119 + .../web/css/css_flexible_box_layout/index.html | 118 + .../using_css_flexible_boxes/index.html | 382 +++ .../basic_concepts_of_grid_layout/index.html | 715 +++++ files/zh-tw/web/css/css_grid_layout/index.html | 252 ++ .../consistent_list_indentation/index.html | 67 + .../web/css/css_lists_and_counters/index.html | 127 + files/zh-tw/web/css/css_positioning/index.html | 108 + .../understanding_z_index/index.html | 40 + .../stacking_context_example_1/index.html | 139 + .../web/css/css_properties_reference/index.html | 317 ++ files/zh-tw/web/css/css_selectors/index.html | 123 + .../index.html | 62 + files/zh-tw/web/css/css_transitions/index.html | 110 + .../using_css_transitions/index.html | 384 +++ files/zh-tw/web/css/cursor/index.html | 306 ++ .../zh-tw/web/css/descendant_combinator/index.html | 121 + files/zh-tw/web/css/grid-row/index.html | 194 ++ .../zh-tw/web/css/grid-template-columns/index.html | 196 ++ files/zh-tw/web/css/grid-template/index.html | 197 ++ files/zh-tw/web/css/height/index.html | 234 ++ files/zh-tw/web/css/ime-mode/index.html | 56 + files/zh-tw/web/css/index.html | 100 + files/zh-tw/web/css/inheritance/index.html | 48 + files/zh-tw/web/css/line-break/index.html | 71 + files/zh-tw/web/css/media_queries/index.html | 112 + .../media_queries/testing_media_queries/index.html | 118 + files/zh-tw/web/css/object-fit/index.html | 217 ++ files/zh-tw/web/css/pseudo-classes/index.html | 129 + files/zh-tw/web/css/radial-gradient()/index.html | 183 ++ files/zh-tw/web/css/reference/index.html | 211 ++ files/zh-tw/web/css/replaced_element/index.html | 20 + files/zh-tw/web/css/ruby-position/index.html | 112 + .../zh-tw/web/css/shorthand_properties/index.html | 138 + files/zh-tw/web/css/syntax/index.html | 74 + files/zh-tw/web/css/transform-function/index.html | 894 ++++++ .../transform-function/translate3d()/index.html | 116 + files/zh-tw/web/css/transform-origin/index.html | 455 +++ files/zh-tw/web/css/transform/index.html | 159 + files/zh-tw/web/css/transition-duration/index.html | 342 +++ .../web/css/transition-timing-function/index.html | 605 ++++ files/zh-tw/web/css/transition/index.html | 106 + files/zh-tw/web/css/type_selectors/index.html | 79 + files/zh-tw/web/css/white-space/index.html | 425 +++ files/zh-tw/web/css/width/index.html | 294 ++ .../web/demos_of_open_web_technologies/index.html | 144 + files/zh-tw/web/events/abort/index.html | 67 + files/zh-tw/web/events/domcontentloaded/index.html | 133 + files/zh-tw/web/events/index.html | 1928 ++++++++++++ files/zh-tw/web/events/load/index.html | 88 + .../web/guide/ajax/getting_started/index.html | 287 ++ files/zh-tw/web/guide/ajax/index.html | 119 + files/zh-tw/web/guide/api/index.html | 25 + files/zh-tw/web/guide/dom/index.html | 21 + .../creating_and_triggering_events/index.html | 144 + .../web/guide/events/event_handlers/index.html | 178 ++ files/zh-tw/web/guide/events/index.html | 52 + files/zh-tw/web/guide/graphics/index.html | 49 + .../web/guide/html/content_categories/index.html | 150 + .../web/guide/html/event_attributes/index.html | 84 + files/zh-tw/web/guide/html/html5/index.html | 112 + .../html/html5/introduction_to_html5/index.html | 40 + files/zh-tw/web/guide/index.html | 29 + .../introduction_to_web_development/index.html | 13 + files/zh-tw/web/guide/performance/index.html | 14 + files/zh-tw/web/guide/woff/index.html | 100 + .../writing_forward-compatible_websites/index.html | 70 + files/zh-tw/web/html/applying_color/index.html | 502 +++ files/zh-tw/web/html/attributes/index.html | 643 ++++ .../zh-tw/web/html/block-level_elements/index.html | 130 + files/zh-tw/web/html/element/a/index.html | 313 ++ files/zh-tw/web/html/element/blink/index.html | 75 + files/zh-tw/web/html/element/blockquote/index.html | 149 + files/zh-tw/web/html/element/br/index.html | 130 + files/zh-tw/web/html/element/button/index.html | 355 +++ files/zh-tw/web/html/element/canvas/index.html | 193 ++ files/zh-tw/web/html/element/code/index.html | 138 + files/zh-tw/web/html/element/div/index.html | 95 + files/zh-tw/web/html/element/font/index.html | 45 + files/zh-tw/web/html/element/form/index.html | 191 ++ files/zh-tw/web/html/element/frameset/index.html | 39 + files/zh-tw/web/html/element/hr/index.html | 168 + files/zh-tw/web/html/element/index.html | 106 + files/zh-tw/web/html/element/input/index.html | 750 +++++ .../zh-tw/web/html/element/input/submit/index.html | 211 ++ files/zh-tw/web/html/element/marquee/index.html | 112 + files/zh-tw/web/html/element/meter/index.html | 143 + files/zh-tw/web/html/element/nav/index.html | 107 + files/zh-tw/web/html/element/optgroup/index.html | 161 + files/zh-tw/web/html/element/picture/index.html | 156 + files/zh-tw/web/html/element/q/index.html | 103 + files/zh-tw/web/html/element/ruby/index.html | 93 + files/zh-tw/web/html/element/script/index.html | 202 ++ files/zh-tw/web/html/element/summary/index.html | 135 + files/zh-tw/web/html/element/table/index.html | 362 +++ files/zh-tw/web/html/element/template/index.html | 145 + files/zh-tw/web/html/element/time/index.html | 162 + files/zh-tw/web/html/forms_in_html/index.html | 83 + .../html/global_attributes/data-_star_/index.html | 114 + files/zh-tw/web/html/global_attributes/index.html | 474 +++ .../html/global_attributes/spellcheck/index.html | 39 + files/zh-tw/web/html/index.html | 105 + .../html/quirks_mode_and_standards_mode/index.html | 46 + files/zh-tw/web/html/reference/index.html | 22 + .../web/html/supported_media_formats/index.html | 466 +++ .../html/using_the_application_cache/index.html | 391 +++ files/zh-tw/web/http/authentication/index.html | 123 + files/zh-tw/web/http/basics_of_http/index.html | 51 + .../web/http/basics_of_http/mime_types/index.html | 324 ++ .../index.html | 372 +++ files/zh-tw/web/http/caching/index.html | 154 + files/zh-tw/web/http/cookies/index.html | 194 ++ .../http/cors/errors/corsdidnotsucceed/index.html | 22 + .../cors/errors/corsmissingalloworigin/index.html | 48 + .../errors/corsnotsupportingcredentials/index.html | 32 + files/zh-tw/web/http/cors/errors/index.html | 76 + files/zh-tw/web/http/cors/index.html | 549 ++++ files/zh-tw/web/http/data_uris/index.html | 128 + files/zh-tw/web/http/headers/accept/index.html | 92 + files/zh-tw/web/http/headers/dnt/index.html | 83 + files/zh-tw/web/http/headers/index.html | 360 +++ files/zh-tw/web/http/headers/server/index.html | 73 + .../headers/strict-transport-security/index.html | 110 + files/zh-tw/web/http/headers/user-agent/index.html | 146 + .../web/http/headers/x-forwarded-for/index.html | 74 + .../web/http/headers/x-frame-options/index.html | 146 + files/zh-tw/web/http/index.html | 83 + .../zh-tw/web/http/link_prefetching_faq/index.html | 121 + files/zh-tw/web/http/methods/connect/index.html | 82 + files/zh-tw/web/http/methods/get/index.html | 69 + files/zh-tw/web/http/methods/index.html | 63 + files/zh-tw/web/http/methods/post/index.html | 124 + .../web/http/protocol_upgrade_mechanism/index.html | 152 + .../web/http/server-side_access_control/index.html | 212 ++ files/zh-tw/web/http/status/100/index.html | 42 + files/zh-tw/web/http/status/101/index.html | 46 + files/zh-tw/web/http/status/200/index.html | 50 + files/zh-tw/web/http/status/201/index.html | 43 + files/zh-tw/web/http/status/202/index.html | 33 + files/zh-tw/web/http/status/203/index.html | 37 + files/zh-tw/web/http/status/204/index.html | 49 + files/zh-tw/web/http/status/205/index.html | 39 + files/zh-tw/web/http/status/206/index.html | 79 + files/zh-tw/web/http/status/300/index.html | 38 + files/zh-tw/web/http/status/301/index.html | 54 + files/zh-tw/web/http/status/403/index.html | 49 + files/zh-tw/web/http/status/404/index.html | 59 + files/zh-tw/web/http/status/409/index.html | 35 + files/zh-tw/web/http/status/411/index.html | 38 + files/zh-tw/web/http/status/415/index.html | 39 + .../web/http/status/418_i_m_a_teapot/index.html | 45 + files/zh-tw/web/http/status/451/index.html | 65 + files/zh-tw/web/http/status/500/index.html | 43 + files/zh-tw/web/http/status/502/index.html | 57 + files/zh-tw/web/http/status/503/index.html | 67 + files/zh-tw/web/http/status/504/index.html | 46 + files/zh-tw/web/http/status/index.html | 191 ++ files/zh-tw/web/index.html | 101 + .../a_re-introduction_to_javascript/index.html | 910 ++++++ .../web/javascript/about_javascript/index.html | 69 + files/zh-tw/web/javascript/closures/index.html | 396 +++ .../web/javascript/data_structures/index.html | 294 ++ .../index.html | 259 ++ .../equality_comparisons_and_sameness/index.html | 431 +++ files/zh-tw/web/javascript/eventloop/index.html | 109 + .../control_flow_and_error_handling/index.html | 429 +++ .../guide/details_of_the_object_model/index.html | 720 +++++ .../guide/expressions_and_operators/index.html | 934 ++++++ .../web/javascript/guide/functions/index.html | 442 +++ .../javascript/guide/grammar_and_types/index.html | 697 +++++ files/zh-tw/web/javascript/guide/index.html | 116 + .../guide/indexed_collections/index.html | 450 +++ .../web/javascript/guide/introduction/index.html | 180 ++ .../guide/iterators_and_generators/index.html | 193 ++ .../javascript/guide/keyed_collections/index.html | 156 + .../guide/loops_and_iteration/index.html | 337 ++ .../javascript/guide/numbers_and_dates/index.html | 383 +++ .../guide/regular_expressions/index.html | 700 +++++ .../web/javascript/guide/using_promises/index.html | 256 ++ .../guide/working_with_objects/index.html | 499 +++ files/zh-tw/web/javascript/index.html | 133 + .../inheritance_and_the_prototype_chain/index.html | 310 ++ .../index.html | 393 +++ .../javascript_technologies_overview/index.html | 80 + .../web/javascript/language_resources/index.html | 77 + .../web/javascript/memory_management/index.html | 204 ++ .../javascript/new_in_javascript/1.1/index.html | 71 + .../javascript/new_in_javascript/1.2/index.html | 89 + .../javascript/new_in_javascript/1.3/index.html | 138 + .../javascript/new_in_javascript/1.4/index.html | 25 + .../javascript/new_in_javascript/1.5/index.html | 37 + .../javascript/new_in_javascript/1.6/index.html | 87 + .../javascript/new_in_javascript/1.7/index.html | 600 ++++ .../javascript/new_in_javascript/1.8.1/index.html | 41 + .../javascript/new_in_javascript/1.8.5/index.html | 132 + .../javascript/new_in_javascript/1.8/index.html | 125 + .../web/javascript/new_in_javascript/index.html | 71 + .../index.html" | 43 + .../index.html" | 11 + .../index.html" | 25 + .../index.html" | 105 + .../index.html" | 87 + .../index.html" | 13 + .../index.html" | 15 + .../index.html" | 18 + .../index.html" | 50 + .../obsolete_pages/unicode/index.html | 32 + .../index.html" | 27 + .../index.html" | 39 + .../throw_\350\252\236\346\263\225/index.html" | 34 + .../index.html" | 162 + .../obsolete_pages/\345\200\274/index.html" | 29 + .../index.html" | 13 + .../index.html" | 44 + .../index.html" | 55 + .../index.html" | 56 + .../index.html" | 40 + .../index.html" | 33 + .../index.html" | 42 + .../index.html" | 33 + .../index.html" | 117 + .../\345\270\270\346\225\270/index.html" | 27 + .../index.html" | 9 + .../break_\350\252\236\346\263\225/index.html" | 27 + .../continue_\350\252\236\346\263\225/index.html" | 49 + .../index.html" | 22 + .../for_\350\252\236\346\263\225/index.html" | 53 + .../index.html" | 15 + .../label_\350\252\236\346\263\225/index.html" | 22 + .../while_\350\252\236\346\263\225/index.html" | 38 + .../index.html" | 110 + .../index.html" | 18 + .../index.html" | 27 + .../index.html" | 21 + .../index.html" | 58 + .../index.html" | 40 + .../index.html" | 23 + .../index.html" | 10 + .../index.html" | 12 + .../index.html" | 103 + .../index.html" | 184 ++ .../index.html" | 34 + .../index.html" | 58 + .../index.html" | 35 + .../index.html" | 42 + .../index.html" | 114 + .../index.html" | 42 + .../index.html" | 53 + .../\347\271\274\346\211\277/index.html" | 146 + .../index.html" | 31 + .../index.html" | 143 + .../index.html" | 14 + .../index.html" | 19 + .../index.html" | 24 + .../index.html" | 135 + .../index.html" | 15 + .../\350\250\273\350\247\243/index.html" | 20 + .../\350\256\212\346\225\270/index.html" | 56 + .../index.html" | 293 ++ .../index.html" | 29 + .../index.html" | 64 + .../index.html" | 30 + .../index.html" | 11 + .../index.html" | 14 + .../index.html" | 185 ++ .../index.html" | 19 + .../index.html" | 42 + .../index.html" | 227 ++ .../\351\227\234\346\226\274/index.html" | 47 + .../index.html" | 451 +++ .../index.html" | 19 + .../eval_\345\207\275\346\225\270/index.html" | 16 + .../index.html" | 14 + .../isfinite_\345\207\275\346\225\270/index.html" | 23 + .../isnan_\345\207\275\346\225\270/index.html" | 25 + .../index.html" | 34 + .../index.html" | 21 + .../array_\347\211\251\344\273\266/index.html" | 151 + .../boolean_\347\211\251\344\273\266/index.html" | 12 + .../date_\347\211\251\344\273\266/index.html" | 82 + .../function_\347\211\251\344\273\266/index.html" | 45 + .../index.html" | 12 + .../math_\347\211\251\344\273\266/index.html" | 69 + .../number_\347\211\251\344\273\266/index.html" | 80 + .../regexp_\347\211\251\344\273\266/index.html" | 9 + .../string_\347\211\251\344\273\266/index.html" | 88 + .../reference/classes/constructor/index.html | 157 + .../reference/classes/extends/index.html | 108 + .../web/javascript/reference/classes/index.html | 362 +++ .../javascript/reference/classes/static/index.html | 123 + .../errors/bad_return_or_yield/index.html | 51 + .../web/javascript/reference/errors/index.html | 22 + .../errors/invalid_array_length/index.html | 74 + .../missing_curly_after_property_list/index.html | 47 + .../reference/errors/no_properties/index.html | 36 + .../reference/errors/not_a_function/index.html | 80 + .../reference/errors/not_defined/index.html | 67 + .../errors/redeclared_parameter/index.html | 57 + .../reference/errors/too_much_recursion/index.html | 50 + .../reference/errors/unexpected_type/index.html | 49 + .../functions/arguments/callee/index.html | 197 ++ .../reference/functions/arguments/index.html | 235 ++ .../reference/functions/arrow_functions/index.html | 340 +++ .../functions/default_parameters/index.html | 292 ++ .../javascript/reference/functions/get/index.html | 170 ++ .../web/javascript/reference/functions/index.html | 617 ++++ .../functions/method_definitions/index.html | 213 ++ .../reference/functions/rest_parameters/index.html | 155 + .../javascript/reference/functions/set/index.html | 138 + .../global_objects/array/@@iterator/index.html | 89 + .../global_objects/array/concat/index.html | 157 + .../global_objects/array/copywithin/index.html | 156 + .../global_objects/array/entries/index.html | 86 + .../global_objects/array/every/index.html | 191 ++ .../reference/global_objects/array/fill/index.html | 156 + .../global_objects/array/filter/index.html | 238 ++ .../reference/global_objects/array/find/index.html | 204 ++ .../global_objects/array/findindex/index.html | 181 ++ .../reference/global_objects/array/flat/index.html | 148 + .../global_objects/array/foreach/index.html | 297 ++ .../reference/global_objects/array/from/index.html | 215 ++ .../global_objects/array/includes/index.html | 175 ++ .../reference/global_objects/array/index.html | 457 +++ .../global_objects/array/indexof/index.html | 260 ++ .../global_objects/array/isarray/index.html | 134 + .../reference/global_objects/array/join/index.html | 109 + .../reference/global_objects/array/keys/index.html | 76 + .../global_objects/array/lastindexof/index.html | 168 + .../global_objects/array/length/index.html | 131 + .../reference/global_objects/array/map/index.html | 320 ++ .../reference/global_objects/array/of/index.html | 98 + .../reference/global_objects/array/pop/index.html | 98 + .../reference/global_objects/array/push/index.html | 143 + .../global_objects/array/reduce/index.html | 472 +++ .../global_objects/array/reverse/index.html | 90 + .../global_objects/array/shift/index.html | 114 + .../global_objects/array/slice/index.html | 242 ++ .../reference/global_objects/array/some/index.html | 217 ++ .../reference/global_objects/array/sort/index.html | 248 ++ .../global_objects/array/splice/index.html | 150 + .../global_objects/array/unshift/index.html | 101 + .../global_objects/array/values/index.html | 77 + .../global_objects/arraybuffer/index.html | 225 ++ .../arraybuffer/prototype/index.html | 110 + .../global_objects/asyncfunction/index.html | 118 + .../reference/global_objects/bigint/index.html | 279 ++ .../reference/global_objects/boolean/index.html | 199 ++ .../reference/global_objects/dataview/index.html | 173 ++ .../global_objects/date/getday/index.html | 72 + .../reference/global_objects/date/index.html | 263 ++ .../reference/global_objects/date/now/index.html | 123 + .../global_objects/date/prototype/index.html | 245 ++ .../reference/global_objects/date/utc/index.html | 157 + .../global_objects/error/columnnumber/index.html | 81 + .../reference/global_objects/error/index.html | 233 ++ .../global_objects/function/apply/index.html | 260 ++ .../global_objects/function/bind/index.html | 321 ++ .../global_objects/function/call/index.html | 105 + .../reference/global_objects/function/index.html | 191 ++ .../global_objects/function/length/index.html | 144 + .../global_objects/function/prototype/index.html | 138 + .../javascript/reference/global_objects/index.html | 201 ++ .../reference/global_objects/infinity/index.html | 76 + .../reference/global_objects/isnan/index.html | 183 ++ .../reference/global_objects/json/index.html | 206 ++ .../reference/global_objects/json/parse/index.html | 170 ++ .../global_objects/json/stringify/index.html | 280 ++ .../reference/global_objects/map/index.html | 265 ++ .../reference/global_objects/math/abs/index.html | 104 + .../reference/global_objects/math/ceil/index.html | 170 ++ .../reference/global_objects/math/floor/index.html | 169 + .../reference/global_objects/math/index.html | 196 ++ .../reference/global_objects/math/max/index.html | 117 + .../reference/global_objects/math/pow/index.html | 107 + .../global_objects/math/random/index.html | 95 + .../reference/global_objects/math/round/index.html | 212 ++ .../reference/global_objects/nan/index.html | 85 + .../reference/global_objects/null/index.html | 124 + .../reference/global_objects/number/index.html | 219 ++ .../global_objects/number/isfinite/index.html | 93 + .../global_objects/number/isnan/index.html | 99 + .../global_objects/number/prototype/index.html | 84 + .../global_objects/number/toexponential/index.html | 164 + .../global_objects/number/tofixed/index.html | 108 + .../global_objects/object/assign/index.html | 249 ++ .../global_objects/object/create/index.html | 258 ++ .../object/defineproperties/index.html | 224 ++ .../object/defineproperty/index.html | 380 +++ .../global_objects/object/freeze/index.html | 198 ++ .../object/getprototypeof/index.html | 128 + .../object/hasownproperty/index.html | 184 ++ .../reference/global_objects/object/index.html | 222 ++ .../global_objects/object/keys/index.html | 208 ++ .../object/preventextensions/index.html | 179 ++ .../global_objects/object/proto/index.html | 137 + .../global_objects/object/prototype/index.html | 218 ++ .../global_objects/object/watch/index.html | 191 ++ .../reference/global_objects/parseint/index.html | 193 ++ .../global_objects/promise/all/index.html | 207 ++ .../global_objects/promise/catch/index.html | 189 ++ .../global_objects/promise/finally/index.html | 102 + .../reference/global_objects/promise/index.html | 256 ++ .../global_objects/promise/prototype/index.html | 64 + .../global_objects/promise/race/index.html | 171 ++ .../global_objects/promise/reject/index.html | 72 + .../global_objects/promise/resolve/index.html | 142 + .../global_objects/promise/then/index.html | 271 ++ .../reference/global_objects/proxy/index.html | 400 +++ .../reference/global_objects/rangeerror/index.html | 152 + .../reference/global_objects/reflect/index.html | 130 + .../reference/global_objects/regexp/index.html | 269 ++ .../reference/global_objects/set/add/index.html | 83 + .../reference/global_objects/set/clear/index.html | 79 + .../reference/global_objects/set/delete/index.html | 98 + .../global_objects/set/entries/index.html | 78 + .../reference/global_objects/set/has/index.html | 92 + .../reference/global_objects/set/index.html | 243 ++ .../reference/global_objects/set/values/index.html | 79 + .../reference/global_objects/string/index.html | 328 ++ .../global_objects/string/match/index.html | 151 + .../global_objects/string/padstart/index.html | 96 + .../global_objects/string/prototype/index.html | 176 ++ .../global_objects/string/replace/index.html | 286 ++ .../global_objects/string/tolowercase/index.html | 77 + .../reference/global_objects/typedarray/index.html | 268 ++ .../reference/global_objects/undefined/index.html | 136 + .../reference/global_objects/urierror/index.html | 131 + files/zh-tw/web/javascript/reference/index.html | 300 ++ .../reference/iteration_protocols/index.html | 351 +++ .../reference/lexical_grammar/index.html | 548 ++++ .../operators/arithmetic_operators/index.html | 308 ++ .../reference/operators/async_function/index.html | 111 + .../reference/operators/await/index.html | 152 + .../operators/bitwise_operators/index.html | 554 ++++ .../reference/operators/comma_operator/index.html | 145 + .../operators/comparison_operators/index.html | 283 ++ .../operators/conditional_operator/index.html | 101 + .../operators/destructuring_assignment/index.html | 423 +++ .../web/javascript/reference/operators/index.html | 301 ++ .../operators/logical_operators/index.html | 243 ++ .../operators/object_initializer/index.html | 431 +++ .../operators/operator_precedence/index.html | 316 ++ .../operators/optional_chaining/index.html | 195 ++ .../reference/operators/spread_syntax/index.html | 248 ++ .../reference/operators/super/index.html | 179 ++ .../javascript/reference/operators/this/index.html | 385 +++ .../reference/operators/typeof/index.html | 177 ++ .../reference/statements/async_function/index.html | 163 + .../reference/statements/block/index.html | 86 + .../reference/statements/break/index.html | 120 + .../reference/statements/const/index.html | 129 + .../reference/statements/debugger/index.html | 75 + .../reference/statements/export/index.html | 165 + .../reference/statements/for...in/index.html | 116 + .../reference/statements/function_star_/index.html | 207 ++ .../reference/statements/if...else/index.html | 169 + .../reference/statements/import/index.html | 203 ++ .../web/javascript/reference/statements/index.html | 147 + .../reference/statements/label/index.html | 203 ++ .../javascript/reference/statements/let/index.html | 246 ++ .../reference/statements/return/index.html | 156 + .../reference/statements/switch/index.html | 309 ++ .../reference/statements/throw/index.html | 234 ++ .../javascript/reference/statements/var/index.html | 248 ++ .../javascript/reference/strict_mode/index.html | 369 +++ .../reference/template_literals/index.html | 252 ++ files/zh-tw/web/javascript/shells/index.html | 42 + files/zh-tw/web/javascript/typed_arrays/index.html | 227 ++ files/zh-tw/web/manifest/index.html | 327 ++ files/zh-tw/web/mathml/authoring/index.html | 285 ++ files/zh-tw/web/mathml/index.html | 107 + .../zh-tw/web/media/formats/containers/index.html | 1325 ++++++++ files/zh-tw/web/media/formats/index.html | 88 + files/zh-tw/web/media/index.html | 64 + files/zh-tw/web/opensearch/index.html | 179 ++ files/zh-tw/web/progressive_web_apps/index.html | 77 + files/zh-tw/web/reference/api/index.html | 59 + files/zh-tw/web/reference/index.html | 29 + files/zh-tw/web/security/index.html | 16 + .../web/security/insecure_passwords/index.html | 76 + .../index.html | 29 + files/zh-tw/web/security/mixed_content/index.html | 80 + .../web/security/same-origin_policy/index.html | 117 + .../security/weak_signature_algorithm/index.html | 16 + files/zh-tw/web/svg/attribute/fill-rule/index.html | 46 + files/zh-tw/web/svg/attribute/index.html | 386 +++ .../web/svg/attribute/stroke-dashoffset/index.html | 75 + files/zh-tw/web/svg/index.html | 22 + .../web/svg/tutorial/fills_and_strokes/index.html | 184 ++ .../web/svg/tutorial/getting_started/index.html | 91 + files/zh-tw/web/svg/tutorial/gradients/index.html | 148 + files/zh-tw/web/svg/tutorial/index.html | 51 + .../zh-tw/web/svg/tutorial/introduction/index.html | 26 + files/zh-tw/web/svg/tutorial/patterns/index.html | 54 + files/zh-tw/web/svg/tutorial/positions/index.html | 51 + .../tutorial/\350\267\257\345\276\204/index.html" | 239 ++ .../web/svg/\346\225\231\345\255\270/index.html" | 13 + files/zh-tw/web/tutorials/index.html | 247 ++ .../zh-tw/web/\346\200\247\350\203\275/index.html" | 481 +++ 825 files changed, 140719 insertions(+) create mode 100644 files/zh-tw/web/accessibility/aria/aria_techniques/index.html create mode 100644 files/zh-tw/web/accessibility/aria/forms/basic_form_hints/index.html create mode 100644 files/zh-tw/web/accessibility/aria/forms/index.html create mode 100644 files/zh-tw/web/accessibility/aria/index.html create mode 100644 files/zh-tw/web/accessibility/index.html create mode 100644 files/zh-tw/web/accessibility/mobile_accessibility_checklist/index.html create mode 100644 files/zh-tw/web/api/abortcontroller/index.html create mode 100644 files/zh-tw/web/api/ambient_light_events/index.html create mode 100644 files/zh-tw/web/api/analysernode/getbytefrequencydata/index.html create mode 100644 files/zh-tw/web/api/analysernode/index.html create mode 100644 files/zh-tw/web/api/animationevent/index.html create mode 100644 files/zh-tw/web/api/animationevent/initanimationevent/index.html create mode 100644 files/zh-tw/web/api/battery_status_api/index.html create mode 100644 files/zh-tw/web/api/blob/blob/index.html create mode 100644 files/zh-tw/web/api/blob/index.html create mode 100644 files/zh-tw/web/api/blob/size/index.html create mode 100644 files/zh-tw/web/api/blob/type/index.html create mode 100644 files/zh-tw/web/api/body/index.html create mode 100644 files/zh-tw/web/api/body/json/index.html create mode 100644 files/zh-tw/web/api/canvas_api/drawing_graphics_with_canvas/index.html create mode 100644 files/zh-tw/web/api/canvas_api/index.html create mode 100644 files/zh-tw/web/api/canvas_api/tutorial/advanced_animations/index.html create mode 100644 files/zh-tw/web/api/canvas_api/tutorial/applying_styles_and_colors/index.html create mode 100644 files/zh-tw/web/api/canvas_api/tutorial/basic_animations/index.html create mode 100644 files/zh-tw/web/api/canvas_api/tutorial/basic_usage/index.html create mode 100644 files/zh-tw/web/api/canvas_api/tutorial/compositing/index.html create mode 100644 files/zh-tw/web/api/canvas_api/tutorial/drawing_shapes/index.html create mode 100644 files/zh-tw/web/api/canvas_api/tutorial/drawing_text/index.html create mode 100644 files/zh-tw/web/api/canvas_api/tutorial/index.html create mode 100644 files/zh-tw/web/api/canvas_api/tutorial/optimizing_canvas/index.html create mode 100644 files/zh-tw/web/api/canvas_api/tutorial/pixel_manipulation_with_canvas/index.html create mode 100644 files/zh-tw/web/api/canvas_api/tutorial/transformations/index.html create mode 100644 files/zh-tw/web/api/canvas_api/tutorial/using_images/index.html create mode 100644 files/zh-tw/web/api/canvasrenderingcontext2d/clearrect/index.html create mode 100644 files/zh-tw/web/api/canvasrenderingcontext2d/index.html create mode 100644 files/zh-tw/web/api/channel_messaging_api/index.html create mode 100644 files/zh-tw/web/api/characterdata/index.html create mode 100644 files/zh-tw/web/api/childnode/index.html create mode 100644 files/zh-tw/web/api/clients/index.html create mode 100644 files/zh-tw/web/api/clipboardevent/index.html create mode 100644 files/zh-tw/web/api/console/assert/index.html create mode 100644 files/zh-tw/web/api/console/index.html create mode 100644 files/zh-tw/web/api/css_object_model/determining_the_dimensions_of_elements/index.html create mode 100644 files/zh-tw/web/api/css_object_model/index.html create mode 100644 files/zh-tw/web/api/css_object_model/managing_screen_orientation/index.html create mode 100644 files/zh-tw/web/api/css_object_model/using_dynamic_styling_information/index.html create mode 100644 files/zh-tw/web/api/cssstyledeclaration/index.html create mode 100644 files/zh-tw/web/api/cssstylesheet/index.html create mode 100644 files/zh-tw/web/api/cssstylesheet/insertrule/index.html create mode 100644 files/zh-tw/web/api/customevent/customevent/index.html create mode 100644 files/zh-tw/web/api/customevent/index.html create mode 100644 files/zh-tw/web/api/datatransfer/index.html create mode 100644 files/zh-tw/web/api/detecting_device_orientation/index.html create mode 100644 files/zh-tw/web/api/devicemotionevent/index.html create mode 100644 files/zh-tw/web/api/deviceorientationevent/index.html create mode 100644 files/zh-tw/web/api/document.createtreewalker/index.html create mode 100644 files/zh-tw/web/api/document/body/index.html create mode 100644 files/zh-tw/web/api/document/createdocumentfragment/index.html create mode 100644 files/zh-tw/web/api/document/createelement/index.html create mode 100644 files/zh-tw/web/api/document/createrange/index.html create mode 100644 files/zh-tw/web/api/document/createtextnode/index.html create mode 100644 files/zh-tw/web/api/document/defaultview/index.html create mode 100644 files/zh-tw/web/api/document/designmode/index.html create mode 100644 files/zh-tw/web/api/document/documentelement/index.html create mode 100644 files/zh-tw/web/api/document/execcommand/index.html create mode 100644 files/zh-tw/web/api/document/forms/index.html create mode 100644 files/zh-tw/web/api/document/getelementsbyclassname/index.html create mode 100644 files/zh-tw/web/api/document/head/index.html create mode 100644 files/zh-tw/web/api/document/index.html create mode 100644 files/zh-tw/web/api/document/keyup_event/index.html create mode 100644 files/zh-tw/web/api/document/queryselector/index.html create mode 100644 files/zh-tw/web/api/document/readystate/index.html create mode 100644 files/zh-tw/web/api/document/registerelement/index.html create mode 100644 files/zh-tw/web/api/document/scroll_event/index.html create mode 100644 files/zh-tw/web/api/document/width/index.html create mode 100644 files/zh-tw/web/api/document_object_model/examples/index.html create mode 100644 files/zh-tw/web/api/document_object_model/how_to_create_a_dom_tree/index.html create mode 100644 files/zh-tw/web/api/document_object_model/index.html create mode 100644 files/zh-tw/web/api/document_object_model/whitespace/index.html create mode 100644 "files/zh-tw/web/api/document_object_model/\344\272\213\344\273\266/index.html" create mode 100644 files/zh-tw/web/api/documentfragment/index.html create mode 100644 files/zh-tw/web/api/documenttype/index.html create mode 100644 files/zh-tw/web/api/domparser/index.html create mode 100644 files/zh-tw/web/api/domstring/index.html create mode 100644 files/zh-tw/web/api/domtokenlist/index.html create mode 100644 files/zh-tw/web/api/dragevent/datatransfer/index.html create mode 100644 files/zh-tw/web/api/dragevent/index.html create mode 100644 files/zh-tw/web/api/element/attributes/index.html create mode 100644 files/zh-tw/web/api/element/classlist/index.html create mode 100644 files/zh-tw/web/api/element/click_event/index.html create mode 100644 files/zh-tw/web/api/element/clientheight/index.html create mode 100644 files/zh-tw/web/api/element/getattribute/index.html create mode 100644 files/zh-tw/web/api/element/index.html create mode 100644 files/zh-tw/web/api/element/innerhtml/index.html create mode 100644 files/zh-tw/web/api/element/insertadjacenthtml/index.html create mode 100644 files/zh-tw/web/api/element/queryselectorall/index.html create mode 100644 files/zh-tw/web/api/element/scrollheight/index.html create mode 100644 files/zh-tw/web/api/element/scrolltop/index.html create mode 100644 files/zh-tw/web/api/element/touchcancel_event/index.html create mode 100644 files/zh-tw/web/api/errorevent/index.html create mode 100644 files/zh-tw/web/api/event/bubbles/index.html create mode 100644 files/zh-tw/web/api/event/comparison_of_event_targets/index.html create mode 100644 files/zh-tw/web/api/event/createevent/index.html create mode 100644 files/zh-tw/web/api/event/currenttarget/index.html create mode 100644 files/zh-tw/web/api/event/defaultprevented/index.html create mode 100644 files/zh-tw/web/api/event/event/index.html create mode 100644 files/zh-tw/web/api/event/eventphase/index.html create mode 100644 files/zh-tw/web/api/event/index.html create mode 100644 files/zh-tw/web/api/event/istrusted/index.html create mode 100644 files/zh-tw/web/api/event/preventdefault/index.html create mode 100644 files/zh-tw/web/api/event/stopimmediatepropagation/index.html create mode 100644 files/zh-tw/web/api/event/stoppropagation/index.html create mode 100644 files/zh-tw/web/api/event/target/index.html create mode 100644 files/zh-tw/web/api/event/timestamp/index.html create mode 100644 files/zh-tw/web/api/event/type/index.html create mode 100644 files/zh-tw/web/api/eventlistener/index.html create mode 100644 files/zh-tw/web/api/eventtarget/dispatchevent/index.html create mode 100644 files/zh-tw/web/api/eventtarget/index.html create mode 100644 files/zh-tw/web/api/eventtarget/removeeventlistener/index.html create mode 100644 files/zh-tw/web/api/fetch_api/index.html create mode 100644 files/zh-tw/web/api/fetch_api/using_fetch/index.html create mode 100644 files/zh-tw/web/api/file/file/index.html create mode 100644 files/zh-tw/web/api/file/filename/index.html create mode 100644 files/zh-tw/web/api/file/index.html create mode 100644 files/zh-tw/web/api/file/using_files_from_web_applications/index.html create mode 100644 files/zh-tw/web/api/file_handle_api/index.html create mode 100644 files/zh-tw/web/api/filelist/index.html create mode 100644 files/zh-tw/web/api/filereader/error/index.html create mode 100644 files/zh-tw/web/api/filereader/index.html create mode 100644 files/zh-tw/web/api/filereader/readystate/index.html create mode 100644 files/zh-tw/web/api/filesystem/index.html create mode 100644 files/zh-tw/web/api/formdata/get/index.html create mode 100644 files/zh-tw/web/api/formdata/index.html create mode 100644 files/zh-tw/web/api/formdata/using_formdata_objects/index.html create mode 100644 files/zh-tw/web/api/fullscreen_api/index.html create mode 100644 files/zh-tw/web/api/gainnode/gain/index.html create mode 100644 files/zh-tw/web/api/gainnode/index.html create mode 100644 files/zh-tw/web/api/geolocation/clearwatch/index.html create mode 100644 files/zh-tw/web/api/geolocation/getcurrentposition/index.html create mode 100644 files/zh-tw/web/api/geolocation/index.html create mode 100644 files/zh-tw/web/api/geolocation/using_geolocation/index.html create mode 100644 files/zh-tw/web/api/geolocation/watchposition/index.html create mode 100644 files/zh-tw/web/api/geolocationcoordinates/accuracy/index.html create mode 100644 files/zh-tw/web/api/geolocationcoordinates/altitude/index.html create mode 100644 files/zh-tw/web/api/geolocationcoordinates/altitudeaccuracy/index.html create mode 100644 files/zh-tw/web/api/geolocationcoordinates/heading/index.html create mode 100644 files/zh-tw/web/api/geolocationcoordinates/index.html create mode 100644 files/zh-tw/web/api/geolocationcoordinates/latitude/index.html create mode 100644 files/zh-tw/web/api/geolocationcoordinates/longitude/index.html create mode 100644 files/zh-tw/web/api/geolocationcoordinates/speed/index.html create mode 100644 files/zh-tw/web/api/geolocationposition/coords/index.html create mode 100644 files/zh-tw/web/api/geolocationposition/index.html create mode 100644 files/zh-tw/web/api/geolocationposition/timestamp/index.html create mode 100644 files/zh-tw/web/api/geolocationpositionerror/code/index.html create mode 100644 files/zh-tw/web/api/geolocationpositionerror/index.html create mode 100644 files/zh-tw/web/api/geolocationpositionerror/message/index.html create mode 100644 files/zh-tw/web/api/globaleventhandlers/index.html create mode 100644 files/zh-tw/web/api/globaleventhandlers/onclick/index.html create mode 100644 files/zh-tw/web/api/globaleventhandlers/onclose/index.html create mode 100644 files/zh-tw/web/api/history/index.html create mode 100644 files/zh-tw/web/api/history_api/index.html create mode 100644 files/zh-tw/web/api/html_drag_and_drop_api/drag_operations/index.html create mode 100644 files/zh-tw/web/api/html_drag_and_drop_api/index.html create mode 100644 files/zh-tw/web/api/htmlcanvaselement/index.html create mode 100644 files/zh-tw/web/api/htmlcanvaselement/todataurl/index.html create mode 100644 files/zh-tw/web/api/htmlcollection/index.html create mode 100644 files/zh-tw/web/api/htmldataelement/index.html create mode 100644 files/zh-tw/web/api/htmldocument/index.html create mode 100644 files/zh-tw/web/api/htmlelement/click/index.html create mode 100644 files/zh-tw/web/api/htmlelement/dataset/index.html create mode 100644 files/zh-tw/web/api/htmlelement/index.html create mode 100644 files/zh-tw/web/api/htmlelement/lang/index.html create mode 100644 files/zh-tw/web/api/htmlelement/style/index.html create mode 100644 files/zh-tw/web/api/htmlformelement/index.html create mode 100644 files/zh-tw/web/api/htmlformelement/submit_event/index.html create mode 100644 files/zh-tw/web/api/htmlimageelement/index.html create mode 100644 files/zh-tw/web/api/htmlinputelement/index.html create mode 100644 files/zh-tw/web/api/htmlmediaelement/index.html create mode 100644 files/zh-tw/web/api/htmlmediaelement/ratechange_event/index.html create mode 100644 files/zh-tw/web/api/htmlmediaelement/readystate/index.html create mode 100644 files/zh-tw/web/api/htmlselectelement/checkvalidity/index.html create mode 100644 files/zh-tw/web/api/htmlselectelement/index.html create mode 100644 files/zh-tw/web/api/htmlselectelement/setcustomvalidity/index.html create mode 100644 files/zh-tw/web/api/idbdatabase/index.html create mode 100644 files/zh-tw/web/api/index.html create mode 100644 files/zh-tw/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html create mode 100644 files/zh-tw/web/api/indexeddb_api/index.html create mode 100644 files/zh-tw/web/api/indexeddb_api/using_indexeddb/index.html create mode 100644 files/zh-tw/web/api/keyboardevent/index.html create mode 100644 files/zh-tw/web/api/keyboardevent/keyboardevent/index.html create mode 100644 files/zh-tw/web/api/media_streams_api/index.html create mode 100644 files/zh-tw/web/api/mediaquerylist/index.html create mode 100644 files/zh-tw/web/api/mediasource/activesourcebuffers/index.html create mode 100644 files/zh-tw/web/api/mediasource/duration/index.html create mode 100644 files/zh-tw/web/api/mediasource/index.html create mode 100644 files/zh-tw/web/api/mediasource/mediasource/index.html create mode 100644 files/zh-tw/web/api/mediasource/readystate/index.html create mode 100644 files/zh-tw/web/api/mouseevent/index.html create mode 100644 files/zh-tw/web/api/mutationobserver/index.html create mode 100644 files/zh-tw/web/api/namednodemap/index.html create mode 100644 files/zh-tw/web/api/navigator/geolocation/index.html create mode 100644 files/zh-tw/web/api/navigator/index.html create mode 100644 files/zh-tw/web/api/navigator/registerprotocolhandler/index.html create mode 100644 files/zh-tw/web/api/navigator/registerprotocolhandler/web-based_protocol_handlers/index.html create mode 100644 files/zh-tw/web/api/navigatoronline/index.html create mode 100644 files/zh-tw/web/api/navigatoronline/online_and_offline_events/index.html create mode 100644 files/zh-tw/web/api/network_information_api/index.html create mode 100644 files/zh-tw/web/api/node/childnodes/index.html create mode 100644 files/zh-tw/web/api/node/clonenode/index.html create mode 100644 files/zh-tw/web/api/node/index.html create mode 100644 files/zh-tw/web/api/node/innertext/index.html create mode 100644 files/zh-tw/web/api/node/insertbefore/index.html create mode 100644 files/zh-tw/web/api/node/nodename/index.html create mode 100644 files/zh-tw/web/api/node/nodetype/index.html create mode 100644 files/zh-tw/web/api/node/ownerdocument/index.html create mode 100644 files/zh-tw/web/api/node/removechild/index.html create mode 100644 files/zh-tw/web/api/node/textcontent/index.html create mode 100644 files/zh-tw/web/api/nodelist/index.html create mode 100644 files/zh-tw/web/api/nondocumenttypechildnode/index.html create mode 100644 files/zh-tw/web/api/notification/index.html create mode 100644 files/zh-tw/web/api/notifications_api/index.html create mode 100644 files/zh-tw/web/api/notifications_api/using_the_notifications_api/index.html create mode 100644 files/zh-tw/web/api/parentnode/children/index.html create mode 100644 files/zh-tw/web/api/parentnode/firstelementchild/index.html create mode 100644 files/zh-tw/web/api/parentnode/index.html create mode 100644 files/zh-tw/web/api/payment_request_api/index.html create mode 100644 files/zh-tw/web/api/paymentrequest/index.html create mode 100644 files/zh-tw/web/api/performance.timing/index.html create mode 100644 files/zh-tw/web/api/performance/index.html create mode 100644 files/zh-tw/web/api/pointer_lock_api/index.html create mode 100644 files/zh-tw/web/api/positionoptions/enablehighaccuracy/index.html create mode 100644 files/zh-tw/web/api/positionoptions/index.html create mode 100644 files/zh-tw/web/api/positionoptions/maximumage/index.html create mode 100644 files/zh-tw/web/api/positionoptions/timeout/index.html create mode 100644 files/zh-tw/web/api/progressevent/index.html create mode 100644 files/zh-tw/web/api/proximity_events/index.html create mode 100644 files/zh-tw/web/api/range/index.html create mode 100644 files/zh-tw/web/api/response/index.html create mode 100644 files/zh-tw/web/api/screen/index.html create mode 100644 files/zh-tw/web/api/screen/orientation/index.html create mode 100644 files/zh-tw/web/api/server-sent_events/index.html create mode 100644 files/zh-tw/web/api/server-sent_events/using_server-sent_events/index.html create mode 100644 files/zh-tw/web/api/storage/index.html create mode 100644 files/zh-tw/web/api/touch/index.html create mode 100644 files/zh-tw/web/api/touch_events/index.html create mode 100644 files/zh-tw/web/api/touchevent/index.html create mode 100644 files/zh-tw/web/api/touchlist/index.html create mode 100644 files/zh-tw/web/api/uievent/index.html create mode 100644 files/zh-tw/web/api/uievent/uievent/index.html create mode 100644 files/zh-tw/web/api/url/createobjecturl/index.html create mode 100644 files/zh-tw/web/api/url/index.html create mode 100644 files/zh-tw/web/api/validitystate/index.html create mode 100644 files/zh-tw/web/api/vibration_api/index.html create mode 100644 files/zh-tw/web/api/web_audio_api/index.html create mode 100644 files/zh-tw/web/api/web_video_text_tracks_format/index.html create mode 100644 files/zh-tw/web/api/web_workers_api/index.html create mode 100644 files/zh-tw/web/api/web_workers_api/using_web_workers/index.html create mode 100644 files/zh-tw/web/api/webgl_api/index.html create mode 100644 files/zh-tw/web/api/webgl_api/tutorial/adding_2d_content_to_a_webgl_context/index.html create mode 100644 files/zh-tw/web/api/webgl_api/tutorial/animating_objects_with_webgl/index.html create mode 100644 files/zh-tw/web/api/webgl_api/tutorial/getting_started_with_webgl/index.html create mode 100644 files/zh-tw/web/api/webgl_api/tutorial/index.html create mode 100644 files/zh-tw/web/api/webgl_api/tutorial/using_shaders_to_apply_color_in_webgl/index.html create mode 100644 files/zh-tw/web/api/webrtc_api/index.html create mode 100644 files/zh-tw/web/api/webvr_api/index.html create mode 100644 files/zh-tw/web/api/wheelevent/index.html create mode 100644 files/zh-tw/web/api/window.history/index.html create mode 100644 files/zh-tw/web/api/window.onpopstate/index.html create mode 100644 files/zh-tw/web/api/window.requestanimationframe/index.html create mode 100644 files/zh-tw/web/api/window/getcomputedstyle/index.html create mode 100644 files/zh-tw/web/api/window/index.html create mode 100644 files/zh-tw/web/api/window/localstorage/index.html create mode 100644 files/zh-tw/web/api/window/location/index.html create mode 100644 files/zh-tw/web/api/window/navigator/index.html create mode 100644 files/zh-tw/web/api/window/opener/index.html create mode 100644 files/zh-tw/web/api/window/orientationchange_event/index.html create mode 100644 files/zh-tw/web/api/window/print/index.html create mode 100644 files/zh-tw/web/api/window/requestidlecallback/index.html create mode 100644 files/zh-tw/web/api/window/sessionstorage/index.html create mode 100644 files/zh-tw/web/api/window/sidebar/adding_search_engines_from_web_pages/index.html create mode 100644 files/zh-tw/web/api/window/sidebar/index.html create mode 100644 files/zh-tw/web/api/windowbase64/index.html create mode 100644 files/zh-tw/web/api/windoweventhandlers/index.html create mode 100644 files/zh-tw/web/api/windoweventhandlers/onbeforeunload/index.html create mode 100644 files/zh-tw/web/api/windoworworkerglobalscope/btoa/index.html create mode 100644 files/zh-tw/web/api/windoworworkerglobalscope/index.html create mode 100644 files/zh-tw/web/api/windoworworkerglobalscope/setinterval/index.html create mode 100644 files/zh-tw/web/api/windowtimers/index.html create mode 100644 files/zh-tw/web/api/xmlhttprequest/index.html create mode 100644 files/zh-tw/web/api/xmlhttprequest/onreadystatechange/index.html create mode 100644 files/zh-tw/web/api/xmlhttprequest/readystate/index.html create mode 100644 files/zh-tw/web/api/xmlhttprequest/setrequestheader/index.html create mode 100644 files/zh-tw/web/api/xmlhttprequest/status/index.html create mode 100644 files/zh-tw/web/api/xmlhttprequest/synchronous_and_asynchronous_requests/index.html create mode 100644 files/zh-tw/web/api/xmlhttprequest/using_xmlhttprequest/index.html create mode 100644 files/zh-tw/web/api/xmlhttprequest/withcredentials/index.html create mode 100644 files/zh-tw/web/api/xmlhttprequest/xmlhttprequest/index.html create mode 100644 files/zh-tw/web/api/xmlhttprequesteventtarget/index.html create mode 100644 files/zh-tw/web/css/@font-face/index.html create mode 100644 files/zh-tw/web/css/@media/height/index.html create mode 100644 files/zh-tw/web/css/@media/index.html create mode 100644 files/zh-tw/web/css/@viewport/height/index.html create mode 100644 files/zh-tw/web/css/@viewport/index.html create mode 100644 files/zh-tw/web/css/_colon_first-child/index.html create mode 100644 files/zh-tw/web/css/_colon_first-of-type/index.html create mode 100644 files/zh-tw/web/css/_colon_lang/index.html create mode 100644 files/zh-tw/web/css/_colon_target/index.html create mode 100644 files/zh-tw/web/css/_doublecolon_first-letter/index.html create mode 100644 files/zh-tw/web/css/animation-fill-mode/index.html create mode 100644 files/zh-tw/web/css/attr()/index.html create mode 100644 files/zh-tw/web/css/background-attachment/index.html create mode 100644 files/zh-tw/web/css/background-color/index.html create mode 100644 files/zh-tw/web/css/border-image/border-image/index.html create mode 100644 files/zh-tw/web/css/border-image/index.html create mode 100644 files/zh-tw/web/css/border/index.html create mode 100644 files/zh-tw/web/css/box-shadow/index.html create mode 100644 files/zh-tw/web/css/box-sizing/index.html create mode 100644 files/zh-tw/web/css/clip/index.html create mode 100644 files/zh-tw/web/css/common_css_questions/index.html create mode 100644 files/zh-tw/web/css/css_animations/index.html create mode 100644 files/zh-tw/web/css/css_animations/using_css_animations/index.html create mode 100644 files/zh-tw/web/css/css_background_and_borders/index.html create mode 100644 files/zh-tw/web/css/css_background_and_borders/using_css_multiple_backgrounds/index.html create mode 100644 files/zh-tw/web/css/css_box_model/index.html create mode 100644 files/zh-tw/web/css/css_box_model/mastering_margin_collapsing/index.html create mode 100644 files/zh-tw/web/css/css_colors/color_picker_tool/index.html create mode 100644 files/zh-tw/web/css/css_colors/index.html create mode 100644 files/zh-tw/web/css/css_flexible_box_layout/index.html create mode 100644 files/zh-tw/web/css/css_flexible_box_layout/using_css_flexible_boxes/index.html create mode 100644 files/zh-tw/web/css/css_grid_layout/basic_concepts_of_grid_layout/index.html create mode 100644 files/zh-tw/web/css/css_grid_layout/index.html create mode 100644 files/zh-tw/web/css/css_lists_and_counters/consistent_list_indentation/index.html create mode 100644 files/zh-tw/web/css/css_lists_and_counters/index.html create mode 100644 files/zh-tw/web/css/css_positioning/index.html create mode 100644 files/zh-tw/web/css/css_positioning/understanding_z_index/index.html create mode 100644 files/zh-tw/web/css/css_positioning/understanding_z_index/stacking_context_example_1/index.html create mode 100644 files/zh-tw/web/css/css_properties_reference/index.html create mode 100644 files/zh-tw/web/css/css_selectors/index.html create mode 100644 files/zh-tw/web/css/css_selectors/using_the__colon_target_pseudo-class_in_selectors/index.html create mode 100644 files/zh-tw/web/css/css_transitions/index.html create mode 100644 files/zh-tw/web/css/css_transitions/using_css_transitions/index.html create mode 100644 files/zh-tw/web/css/cursor/index.html create mode 100644 files/zh-tw/web/css/descendant_combinator/index.html create mode 100644 files/zh-tw/web/css/grid-row/index.html create mode 100644 files/zh-tw/web/css/grid-template-columns/index.html create mode 100644 files/zh-tw/web/css/grid-template/index.html create mode 100644 files/zh-tw/web/css/height/index.html create mode 100644 files/zh-tw/web/css/ime-mode/index.html create mode 100644 files/zh-tw/web/css/index.html create mode 100644 files/zh-tw/web/css/inheritance/index.html create mode 100644 files/zh-tw/web/css/line-break/index.html create mode 100644 files/zh-tw/web/css/media_queries/index.html create mode 100644 files/zh-tw/web/css/media_queries/testing_media_queries/index.html create mode 100644 files/zh-tw/web/css/object-fit/index.html create mode 100644 files/zh-tw/web/css/pseudo-classes/index.html create mode 100644 files/zh-tw/web/css/radial-gradient()/index.html create mode 100644 files/zh-tw/web/css/reference/index.html create mode 100644 files/zh-tw/web/css/replaced_element/index.html create mode 100644 files/zh-tw/web/css/ruby-position/index.html create mode 100644 files/zh-tw/web/css/shorthand_properties/index.html create mode 100644 files/zh-tw/web/css/syntax/index.html create mode 100644 files/zh-tw/web/css/transform-function/index.html create mode 100644 files/zh-tw/web/css/transform-function/translate3d()/index.html create mode 100644 files/zh-tw/web/css/transform-origin/index.html create mode 100644 files/zh-tw/web/css/transform/index.html create mode 100644 files/zh-tw/web/css/transition-duration/index.html create mode 100644 files/zh-tw/web/css/transition-timing-function/index.html create mode 100644 files/zh-tw/web/css/transition/index.html create mode 100644 files/zh-tw/web/css/type_selectors/index.html create mode 100644 files/zh-tw/web/css/white-space/index.html create mode 100644 files/zh-tw/web/css/width/index.html create mode 100644 files/zh-tw/web/demos_of_open_web_technologies/index.html create mode 100644 files/zh-tw/web/events/abort/index.html create mode 100644 files/zh-tw/web/events/domcontentloaded/index.html create mode 100644 files/zh-tw/web/events/index.html create mode 100644 files/zh-tw/web/events/load/index.html create mode 100644 files/zh-tw/web/guide/ajax/getting_started/index.html create mode 100644 files/zh-tw/web/guide/ajax/index.html create mode 100644 files/zh-tw/web/guide/api/index.html create mode 100644 files/zh-tw/web/guide/dom/index.html create mode 100644 files/zh-tw/web/guide/events/creating_and_triggering_events/index.html create mode 100644 files/zh-tw/web/guide/events/event_handlers/index.html create mode 100644 files/zh-tw/web/guide/events/index.html create mode 100644 files/zh-tw/web/guide/graphics/index.html create mode 100644 files/zh-tw/web/guide/html/content_categories/index.html create mode 100644 files/zh-tw/web/guide/html/event_attributes/index.html create mode 100644 files/zh-tw/web/guide/html/html5/index.html create mode 100644 files/zh-tw/web/guide/html/html5/introduction_to_html5/index.html create mode 100644 files/zh-tw/web/guide/index.html create mode 100644 files/zh-tw/web/guide/introduction_to_web_development/index.html create mode 100644 files/zh-tw/web/guide/performance/index.html create mode 100644 files/zh-tw/web/guide/woff/index.html create mode 100644 files/zh-tw/web/guide/writing_forward-compatible_websites/index.html create mode 100644 files/zh-tw/web/html/applying_color/index.html create mode 100644 files/zh-tw/web/html/attributes/index.html create mode 100644 files/zh-tw/web/html/block-level_elements/index.html create mode 100644 files/zh-tw/web/html/element/a/index.html create mode 100644 files/zh-tw/web/html/element/blink/index.html create mode 100644 files/zh-tw/web/html/element/blockquote/index.html create mode 100644 files/zh-tw/web/html/element/br/index.html create mode 100644 files/zh-tw/web/html/element/button/index.html create mode 100644 files/zh-tw/web/html/element/canvas/index.html create mode 100644 files/zh-tw/web/html/element/code/index.html create mode 100644 files/zh-tw/web/html/element/div/index.html create mode 100644 files/zh-tw/web/html/element/font/index.html create mode 100644 files/zh-tw/web/html/element/form/index.html create mode 100644 files/zh-tw/web/html/element/frameset/index.html create mode 100644 files/zh-tw/web/html/element/hr/index.html create mode 100644 files/zh-tw/web/html/element/index.html create mode 100644 files/zh-tw/web/html/element/input/index.html create mode 100644 files/zh-tw/web/html/element/input/submit/index.html create mode 100644 files/zh-tw/web/html/element/marquee/index.html create mode 100644 files/zh-tw/web/html/element/meter/index.html create mode 100644 files/zh-tw/web/html/element/nav/index.html create mode 100644 files/zh-tw/web/html/element/optgroup/index.html create mode 100644 files/zh-tw/web/html/element/picture/index.html create mode 100644 files/zh-tw/web/html/element/q/index.html create mode 100644 files/zh-tw/web/html/element/ruby/index.html create mode 100644 files/zh-tw/web/html/element/script/index.html create mode 100644 files/zh-tw/web/html/element/summary/index.html create mode 100644 files/zh-tw/web/html/element/table/index.html create mode 100644 files/zh-tw/web/html/element/template/index.html create mode 100644 files/zh-tw/web/html/element/time/index.html create mode 100644 files/zh-tw/web/html/forms_in_html/index.html create mode 100644 files/zh-tw/web/html/global_attributes/data-_star_/index.html create mode 100644 files/zh-tw/web/html/global_attributes/index.html create mode 100644 files/zh-tw/web/html/global_attributes/spellcheck/index.html create mode 100644 files/zh-tw/web/html/index.html create mode 100644 files/zh-tw/web/html/quirks_mode_and_standards_mode/index.html create mode 100644 files/zh-tw/web/html/reference/index.html create mode 100644 files/zh-tw/web/html/supported_media_formats/index.html create mode 100644 files/zh-tw/web/html/using_the_application_cache/index.html create mode 100644 files/zh-tw/web/http/authentication/index.html create mode 100644 files/zh-tw/web/http/basics_of_http/index.html create mode 100644 files/zh-tw/web/http/basics_of_http/mime_types/index.html create mode 100644 files/zh-tw/web/http/browser_detection_using_the_user_agent/index.html create mode 100644 files/zh-tw/web/http/caching/index.html create mode 100644 files/zh-tw/web/http/cookies/index.html create mode 100644 files/zh-tw/web/http/cors/errors/corsdidnotsucceed/index.html create mode 100644 files/zh-tw/web/http/cors/errors/corsmissingalloworigin/index.html create mode 100644 files/zh-tw/web/http/cors/errors/corsnotsupportingcredentials/index.html create mode 100644 files/zh-tw/web/http/cors/errors/index.html create mode 100644 files/zh-tw/web/http/cors/index.html create mode 100644 files/zh-tw/web/http/data_uris/index.html create mode 100644 files/zh-tw/web/http/headers/accept/index.html create mode 100644 files/zh-tw/web/http/headers/dnt/index.html create mode 100644 files/zh-tw/web/http/headers/index.html create mode 100644 files/zh-tw/web/http/headers/server/index.html create mode 100644 files/zh-tw/web/http/headers/strict-transport-security/index.html create mode 100644 files/zh-tw/web/http/headers/user-agent/index.html create mode 100644 files/zh-tw/web/http/headers/x-forwarded-for/index.html create mode 100644 files/zh-tw/web/http/headers/x-frame-options/index.html create mode 100644 files/zh-tw/web/http/index.html create mode 100644 files/zh-tw/web/http/link_prefetching_faq/index.html create mode 100644 files/zh-tw/web/http/methods/connect/index.html create mode 100644 files/zh-tw/web/http/methods/get/index.html create mode 100644 files/zh-tw/web/http/methods/index.html create mode 100644 files/zh-tw/web/http/methods/post/index.html create mode 100644 files/zh-tw/web/http/protocol_upgrade_mechanism/index.html create mode 100644 files/zh-tw/web/http/server-side_access_control/index.html create mode 100644 files/zh-tw/web/http/status/100/index.html create mode 100644 files/zh-tw/web/http/status/101/index.html create mode 100644 files/zh-tw/web/http/status/200/index.html create mode 100644 files/zh-tw/web/http/status/201/index.html create mode 100644 files/zh-tw/web/http/status/202/index.html create mode 100644 files/zh-tw/web/http/status/203/index.html create mode 100644 files/zh-tw/web/http/status/204/index.html create mode 100644 files/zh-tw/web/http/status/205/index.html create mode 100644 files/zh-tw/web/http/status/206/index.html create mode 100644 files/zh-tw/web/http/status/300/index.html create mode 100644 files/zh-tw/web/http/status/301/index.html create mode 100644 files/zh-tw/web/http/status/403/index.html create mode 100644 files/zh-tw/web/http/status/404/index.html create mode 100644 files/zh-tw/web/http/status/409/index.html create mode 100644 files/zh-tw/web/http/status/411/index.html create mode 100644 files/zh-tw/web/http/status/415/index.html create mode 100644 files/zh-tw/web/http/status/418_i_m_a_teapot/index.html create mode 100644 files/zh-tw/web/http/status/451/index.html create mode 100644 files/zh-tw/web/http/status/500/index.html create mode 100644 files/zh-tw/web/http/status/502/index.html create mode 100644 files/zh-tw/web/http/status/503/index.html create mode 100644 files/zh-tw/web/http/status/504/index.html create mode 100644 files/zh-tw/web/http/status/index.html create mode 100644 files/zh-tw/web/index.html create mode 100644 files/zh-tw/web/javascript/a_re-introduction_to_javascript/index.html create mode 100644 files/zh-tw/web/javascript/about_javascript/index.html create mode 100644 files/zh-tw/web/javascript/closures/index.html create mode 100644 files/zh-tw/web/javascript/data_structures/index.html create mode 100644 files/zh-tw/web/javascript/enumerability_and_ownership_of_properties/index.html create mode 100644 files/zh-tw/web/javascript/equality_comparisons_and_sameness/index.html create mode 100644 files/zh-tw/web/javascript/eventloop/index.html create mode 100644 files/zh-tw/web/javascript/guide/control_flow_and_error_handling/index.html create mode 100644 files/zh-tw/web/javascript/guide/details_of_the_object_model/index.html create mode 100644 files/zh-tw/web/javascript/guide/expressions_and_operators/index.html create mode 100644 files/zh-tw/web/javascript/guide/functions/index.html create mode 100644 files/zh-tw/web/javascript/guide/grammar_and_types/index.html create mode 100644 files/zh-tw/web/javascript/guide/index.html create mode 100644 files/zh-tw/web/javascript/guide/indexed_collections/index.html create mode 100644 files/zh-tw/web/javascript/guide/introduction/index.html create mode 100644 files/zh-tw/web/javascript/guide/iterators_and_generators/index.html create mode 100644 files/zh-tw/web/javascript/guide/keyed_collections/index.html create mode 100644 files/zh-tw/web/javascript/guide/loops_and_iteration/index.html create mode 100644 files/zh-tw/web/javascript/guide/numbers_and_dates/index.html create mode 100644 files/zh-tw/web/javascript/guide/regular_expressions/index.html create mode 100644 files/zh-tw/web/javascript/guide/using_promises/index.html create mode 100644 files/zh-tw/web/javascript/guide/working_with_objects/index.html create mode 100644 files/zh-tw/web/javascript/index.html create mode 100644 files/zh-tw/web/javascript/inheritance_and_the_prototype_chain/index.html create mode 100644 files/zh-tw/web/javascript/introduction_to_object-oriented_javascript/index.html create mode 100644 files/zh-tw/web/javascript/javascript_technologies_overview/index.html create mode 100644 files/zh-tw/web/javascript/language_resources/index.html create mode 100644 files/zh-tw/web/javascript/memory_management/index.html create mode 100644 files/zh-tw/web/javascript/new_in_javascript/1.1/index.html create mode 100644 files/zh-tw/web/javascript/new_in_javascript/1.2/index.html create mode 100644 files/zh-tw/web/javascript/new_in_javascript/1.3/index.html create mode 100644 files/zh-tw/web/javascript/new_in_javascript/1.4/index.html create mode 100644 files/zh-tw/web/javascript/new_in_javascript/1.5/index.html create mode 100644 files/zh-tw/web/javascript/new_in_javascript/1.6/index.html create mode 100644 files/zh-tw/web/javascript/new_in_javascript/1.7/index.html create mode 100644 files/zh-tw/web/javascript/new_in_javascript/1.8.1/index.html create mode 100644 files/zh-tw/web/javascript/new_in_javascript/1.8.5/index.html create mode 100644 files/zh-tw/web/javascript/new_in_javascript/1.8/index.html create mode 100644 files/zh-tw/web/javascript/new_in_javascript/index.html create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/javascript_\346\246\202\350\246\201/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/liveconnect_\346\246\202\350\246\201/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/liveconnect_\346\246\202\350\246\201/java_\345\220\221_javascript_\347\232\204\351\200\232\350\250\212/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/liveconnect_\346\246\202\350\246\201/java_\345\220\221_javascript_\347\232\204\351\200\232\350\250\212/liveconnect_\351\241\236\345\210\245\347\232\204\344\275\277\347\224\250/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/liveconnect_\346\246\202\350\246\201/javascript_\345\220\221_java_\347\232\204\351\200\232\350\250\212/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/liveconnect_\346\246\202\350\246\201/\345\214\205\350\243\235\345\231\250\347\232\204\351\201\213\347\224\250/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/liveconnect_\346\246\202\350\246\201/\350\263\207\346\226\231\351\241\236\345\236\213\347\232\204\350\275\211\346\217\233/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/liveconnect_\346\246\202\350\246\201/\350\263\207\346\226\231\351\241\236\345\236\213\347\232\204\350\275\211\346\217\233/\345\276\236_java_\345\210\260_javascript_\347\232\204\350\275\211\346\217\233/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/liveconnect_\346\246\202\350\246\201/\350\263\207\346\226\231\351\241\236\345\236\213\347\232\204\350\275\211\346\217\233/\345\276\236_javascript_\345\210\260_java_\347\232\204\350\275\211\346\217\233/index.html" create mode 100644 files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/unicode/index.html create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\344\273\245\351\241\236\345\210\245\347\202\272\345\237\272\347\244\216\347\232\204\350\252\236\350\250\200_vs._\344\273\245\345\216\237\345\236\213\347\202\272\345\237\272\347\244\216\347\232\204\350\252\236\350\250\200/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\344\276\213\345\244\226\350\231\225\347\220\206\350\252\236\346\263\225/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\344\276\213\345\244\226\350\231\225\347\220\206\350\252\236\346\263\225/throw_\350\252\236\346\263\225/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\344\276\213\345\244\226\350\231\225\347\220\206\350\252\236\346\263\225/try...catch_\350\252\236\346\263\225/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\345\200\274/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\345\206\215\350\253\207\345\261\254\346\200\247\347\232\204\347\271\274\346\211\277/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\345\206\215\350\253\207\345\261\254\346\200\247\347\232\204\347\271\274\346\211\277/\345\257\246\351\253\224\351\227\234\344\277\202\347\232\204\347\242\272\345\256\232/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\345\206\215\350\253\207\345\261\254\346\200\247\347\232\204\347\271\274\346\211\277/\345\261\200\345\237\237\345\200\274\345\222\214\347\271\274\346\211\277\345\200\274/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\345\206\215\350\253\207\345\261\254\346\200\247\347\232\204\347\271\274\346\211\277/\345\273\272\346\247\213\345\255\220\344\270\255\347\232\204\345\205\250\345\237\237\350\263\207\350\250\212/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\345\206\215\350\253\207\345\261\254\346\200\247\347\232\204\347\271\274\346\211\277/\346\262\222\346\234\211\345\244\232\351\207\215\347\271\274\346\211\277/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\345\207\275\346\225\270\347\232\204\345\221\274\345\217\253/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\345\207\275\346\225\270\347\232\204\345\256\232\347\276\251/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\345\215\200\345\241\212\350\252\236\346\263\225/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\345\255\227\351\235\242\350\241\250\351\201\224/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\345\270\270\346\225\270/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\345\273\272\347\253\213\346\226\260\347\232\204\347\211\251\344\273\266/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\345\276\252\347\222\260\350\252\236\346\263\225/break_\350\252\236\346\263\225/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\345\276\252\347\222\260\350\252\236\346\263\225/continue_\350\252\236\346\263\225/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\345\276\252\347\222\260\350\252\236\346\263\225/do...while_\350\252\236\346\263\225/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\345\276\252\347\222\260\350\252\236\346\263\225/for_\350\252\236\346\263\225/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\345\276\252\347\222\260\350\252\236\346\263\225/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\345\276\252\347\222\260\350\252\236\346\263\225/label_\350\252\236\346\263\225/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\345\276\252\347\222\260\350\252\236\346\263\225/while_\350\252\236\346\263\225/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\346\226\260\347\211\251\344\273\266\347\232\204\345\273\272\347\253\213/getter_\345\222\214_setter_\347\232\204\345\256\232\347\276\251/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\346\226\260\347\211\251\344\273\266\347\232\204\345\273\272\347\253\213/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\346\226\260\347\211\251\344\273\266\347\232\204\345\273\272\347\253\213/\344\275\277\347\224\250_this_\345\217\226\345\276\227\347\211\251\344\273\266\347\232\204\345\217\203\350\200\203/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\346\226\260\347\211\251\344\273\266\347\232\204\345\273\272\347\253\213/\345\261\254\346\200\247\347\232\204\345\210\252\351\231\244/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\346\226\260\347\211\251\344\273\266\347\232\204\345\273\272\347\253\213/\345\273\272\346\247\213\345\255\220\345\207\275\346\225\270\347\232\204\344\275\277\347\224\250/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\346\226\260\347\211\251\344\273\266\347\232\204\345\273\272\347\253\213/\346\226\271\346\263\225\347\232\204\345\256\232\347\276\251/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\346\226\260\347\211\251\344\273\266\347\232\204\345\273\272\347\253\213/\347\211\251\344\273\266\345\210\235\345\247\213\345\214\226\345\255\220\347\232\204\344\275\277\347\224\250/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\346\226\260\347\211\251\344\273\266\347\232\204\345\273\272\347\253\213/\347\211\251\344\273\266\345\261\254\346\200\247\347\232\204\347\264\242\345\274\225/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\346\226\260\347\211\251\344\273\266\347\232\204\345\273\272\347\253\213/\351\207\235\345\260\215\347\211\251\344\273\266\347\232\204\351\241\236\345\236\213\345\256\232\347\276\251\345\261\254\346\200\247/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\346\242\235\344\273\266\350\252\236\346\263\225/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\346\255\243\350\246\217\350\241\250\351\201\224\345\274\217\346\250\241\345\274\217\347\232\204\347\267\250\345\257\253/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\346\255\243\350\246\217\350\241\250\351\201\224\345\274\217\347\232\204\345\273\272\347\253\213/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\346\255\243\350\246\217\350\241\250\351\201\224\345\274\217\347\232\204\351\201\213\347\224\250/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\346\255\243\350\246\217\350\241\250\351\201\224\345\274\217\347\232\204\351\201\213\347\224\250/\344\275\277\347\224\250\346\250\231\350\252\214\347\232\204\351\200\262\351\232\216\346\220\234\345\260\213/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\346\255\243\350\246\217\350\241\250\351\201\224\345\274\217\347\232\204\351\201\213\347\224\250/\346\213\254\345\274\247\345\255\220\345\255\227\344\270\262\347\232\204\346\257\224\345\260\215\347\265\220\346\236\234\347\232\204\351\201\213\347\224\250/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\346\255\243\350\246\217\350\241\250\351\201\224\345\274\217\347\232\204\351\201\213\347\224\250/\346\255\243\350\246\217\350\241\250\351\201\224\345\274\217\347\232\204\347\257\204\344\276\213/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\347\211\251\344\273\266\345\222\214\345\261\254\346\200\247/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\347\211\251\344\273\266\347\232\204\346\223\215\344\275\234\350\252\236\346\263\225/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\347\271\274\346\211\277/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\350\201\267\345\223\241\347\232\204\344\276\213\345\255\220/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\350\201\267\345\223\241\347\232\204\344\276\213\345\255\220/\346\233\264\351\235\210\346\264\273\347\232\204\345\273\272\346\247\213\345\255\220/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\350\201\267\345\223\241\347\232\204\344\276\213\345\255\220/\347\211\251\344\273\266\347\232\204\345\261\254\346\200\247/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\350\201\267\345\223\241\347\232\204\344\276\213\345\255\220/\347\211\251\344\273\266\347\232\204\345\261\254\346\200\247/\345\261\254\346\200\247\347\232\204\345\212\240\345\205\245/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\350\201\267\345\223\241\347\232\204\344\276\213\345\255\220/\347\211\251\344\273\266\347\232\204\345\261\254\346\200\247/\345\261\254\346\200\247\347\232\204\347\271\274\346\211\277/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\350\201\267\345\223\241\347\232\204\344\276\213\345\255\220/\351\232\216\345\261\244\347\232\204\345\273\272\347\253\213/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\350\241\250\351\201\224\345\274\217/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\350\250\273\350\247\243/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\350\256\212\346\225\270/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\350\277\255\344\273\243\345\231\250\345\222\214\347\224\242\347\224\237\345\231\250/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\351\201\213\347\256\227\345\255\220/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\351\201\213\347\256\227\345\255\220/\344\273\243\345\205\245\351\201\213\347\256\227\345\255\220/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\351\201\213\347\256\227\345\255\220/\344\275\215\345\205\203\351\201\213\347\256\227\345\255\220/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\351\201\213\347\256\227\345\255\220/\345\255\227\344\270\262\351\201\213\347\256\227\345\255\220/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\351\201\213\347\256\227\345\255\220/\346\257\224\350\274\203\351\201\213\347\256\227\345\255\220/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\351\201\213\347\256\227\345\255\220/\347\211\271\346\256\212\351\201\213\347\256\227\345\255\220/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\351\201\213\347\256\227\345\255\220/\347\256\227\350\241\223\351\201\213\347\256\227\345\255\220/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\351\201\213\347\256\227\345\255\220/\351\202\217\350\274\257\351\201\213\347\256\227\345\255\220/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\351\226\211\345\214\205\347\232\204\351\201\213\347\224\250/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\351\227\234\346\226\274/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\351\231\243\345\210\227\347\232\204\351\201\213\347\224\250/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\351\240\220\345\205\210\345\256\232\347\276\251\347\232\204\345\207\275\346\225\270/escape_\345\222\214_unescape_\345\207\275\346\225\270/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\351\240\220\345\205\210\345\256\232\347\276\251\347\232\204\345\207\275\346\225\270/eval_\345\207\275\346\225\270/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\351\240\220\345\205\210\345\256\232\347\276\251\347\232\204\345\207\275\346\225\270/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\351\240\220\345\205\210\345\256\232\347\276\251\347\232\204\345\207\275\346\225\270/isfinite_\345\207\275\346\225\270/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\351\240\220\345\205\210\345\256\232\347\276\251\347\232\204\345\207\275\346\225\270/isnan_\345\207\275\346\225\270/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\351\240\220\345\205\210\345\256\232\347\276\251\347\232\204\345\207\275\346\225\270/number_\345\222\214_string_\345\207\275\346\225\270/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\351\240\220\345\205\210\345\256\232\347\276\251\347\232\204\345\207\275\346\225\270/parseint_\345\222\214_parsefloat_\345\207\275\346\225\270/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\351\240\220\345\205\210\345\256\232\347\276\251\347\232\204\346\240\270\345\277\203\347\211\251\344\273\266/array_\347\211\251\344\273\266/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\351\240\220\345\205\210\345\256\232\347\276\251\347\232\204\346\240\270\345\277\203\347\211\251\344\273\266/boolean_\347\211\251\344\273\266/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\351\240\220\345\205\210\345\256\232\347\276\251\347\232\204\346\240\270\345\277\203\347\211\251\344\273\266/date_\347\211\251\344\273\266/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\351\240\220\345\205\210\345\256\232\347\276\251\347\232\204\346\240\270\345\277\203\347\211\251\344\273\266/function_\347\211\251\344\273\266/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\351\240\220\345\205\210\345\256\232\347\276\251\347\232\204\346\240\270\345\277\203\347\211\251\344\273\266/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\351\240\220\345\205\210\345\256\232\347\276\251\347\232\204\346\240\270\345\277\203\347\211\251\344\273\266/math_\347\211\251\344\273\266/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\351\240\220\345\205\210\345\256\232\347\276\251\347\232\204\346\240\270\345\277\203\347\211\251\344\273\266/number_\347\211\251\344\273\266/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\351\240\220\345\205\210\345\256\232\347\276\251\347\232\204\346\240\270\345\277\203\347\211\251\344\273\266/regexp_\347\211\251\344\273\266/index.html" create mode 100644 "files/zh-tw/web/javascript/obsolete_pages/obsolete_pages/obsolete_pages/\351\240\220\345\205\210\345\256\232\347\276\251\347\232\204\346\240\270\345\277\203\347\211\251\344\273\266/string_\347\211\251\344\273\266/index.html" create mode 100644 files/zh-tw/web/javascript/reference/classes/constructor/index.html create mode 100644 files/zh-tw/web/javascript/reference/classes/extends/index.html create mode 100644 files/zh-tw/web/javascript/reference/classes/index.html create mode 100644 files/zh-tw/web/javascript/reference/classes/static/index.html create mode 100644 files/zh-tw/web/javascript/reference/errors/bad_return_or_yield/index.html create mode 100644 files/zh-tw/web/javascript/reference/errors/index.html create mode 100644 files/zh-tw/web/javascript/reference/errors/invalid_array_length/index.html create mode 100644 files/zh-tw/web/javascript/reference/errors/missing_curly_after_property_list/index.html create mode 100644 files/zh-tw/web/javascript/reference/errors/no_properties/index.html create mode 100644 files/zh-tw/web/javascript/reference/errors/not_a_function/index.html create mode 100644 files/zh-tw/web/javascript/reference/errors/not_defined/index.html create mode 100644 files/zh-tw/web/javascript/reference/errors/redeclared_parameter/index.html create mode 100644 files/zh-tw/web/javascript/reference/errors/too_much_recursion/index.html create mode 100644 files/zh-tw/web/javascript/reference/errors/unexpected_type/index.html create mode 100644 files/zh-tw/web/javascript/reference/functions/arguments/callee/index.html create mode 100644 files/zh-tw/web/javascript/reference/functions/arguments/index.html create mode 100644 files/zh-tw/web/javascript/reference/functions/arrow_functions/index.html create mode 100644 files/zh-tw/web/javascript/reference/functions/default_parameters/index.html create mode 100644 files/zh-tw/web/javascript/reference/functions/get/index.html create mode 100644 files/zh-tw/web/javascript/reference/functions/index.html create mode 100644 files/zh-tw/web/javascript/reference/functions/method_definitions/index.html create mode 100644 files/zh-tw/web/javascript/reference/functions/rest_parameters/index.html create mode 100644 files/zh-tw/web/javascript/reference/functions/set/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/array/@@iterator/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/array/concat/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/array/copywithin/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/array/entries/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/array/every/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/array/fill/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/array/filter/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/array/find/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/array/findindex/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/array/flat/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/array/foreach/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/array/from/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/array/includes/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/array/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/array/indexof/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/array/isarray/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/array/join/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/array/keys/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/array/lastindexof/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/array/length/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/array/map/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/array/of/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/array/pop/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/array/push/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/array/reduce/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/array/reverse/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/array/shift/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/array/slice/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/array/some/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/array/sort/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/array/splice/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/array/unshift/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/array/values/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/arraybuffer/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/arraybuffer/prototype/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/asyncfunction/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/bigint/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/boolean/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/dataview/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/date/getday/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/date/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/date/now/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/date/prototype/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/date/utc/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/error/columnnumber/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/error/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/function/apply/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/function/bind/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/function/call/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/function/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/function/length/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/function/prototype/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/infinity/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/isnan/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/json/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/json/parse/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/json/stringify/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/map/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/math/abs/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/math/ceil/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/math/floor/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/math/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/math/max/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/math/pow/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/math/random/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/math/round/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/nan/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/null/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/number/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/number/isfinite/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/number/isnan/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/number/prototype/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/number/toexponential/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/number/tofixed/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/object/assign/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/object/create/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/object/defineproperties/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/object/defineproperty/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/object/freeze/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/object/getprototypeof/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/object/hasownproperty/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/object/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/object/keys/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/object/preventextensions/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/object/proto/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/object/prototype/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/object/watch/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/parseint/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/promise/all/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/promise/catch/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/promise/finally/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/promise/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/promise/prototype/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/promise/race/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/promise/reject/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/promise/resolve/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/promise/then/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/proxy/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/rangeerror/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/reflect/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/regexp/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/set/add/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/set/clear/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/set/delete/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/set/entries/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/set/has/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/set/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/set/values/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/string/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/string/match/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/string/padstart/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/string/prototype/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/string/replace/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/string/tolowercase/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/typedarray/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/undefined/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/urierror/index.html create mode 100644 files/zh-tw/web/javascript/reference/index.html create mode 100644 files/zh-tw/web/javascript/reference/iteration_protocols/index.html create mode 100644 files/zh-tw/web/javascript/reference/lexical_grammar/index.html create mode 100644 files/zh-tw/web/javascript/reference/operators/arithmetic_operators/index.html create mode 100644 files/zh-tw/web/javascript/reference/operators/async_function/index.html create mode 100644 files/zh-tw/web/javascript/reference/operators/await/index.html create mode 100644 files/zh-tw/web/javascript/reference/operators/bitwise_operators/index.html create mode 100644 files/zh-tw/web/javascript/reference/operators/comma_operator/index.html create mode 100644 files/zh-tw/web/javascript/reference/operators/comparison_operators/index.html create mode 100644 files/zh-tw/web/javascript/reference/operators/conditional_operator/index.html create mode 100644 files/zh-tw/web/javascript/reference/operators/destructuring_assignment/index.html create mode 100644 files/zh-tw/web/javascript/reference/operators/index.html create mode 100644 files/zh-tw/web/javascript/reference/operators/logical_operators/index.html create mode 100644 files/zh-tw/web/javascript/reference/operators/object_initializer/index.html create mode 100644 files/zh-tw/web/javascript/reference/operators/operator_precedence/index.html create mode 100644 files/zh-tw/web/javascript/reference/operators/optional_chaining/index.html create mode 100644 files/zh-tw/web/javascript/reference/operators/spread_syntax/index.html create mode 100644 files/zh-tw/web/javascript/reference/operators/super/index.html create mode 100644 files/zh-tw/web/javascript/reference/operators/this/index.html create mode 100644 files/zh-tw/web/javascript/reference/operators/typeof/index.html create mode 100644 files/zh-tw/web/javascript/reference/statements/async_function/index.html create mode 100644 files/zh-tw/web/javascript/reference/statements/block/index.html create mode 100644 files/zh-tw/web/javascript/reference/statements/break/index.html create mode 100644 files/zh-tw/web/javascript/reference/statements/const/index.html create mode 100644 files/zh-tw/web/javascript/reference/statements/debugger/index.html create mode 100644 files/zh-tw/web/javascript/reference/statements/export/index.html create mode 100644 files/zh-tw/web/javascript/reference/statements/for...in/index.html create mode 100644 files/zh-tw/web/javascript/reference/statements/function_star_/index.html create mode 100644 files/zh-tw/web/javascript/reference/statements/if...else/index.html create mode 100644 files/zh-tw/web/javascript/reference/statements/import/index.html create mode 100644 files/zh-tw/web/javascript/reference/statements/index.html create mode 100644 files/zh-tw/web/javascript/reference/statements/label/index.html create mode 100644 files/zh-tw/web/javascript/reference/statements/let/index.html create mode 100644 files/zh-tw/web/javascript/reference/statements/return/index.html create mode 100644 files/zh-tw/web/javascript/reference/statements/switch/index.html create mode 100644 files/zh-tw/web/javascript/reference/statements/throw/index.html create mode 100644 files/zh-tw/web/javascript/reference/statements/var/index.html create mode 100644 files/zh-tw/web/javascript/reference/strict_mode/index.html create mode 100644 files/zh-tw/web/javascript/reference/template_literals/index.html create mode 100644 files/zh-tw/web/javascript/shells/index.html create mode 100644 files/zh-tw/web/javascript/typed_arrays/index.html create mode 100644 files/zh-tw/web/manifest/index.html create mode 100644 files/zh-tw/web/mathml/authoring/index.html create mode 100644 files/zh-tw/web/mathml/index.html create mode 100644 files/zh-tw/web/media/formats/containers/index.html create mode 100644 files/zh-tw/web/media/formats/index.html create mode 100644 files/zh-tw/web/media/index.html create mode 100644 files/zh-tw/web/opensearch/index.html create mode 100644 files/zh-tw/web/progressive_web_apps/index.html create mode 100644 files/zh-tw/web/reference/api/index.html create mode 100644 files/zh-tw/web/reference/index.html create mode 100644 files/zh-tw/web/security/index.html create mode 100644 files/zh-tw/web/security/insecure_passwords/index.html create mode 100644 files/zh-tw/web/security/mixed_content/how_to_fix_website_with_mixed_content/index.html create mode 100644 files/zh-tw/web/security/mixed_content/index.html create mode 100644 files/zh-tw/web/security/same-origin_policy/index.html create mode 100644 files/zh-tw/web/security/weak_signature_algorithm/index.html create mode 100644 files/zh-tw/web/svg/attribute/fill-rule/index.html create mode 100644 files/zh-tw/web/svg/attribute/index.html create mode 100644 files/zh-tw/web/svg/attribute/stroke-dashoffset/index.html create mode 100644 files/zh-tw/web/svg/index.html create mode 100644 files/zh-tw/web/svg/tutorial/fills_and_strokes/index.html create mode 100644 files/zh-tw/web/svg/tutorial/getting_started/index.html create mode 100644 files/zh-tw/web/svg/tutorial/gradients/index.html create mode 100644 files/zh-tw/web/svg/tutorial/index.html create mode 100644 files/zh-tw/web/svg/tutorial/introduction/index.html create mode 100644 files/zh-tw/web/svg/tutorial/patterns/index.html create mode 100644 files/zh-tw/web/svg/tutorial/positions/index.html create mode 100644 "files/zh-tw/web/svg/tutorial/\350\267\257\345\276\204/index.html" create mode 100644 "files/zh-tw/web/svg/\346\225\231\345\255\270/index.html" create mode 100644 files/zh-tw/web/tutorials/index.html create mode 100644 "files/zh-tw/web/\346\200\247\350\203\275/index.html" (limited to 'files/zh-tw/web') diff --git a/files/zh-tw/web/accessibility/aria/aria_techniques/index.html b/files/zh-tw/web/accessibility/aria/aria_techniques/index.html new file mode 100644 index 0000000000..502a808e1d --- /dev/null +++ b/files/zh-tw/web/accessibility/aria/aria_techniques/index.html @@ -0,0 +1,164 @@ +--- +title: Using ARIA +slug: Web/Accessibility/ARIA/ARIA_Techniques +translation_of: Web/Accessibility/ARIA/ARIA_Techniques +--- +

 

+ +

Roles(角色)

+ +

 

+ +

Widget roles (局部組件)

+ +
+ +
+ +

Composite roles

+ +

下面的技術,描述了每個複合角色,以及他們的必要和可選的子角色。

+ +
+ +
+ +

Document structure roles

+ +
+ +
+ +

Landmark roles

+ +
+ +
+ +

States and properties

+ +

 

+ +

Widget attributes

+ +
+ +
+ +

Live region attributes

+ +
+ +
+ +

Drag & drop attributes

+ +
+ +
+ +

Relationship attributes

+ +
+ +
diff --git a/files/zh-tw/web/accessibility/aria/forms/basic_form_hints/index.html b/files/zh-tw/web/accessibility/aria/forms/basic_form_hints/index.html new file mode 100644 index 0000000000..532911294d --- /dev/null +++ b/files/zh-tw/web/accessibility/aria/forms/basic_form_hints/index.html @@ -0,0 +1,119 @@ +--- +title: 基本表單應用 +slug: Web/Accessibility/ARIA/forms/Basic_form_hints +tags: + - 待翻譯 +translation_of: Web/Accessibility/ARIA/forms/Basic_form_hints +--- +

表單的 label

+ +

當使用傳統的 HTML 表單元素建立表單時,提供控制用的標籤(label)以及將標籤與對應表單元素建立關聯是非常重要的。當 screen reader (例如瀏覽器、電子郵件……等等)瀏覽一個頁面時,screen reader 會顯示 form controls ,但若沒有標示 control 和 label 之間的關聯,  screen reader 沒法知道哪個 label 是對應哪個 control。

+ +

下面的範例顯示一個使用標籤的表單。注意每一個 {{ HTMLElement("input") }} 元件都有 id,每一個 {{ HTMLElement("label") }} 元件有 for 屬性,用來對應 {{ HTMLElement("input") }} 元素的 id 。

+ +

範例 1. 使用 label 的簡易表單

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

使用 ARIA 標籤

+ +

HTML 的 {{ HTMLElement("label") }} 元素適用於表單相關元素 , 但是許多表單控件被實現為動態JavaScript小部件 , 使用 {{ HTMLElement("div") }} 或 {{ HTMLElement("span") }}。 WAI-ARIA , 來自 W3C 的網路無障礙計畫 ( Web Accessibility Initiative ) 的無障礙互聯網應用程序規範 ( Accessible Rich Internet Applications specification ) , 為這些情況提供了 aria-labelledby 屬性。

+ +

下面的範例顯示使用無序列表 ( unordered list ) 實現的單選按鈕組 ( radio button group )。注意程式碼第三行 , {{ HTMLElement("li") }} 元素將 aria-labelledby 屬性設置為 "rg1_label" , 在第一行中元素 {{ HTMLElement("h3") }} 的 id , 即單選按鈕組的標籤。

+ +

範例 2. 使用無序列表實現的單選按鈕組 ( 改編自 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>
+
+ +

Describing with ARIA

+ +

Form controls sometimes have a description associated with them, in addition to the label. ARIA provides the aria-describedby attribute to directly associate the description with the control.

+ +

The example below shows a {{ HTMLElement("button") }} element that is described by a sentence in a separate {{ HTMLElement("div") }} element. The aria-describedby attribute on the {{ HTMLElement("button") }} references the id of the {{ HTMLElement("div") }}.

+ +

Example 3. A button described by a separate element.

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

(Note that the aria-describedby attribute is used for other purposes, in addition to form controls.)

+ +

Required and invalid fields

+ +

Web developers typically use presentational strategies to indicated required or invalid fields, but assistive technologies (ATs) cannot necessarily infer this information from the presentation. ARIA provides attributes for indicating that form controls are required or invalid:

+ + + +

The example below shows a simple form with three fields. On lines 4 and 12, the aria-required attributes are set to true (in addition to the asterisks next to the labels) indicating that the name and email fields are required. The second part of the example is a snippet of JavaScript that validates the email format and sets the aria-invalid attribute of the email field (line 12 of the HTML) according to the result (in addition to changing the presentation of the element).

+ +

Example 4a. A form with required fields.

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

Example 4b. Part of a script that validates the form entry.

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

提供有幫助的錯誤訊息

+ +

繼續閱讀了解如何使用 ARIA alerts to enhance forms.

+ +
TBD: we should either combine into one article or separate into techniques, or both. Also, is ARIA markup appropriate for error messages in a page loaded after server side validation?
+ +

參閱 WAI-ARIA Authoring Practices .

diff --git a/files/zh-tw/web/accessibility/aria/forms/index.html b/files/zh-tw/web/accessibility/aria/forms/index.html new file mode 100644 index 0000000000..ca529d1b1e --- /dev/null +++ b/files/zh-tw/web/accessibility/aria/forms/index.html @@ -0,0 +1,19 @@ +--- +title: Forms +slug: Web/Accessibility/ARIA/forms +tags: + - ARIA + - Accessibility + - NeedsTranslation + - TopicStub +translation_of: Web/Accessibility/ARIA/forms +--- +

下列連結提供多種技術的資訊來處進網頁表格的存取:

+ + + +

透過Yahoo! article on form validation and ARIA, 網頁的瀏覽可發現上面所列出的技術的實際應用.

diff --git a/files/zh-tw/web/accessibility/aria/index.html b/files/zh-tw/web/accessibility/aria/index.html new file mode 100644 index 0000000000..891695ab5a --- /dev/null +++ b/files/zh-tw/web/accessibility/aria/index.html @@ -0,0 +1,142 @@ +--- +title: ARIA +slug: Web/Accessibility/ARIA +tags: + - ARIA + - Accessibility + - NeedsTranslation + - TopicStub +translation_of: Web/Accessibility/ARIA +--- +

Accessible Rich Internet Applications (ARIA) defines ways to make Web content and Web applications (especially those developed with Ajax and JavaScript) more accessible to people with disabilities. For example, ARIA enables accessible navigation landmarks, JavaScript widgets, form hints and error messages, live content updates, and more.

+ +

ARIA is a set of special accessibility attributes which can be added to any markup, but is especially suited to HTML. The role attribute defines what the general type of object is (such as an article, alert, or slider). Additional ARIA attributes provide other useful properties, such as a description for a form or the current value of a progressbar.

+ +

ARIA is implemented in most popular browsers and screen readers. However, implementations vary and older technologies don't support it well (if at all). Use either "safe" ARIA that degrades gracefully, or ask users to upgrade to newer technology.

+ +
+

Note: Please contribute and make ARIA better for the next person! Not enough time? Send suggestions to Mozilla's accessibility mailing list, or #accessibility IRC channel.

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

Getting Started with ARIA

+ +
+
Introduction to ARIA
+
A quick introduction to making dynamic content accessible with ARIA. See also the classic ARIA intro by Gez Lemon, from 2008.
+
Web Applications and ARIA FAQ
+
Answers common questions about WAI-ARIA and why it's needed to make web applications accessible.
+
Videos of Screen Readers Using ARIA
+
See both real and simplfied examples from around the web, including "before" and "after" ARIA videos. 
+
Using ARIA in HTML
+
A practical guide for developers. It suggests what ARIA attributes to use on HTML elements. Suggestions are based on implementation realities.
+
+ +

Simple ARIA Enhancements

+ +
+
Enhancing Page Navigation with ARIA Landmarks
+
A nice intro to using ARIA landmarks to improve web page navigation for screen reader users. See also, ARIA landmark implementation notes and examples on real sites (updated as of July '11).
+
Improving Form Accessibility
+
ARIA is not just for dynamic content! Learn how to improve accessibility of HTML forms using additional ARIA attributes. 
+
Live regions (work-in-progress)
+
Live regions provide suggestions to screen readers about how to handle changes to the contents of a page.
+
Using ARIA Live Regions to Announce Content Changes
+
A quick summary of live regions, by the makers of JAWS screen reader software. Note that live regions are also supported by NVDA in Firefox, and VoiceOver with Safari (as of OS X Lion and iOS 5).
+
+ +

ARIA for Scripted Widgets

+ +
+
Keyboard Navigation and Focus for JavaScript Widgets
+
The first step in developing an accessible JavaScript widget is to make it keyboard navigable. This article steps through the process. The Yahoo! focus management article is a great resource as well.
+
Style Guide for Keyboard Navigation
+
A challenge with ARIA is getting developers to implement consistent behavior -- clearly best for users. This style guide describes the keyboard interface for common widgets.
+
+ +

ARIA Resources

+ +
+
Widget Techniques, Tutorials, and Examples
+
Need a slider, a menu, or another kind of widget? Find resources here.
+
ARIA-Enabled JavaScript UI Libraries
+
If you're starting a new project, choose a UI widget library with ARIA support already built-in. Warning: this is from 2009 -- content should be moved to an MDN page where it can be updated.
+
Accessibility of HTML5 and Rich Internet Applications - CSUN 2012 Workshop Materials
+
Includes slide presentations and examples.
+
+
+

Mailing List

+ +
+
Free ARIA Google Group
+
A place to ask questions about ARIA, as well as make suggestions for improving the ARIA documentation found on these pages.
+
+ +

Blogs

+ +

ARIA information on blogs tends to get out of date quickly. Still, there is some great info out there from other developers making ARIA work today.

+ +

Paciello Group

+ +

Accessible Culture

+ +

Filing Bugs

+ +

File ARIA bugs on browsers, screen readers, and JavaScript libraries.

+ +

Examples

+ +
+
ARIA Examples Library
+
A set of barebones example files which are easy to learn from.
+
Accessible JS Widget Library Demos
+
Dojo, jQueryFluid, YUI
+
+ +
+
Yahoo! Mail
+
Yahoo! puts it all together with Yahoo! Mail, a web app that almost looks like a native app. It works very well. As a review of Yahoo! Mail by screen reader Marco Zehe says, "Keep up the good work!".
+
+ +
+
Yahoo! Search
+
Yahoo! has done an amazing job of advancing ARIA here, by exercising ARIA's full capabilities and sharing their techniques. Yahoo! Search uses a combination of ARIA landmarks, live regions, and widgets.
+
+ +

Standardization Efforts

+ +
+
WAI-ARIA Activities Overview at W3C
+
Authoritative Overview of WAI-ARIA Standardization efforts by the Web Accessibility Initiative (WAI)
+
WAI-ARIA Specification
+
The W3C specification itself, useful as a reference. Note that, at this stage, it is important to test compatibility, as implementations are still inconsistent.
+
WAI-ARIA Authoring Practices
+
Like the W3C WAI-ARIA specification, the official best practices represents a future ideal -- a day when authors can rely on consistent ARIA support across browsers and screen readers. The W3C documents provide an in-depth view of ARIA.
+
+ For now, web developers implementing ARIA should maximize compatibility. Use best practices docs and examples based on current implementations.
+
Open AJAX Accessibility Task Force
+
The Open AJAX effort centers around developing tools, sample files, and automated tests for ARIA.
+
Under Construction: WCAG 2.0 ARIA Techniques
+
The community needs a complete set of WCAG techniques for WAI-ARIA + HTML, so that organizations can be comfortable claiming their ARIA-enabled content is WCAG compliant. This is mostly important when regulations or policies are based on WCAG.
+
+
+ + +
+
Accessibility, AJAX, JavaScript
+
+
+ +

 

diff --git a/files/zh-tw/web/accessibility/index.html b/files/zh-tw/web/accessibility/index.html new file mode 100644 index 0000000000..b8ed259ecf --- /dev/null +++ b/files/zh-tw/web/accessibility/index.html @@ -0,0 +1,61 @@ +--- +title: 無障礙網頁 +slug: Web/Accessibility +tags: + - Accessibility + - Advanced + - Landing + - NeedsTranslation + - TopicStub + - Web Development +translation_of: Web/Accessibility +--- +

網路開發中的無障礙網頁,意味著盡可能令所有人都能使用網站,就算是在某些感官方面受限的人也不例外。本頁面會提供一些關於無障礙網頁的資訊。

+ +

「理想的無障礙環境就是在各方面都營造一個無障礙的環境。在有形方面,所應該考量事情包括,生活上、行動上、教育上所可能遭受到的障礙,並提供其足以克服這些環境的需求,此等需求包括個體本身的配備,如點字機……以及周圍環境中的裝設,如扶手、導盲磚……」 中文維基百科的「無障礙環境」、「理想無障礙環境」章節

+ +

從根本上,網路是為了在所有人面前都能運行而設計的,無論他們使用的軟硬體、語言文化、地理位置、抑或身心功能如何。當聽覺、運動、視力或認知能力障礙的人,都能訪問網路的時候,這個目標才算達成。」W3C - Accessibility

+ +
+
+

重要概念

+ +

MDN Accessibility Learning Area 涵蓋了最新的無障礙網頁教學所需:

+ +
+
何謂無障礙網頁?
+
這篇文章針對何謂無障礙網頁,起了一個好開頭。這模塊包含了要考慮哪些族群以及理由、不同族群會用什麼工具和 Web 互動、還有怎麼把無障礙網頁導入 Web 開發工作流程。
+
HTML:無障礙網頁的好開始
+
只要確保在任何時候,正確的 HTML 元素都用於正確的目的,就能消除各種網頁的障礙。這篇文章詳述 HTML 如何確保網頁無障礙。
+
充分實踐 CSS 與 JavaScript 的無障礙
+
如果 CSS 與 JavaScript 使用得當,將可以為無障礙網頁提供助力……反過來的話,就會嚴重影響無障礙體驗。這篇文章詳述如何在內容複雜的情況下,確保能充分實踐 CSS 與 JavaScript 的無障礙。
+
WAI-ARIA 基礎
+
從之前的文章來看,有時製作要涉及到非語意的 HTML 還有動態 JavaScript 更新技術……等,會令複雜的 UI 控制變得很困難。WAI-ARIA 正是為了解決此一問題而生。它對瀏覽器和輔助技術添加進一步的語意,讓用戶能知道發生了什麼事。我們將介紹如何在基本層面使用此技術,以提昇無障礙。
+
無障礙多媒體
+
會導致無障礙網頁出問題的另一個根源是多媒體:影片、聲音、圖片等內容,需要有合適的文字替代,以便輔助技術和它的用戶能夠理解。我們將在這篇文章中闡明作法。
+
行動無障礙網頁
+
隨著行動設備訪問漸受歡迎、還有像是 iOS 與 Android 這般熱門平台,已經具備完善的輔助工具,考慮到如何在這些平台上實踐無障礙網頁,就變得十分重要。這篇文章將討論行動裝置特有的無障礙網頁相關議題。
+
+
+ +
+

其他文件

+ +
+
Understanding the Web Content Accessibility Guidelines
+
+

This set of articles provides quick explanations to help you understand the steps that need to be taken to conform to the recommendations outlined in the W3C Web Content Accessibility Guidelines 2.0 (WCAG 2.0 or just WCAG, for the purposes of this writing).

+
+
Keyboard-navigable JavaScript widgets
+
Until now, web developers who want to make their styled <div> and <span> based widgets have lacked the proper techniques. Keyboard accessibility is part of the minimum accessibility requirements which a developer should be aware of.
+
ARIA
+
A collection of articles to learn how to use ARIA to make your HTML documents more accessible.
+
Assistive technology (AT) development
+
A collection of articles intended for AT developers
+
Mobile accessibility checklist
+
This document provides a concise checklist of accessibility requirements for mobile app developers.
+
+ +

所有與無障礙網頁相關的文章……

+
+
diff --git a/files/zh-tw/web/accessibility/mobile_accessibility_checklist/index.html b/files/zh-tw/web/accessibility/mobile_accessibility_checklist/index.html new file mode 100644 index 0000000000..b05da206bc --- /dev/null +++ b/files/zh-tw/web/accessibility/mobile_accessibility_checklist/index.html @@ -0,0 +1,94 @@ +--- +title: 行動無障礙檢核清單 +slug: Web/Accessibility/Mobile_accessibility_checklist +translation_of: Web/Accessibility/Mobile_accessibility_checklist +--- +
+

本文提供行動應用程式開發者一個簡潔的無障礙必備要件檢核清單,本文將隨著更多模型產生而不斷地演進。

+
+ +

顏色

+ + + +
+

注意: Jon Snook已撰寫實用的 Colour Contrast Checker 能用於檢查背景與前景顏色的對比。同樣地,Tanaguru Contrast-Finder 也提供類似功能,而且建議相似且更好的對比顏色提供你考量使用。

+
+ +

可視性

+ + + +

焦點

+ + + +

文字相等意義

+ + + +

處理狀態

+ + + +

一般準則

+ + + +
+

注意: Tanaguru自動無障礙測試服務提供有用的方法去發現一些發生於網頁或安裝的網頁應用程式(如Firefox OS)無障礙錯誤。你可在tanaguru.org找到更多關於Tanaguru技術開發,以及貢獻該專案的資訊。

+
+ +
+

注意: 本文件原始版本Yura Zenevich撰寫。

+
+ +

 

diff --git a/files/zh-tw/web/api/abortcontroller/index.html b/files/zh-tw/web/api/abortcontroller/index.html new file mode 100644 index 0000000000..8caa750806 --- /dev/null +++ b/files/zh-tw/web/api/abortcontroller/index.html @@ -0,0 +1,97 @@ +--- +title: AbortController +slug: Web/API/AbortController +translation_of: Web/API/AbortController +--- +
{{APIRef("DOM")}}{{SeeCompatTable}}
+ +

AbortController 介面代表一個控制器物件,讓你可以在需要時中斷一個或多個 DOM 請求。

+ +

你可以使用 {{domxref("AbortController.AbortController()")}} 建立一個新的 AbortController 物件。與 DOM 請求溝通時則是使用 {{domxref("AbortSignal")}} 物件。

+ +

建構子

+ +
+
{{domxref("AbortController.AbortController()")}}
+
建立一個新的 AbortController 物件實體。
+
+ +

屬性

+ +
+
{{domxref("AbortController.signal")}} {{readonlyInline}}
+
回傳一個 {{domxref("AbortSignal")}} 物件實體,可以用來中斷一個 DOM 請求、或是與其溝通。
+
+ +

方法

+ +
+
{{domxref("AbortController.abort()")}}
+
在一個 DOM 請求完成前中斷他。這可以用來中斷 fetch 請求、對任何 Response {{domxref("Body")}} 的讀取、或是資料流。
+
+ +

範例

+ +

在下面的程式碼片段中,我們要用 Fetch API 來下載一部影片。

+ +

我們首先用 {{domxref("AbortController.AbortController","AbortController()")}} 建立一個控制器,然後透過 {{domxref("AbortController.signal")}} 屬性取得他的 {{domxref("AbortSignal")}} 物件。

+ +

在初始化 fetch 請求 的時候,我們把 AbortSignal 作為選項傳入該請求的選項物件中(參考下方的 {signal})。這樣會把剛才的中斷訊號與控制器跟 fetch 請求關聯起來,讓我們可以透過呼叫 {{domxref("AbortController.abort()")}} 來中斷該請求。請參考下方範例中第二個事件處理器。

+ +
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('下載已中斷');
+});
+
+function fetchVideo() {
+  ...
+  fetch(url, {signal}).then(function(response) {
+    ...
+  }).catch(function(e) {
+    reports.textContent = '下載錯誤: ' + e.message;
+  })
+}
+ +
+

注意: 當 abort() 被呼叫的時候,fetch() 回傳的 Promise 會被以 AbortError 拒絕。

+
+ +

在 GitHub 有個完整的範例可供參考 — 請參見 abort-api或是也可以實際體驗看看)。

+ +

規格

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#interface-abortcontroller', 'AbortController')}}{{Spec2('DOM WHATWG')}}初始定義
+ +

瀏覽器相容性

+ + + +

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

+ +

參見

+ + diff --git a/files/zh-tw/web/api/ambient_light_events/index.html b/files/zh-tw/web/api/ambient_light_events/index.html new file mode 100644 index 0000000000..06eadc5621 --- /dev/null +++ b/files/zh-tw/web/api/ambient_light_events/index.html @@ -0,0 +1,96 @@ +--- +title: 使用光線事件 +slug: Web/API/Ambient_Light_Events +translation_of: Web/API/Ambient_Light_Events +--- +

{{ SeeCompatTable }}

+

摘要

+

環境光源 (Ambient light) 事件,可告知 Apps 或網頁目前光線強度的變化,以利做出反應,例如改變使用者介面 (User Interface,UI) 的顏色對比,或在拍照時改變曝光程度

+

光源事件

+

只要裝置的光線感測器偵測到光線強度變化,隨即通知瀏覽器。一旦瀏覽器取得該通知,就會發出 DeviceLightEvent 事件而提供光線強度的確實資訊。

+

只要使用 addEventListener 函式 (使用 {{event("devicelight")}} 事件名稱),或將事件處理器 (Event Handler) 附加至 window.ondevicelight 屬性,均可於 window 物件擷取到此事件。

+

一旦擷取完畢,則事件物件將透過 DeviceLightEvent.value 屬性,存取光線強度值 (以 Lux 為單位)。

+

範例

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

規格

+ + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('AmbientLight', '', 'Ambient Light Events') }}{{ Spec2('AmbientLight') }}Initial specification
+

瀏覽器相容性

+

{{ CompatibilityTable() }}

+
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
{{domxref("DeviceLightEvent")}}{{CompatNo()}}{{CompatGeckoDesktop("22.0")}} (Mac OS X only){{CompatNo()}}{{CompatNo()}}{{CompatNo()}}
+
+
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
{{domxref("DeviceLightEvent")}}{{CompatNo()}}{{CompatNo()}}{{CompatGeckoMobile("15.0")}}{{CompatNo()}}{{CompatNo()}}{{CompatNo()}}
+
+

Gecko 說明

+

已建構 {{event("devicelight")}} 事件,且在 Firefox Mobile for Android (15.0) 與 Firefox OS (B2G) 中均預設為開啟。從 Gecko 22.0 (Firefox 22.0 / Thunderbird 22.0 / SeaMonkey 2.19) 開始,亦提供 Mac OS X 的桌機支援。目前對 Windows 7 的支援功能仍開發中 (請見 bug 754199)。

+

另請參閱

+ diff --git a/files/zh-tw/web/api/analysernode/getbytefrequencydata/index.html b/files/zh-tw/web/api/analysernode/getbytefrequencydata/index.html new file mode 100644 index 0000000000..d6b226dd8f --- /dev/null +++ b/files/zh-tw/web/api/analysernode/getbytefrequencydata/index.html @@ -0,0 +1,149 @@ +--- +title: AnalyserNode.getByteFrequencyData() +slug: Web/API/AnalyserNode/getByteFrequencyData +translation_of: Web/API/AnalyserNode/getByteFrequencyData +--- +

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

+ +
+

{{ domxref("AnalyserNode") }} 介面的 getByteFrequencyData() 方法會將當前的頻率資料複製到 {{domxref("Uint8Array")}} (無號 byte 陣列)。

+ +

如果陣列的元素數目比 {{domxref("AnalyserNode.frequencyBinCount")}} 少的話,多餘的元素會被 drop 掉。如果比需要的少的話,多餘的元素會被忽略。

+
+ +

語法

+ +
var audioCtx = new AudioContext();
+var analyser = audioCtx.createAnalyser();
+var dataArray = new Uint8Array(analyser.frequencyBinCount); // Uint8Array 應該要和 frequencyBinCount 等長
+analyser.getByteFrequencyData(dataArray); // 將 getByteFrequencyData() 回傳的資料放進 Uint8Array
+
+ +

回傳值

+ +

{{domxref("Uint8Array")}}。

+ +

範例

+ +

下面的範例顯示出 {{domxref("AudioContext")}} 用於建立一個 AnalyserNode 的基本用法,然後 {{domxref("window.requestAnimationFrame()", "requestAnimationFrame")}} 以及 {{htmlelement("canvas")}} 用來重複收集當前聲音輸入的頻率資料並在 "winamp bargraph style" 畫出輸出。若要知道更完整的範例或是資訊,請參考 Voice-change-O-matic demo (看 app.js 第 128–205 行 會有相關的程式碼)。

+ +
var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
+var analyser = audioCtx.createAnalyser();
+
+  ...
+
+analyser.fftSize = 256;
+var bufferLength = analyser.frequencyBinCount;
+console.log(bufferLength);
+var dataArray = new Uint8Array(bufferLength);
+
+canvasCtx.clearRect(0, 0, WIDTH, HEIGHT);
+
+function draw() {
+  drawVisual = requestAnimationFrame(draw);
+
+  analyser.getByteFrequencyData(dataArray);
+
+  canvasCtx.fillStyle = 'rgb(0, 0, 0)';
+  canvasCtx.fillRect(0, 0, WIDTH, HEIGHT);
+
+  var barWidth = (WIDTH / bufferLength) * 2.5;
+  var barHeight;
+  var x = 0;
+
+  for(var i = 0; i < bufferLength; i++) {
+    barHeight = dataArray[i];
+
+    canvasCtx.fillStyle = 'rgb(' + (barHeight+100) + ',50,50)';
+    canvasCtx.fillRect(x,HEIGHT-barHeight/2,barWidth,barHeight/2);
+
+    x += barWidth + 1;
+  }
+};
+
+draw();
+ +

參數

+ +
+
陣列
+
頻率定義域會被複製進去的 {{domxref("Uint8Array")}} 。
+
+ +

規範

+ + + + + + + + + + + + + + +
規範狀態Comment
{{SpecName('Web Audio API', '#widl-AnalyserNode-getByteFrequencyData-void-Uint8Array-array', 'getByteFrequencyData()')}}{{Spec2('Web Audio API')}} 
+ +

瀏覽器支援度

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

參看

+ + diff --git a/files/zh-tw/web/api/analysernode/index.html b/files/zh-tw/web/api/analysernode/index.html new file mode 100644 index 0000000000..875993cea9 --- /dev/null +++ b/files/zh-tw/web/api/analysernode/index.html @@ -0,0 +1,226 @@ +--- +title: AnalyserNode +slug: Web/API/AnalyserNode +tags: + - API + - AnalyserNode + - Interface + - NeedsTranslation + - Reference + - TopicStub + - Web Audio API +translation_of: Web/API/AnalyserNode +--- +

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

+ +

The AnalyserNode interface represents a node able to provide real-time frequency and time-domain analysis information. It is an {{domxref("AudioNode")}} that passes the audio stream unchanged from the input to the output, but allows you to take the generated data, process it, and create audio visualizations.

+ +

An AnalyzerNode has exactly one input and one output. The node works even if the output is not connected.

+ +

Without modifying the audio stream, the node allows to get the frequency and time-domain data associated to it, using a FFT.

+ + + + + + + + + + + + + + + + + + + + + + + + +
Number of inputs1
Number of outputs1 (but may be left unconnected)
Channel count mode"explicit"
Channel count1
Channel interpretation"speakers"
+ +

Inheritance

+ +

This interface inherits from the following parent interfaces:

+ +

{{InheritanceDiagram}}

+ +

Properties

+ +

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

+ +
+
{{domxref("AnalyserNode.fftSize")}}
+
Is an unsigned long value representing the size of the FFT (Fast Fourier Transform) to be used to determine the frequency domain.
+
{{domxref("AnalyserNode.frequencyBinCount")}} {{readonlyInline}}
+
Is an unsigned long value half that of the FFT size. This generally equates to the number of data values you will have to play with for the visualization.
+
{{domxref("AnalyserNode.minDecibels")}}
+
Is a double value representing the minimum power value in the scaling range for the FFT analysis data, for conversion to unsigned byte values — basically, this specifies the minimum value for the range of results when using getByteFrequencyData().
+
{{domxref("AnalyserNode.maxDecibels")}}
+
Is a double value representing the maximum power value in the scaling range for the FFT analysis data, for conversion to unsigned byte values — basically, this specifies the maximum value for the range of results when using getByteFrequencyData().
+
{{domxref("AnalyserNode.smoothingTimeConstant")}}
+
Is a double value representing the averaging constant with the last analysis frame — basically, it makes the transition between values over time smoother.
+
+ +

Methods

+ +

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

+ +
+
{{domxref("AnalyserNode.getFloatFrequencyData()")}}
+
Copies the current frequency data into a {{domxref("Float32Array")}} array passed into it.
+
+ +
+
{{domxref("AnalyserNode.getByteFrequencyData()")}}
+
Copies the current frequency data into a {{domxref("Uint8Array")}} (unsigned byte array) passed into it.
+
+ +
+
{{domxref("AnalyserNode.getFloatTimeDomainData()")}}
+
Copies the current waveform, or time-domain, data into a {{domxref("Float32Array")}} array passed into it.
+
{{domxref("AnalyserNode.getByteTimeDomainData()")}}
+
Copies the current waveform, or time-domain, data into a {{domxref("Uint8Array")}} (unsigned byte array) passed into it.
+
+ +

Examples

+ +
+

Note: See the guide Visualizations with Web Audio API for more information on creating audio visualizations.

+
+ +

Basic usage

+ +

The following example shows basic usage of an {{domxref("AudioContext")}} to create an AnalyserNode, then {{domxref("window.requestAnimationFrame()","requestAnimationFrame")}} and {{htmlelement("canvas")}} to collect time domain data repeatedly and draw an "oscilloscope style" output of the current audio input. For more complete applied examples/information, check out our Voice-change-O-matic demo (see app.js lines 128–205 for relevant code).

+ +
var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
+var analyser = audioCtx.createAnalyser();
+
+  ...
+
+analyser.fftSize = 2048;
+var bufferLength = analyser.frequencyBinCount;
+var dataArray = new Uint8Array(bufferLength);
+analyser.getByteTimeDomainData(dataArray);
+
+// draw an oscilloscope of the current audio source
+
+function draw() {
+
+      drawVisual = requestAnimationFrame(draw);
+
+      analyser.getByteTimeDomainData(dataArray);
+
+      canvasCtx.fillStyle = 'rgb(200, 200, 200)';
+      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();
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#the-analysernode-interface', 'AnalyserNode')}}{{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
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
+
+ +

See also

+ + diff --git a/files/zh-tw/web/api/animationevent/index.html b/files/zh-tw/web/api/animationevent/index.html new file mode 100644 index 0000000000..d4528894b5 --- /dev/null +++ b/files/zh-tw/web/api/animationevent/index.html @@ -0,0 +1,182 @@ +--- +title: AnimationEvent +slug: Web/API/AnimationEvent +tags: + - API + - CSS + - CSS Animations + - Experimental + - Interface + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/API/AnimationEvent +--- +

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

+ +

摘要

+ +

AnimationEvent 介面表現提供動畫相關資訊的事件。

+ +

{{InheritanceDiagram}}

+ +

性能

+ +

另外從其父 {{domxref("Event")}} 繼承屬性

+ +
+
{{domxref("AnimationEvent.animationName")}} {{readonlyInline}}
+
是一個{{domxref("DOMString")}}包含的值 {{cssxref("animation-name")}} CSS屬性與過渡有關。
+
{{domxref("AnimationEvent.elapsedTime")}} {{readonlyInline}}
+
是一個float給予時間的動畫已經運行,以秒為單位,當該事件燒製,不含動畫被暫停的任何時間量。為一個"animationstart"事件,elapsedTime0.0,除非有一個負值{{cssxref("animation-delay")}},在這種情況下,該事件將與燒製elapsedTime含有 (-1 * delay)
+
{{domxref("AnimationEvent.pseudoElement")}} {{readonlyInline}}
+
是一個{{domxref("DOMString")}},從"::",包含的名字虛擬元素的動畫運行。如果動畫上不偽元素,但該元素,一個空字符串上運行:''。
+
+ +

構造函數

+ +
+
{{domxref("AnimationEvent.AnimationEvent","AnimationEvent()")}}
+
創建一個AnimationEvent事件具有給定參數。
+
+ +

方法

+ +

同時繼承其父{{domxref("事件")}}方法

+ +
+
{{domxref("AnimationEvent.initAnimationEvent()")}} {{non-standard_inline}}{{deprecated_inline}}
+
初始化AnimationEvent 使用過時的創建 {{domxref("Document.createEvent()", "Document.createEvent(\"AnimationEvent\")")}} 方法。
+
+ +

規範

+ + + + + + + + + + + + + + + + +
產品規格狀態註解
{{ SpecName('CSS3 Animations', '#AnimationEvent-interface', 'AnimationEvent') }}{{ Spec2('CSS3 Animations') }}初始定義。
+ +

瀏覽器兼容性

+ +

{{CompatibilityTable()}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
特點ChromeFirefox (Gecko)Internet ExplorerOperaSafari
基本支持1.0 {{ property_prefix("webkit") }}{{CompatGeckoDesktop("6.0")}}10.012 {{property_prefix("O")}}
+ 12.10
+ 15.0 {{ property_prefix("webkit") }}
4.0 {{ property_prefix("webkit") }}
AnimationEvent()構造函數{{CompatNo}}{{CompatGeckoDesktop("23.0")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
initAnimationEvent(){{non-standard_inline}} {{deprecated_inline}}1.0{{CompatGeckoDesktop("6.0")}}
+ 在{{CompatGeckoDesktop("23.0")}}刪除
10.0124
pseudoelement{{CompatNo}}{{CompatGeckoDesktop("23.0")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
特點AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
基本支持{{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()構造函數{{CompatNo}}{{CompatGeckoMobile("23.0")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
initAnimationEvent(){{non-standard_inline}} {{deprecated_inline}}{{CompatVersionUnknown}}{{CompatGeckoMobile("6.0")}}
+ 在{{CompatGeckoMobile("23.0")}}刪除
10.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}
pseudoelement{{CompatNo}}{{CompatGeckoMobile("23.0")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

另請參見

+ + diff --git a/files/zh-tw/web/api/animationevent/initanimationevent/index.html b/files/zh-tw/web/api/animationevent/initanimationevent/index.html new file mode 100644 index 0000000000..de5c7efe15 --- /dev/null +++ b/files/zh-tw/web/api/animationevent/initanimationevent/index.html @@ -0,0 +1,129 @@ +--- +title: AnimationEvent.initAnimationEvent() +slug: Web/API/AnimationEvent/initAnimationEvent +tags: + - API + - AnimationEvent + - CSSOM + - Method + - Obsolete + - Web Animations +translation_of: Web/API/AnimationEvent/initAnimationEvent +--- +

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

+ +

Summary

+ +

The AnimationEvent.initAnimationEvent() method Initializes an animation event created using the deprecated {{domxref("Document.createEvent()", "Document.createEvent(\"AnimationEvent\")")}} method.

+ +

AnimationEvent created this way are untrusted.

+ +
+

Note: During the standardization process, this method was removed from the specification. It has been deprecated and is in the progress of being removed from most implementations. Do not use this method; instead, use the standard constructor, {{domxref("AnimationEvent.AnimationEvent", "AnimationEvent()")}}, to create a synthetic {{domxref("AnimationEvent")}}.

+
+ +

Syntax

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

Parameters

+ +
+
typeArg
+
A {{domxref("DOMString")}} identifying the specific type of animation event that occurred. The following values are allowed: + + + + + + + + + + + + + + + + + + + + + +
ValueMeaning
animationstartThe animation has started.
animationendThe animation completed.
animationiterationThe current iteration just completed.
+
+
canBubbleArg
+
A {{domxref("Boolean")}} flag indicating if the event can bubble (true) or not (false).
+
cancelableArg
+
A {{domxref("Boolean")}} flag indicating if the event associated action can be avoided (true) or not (false).
+
animationNameArg
+
A {{domxref("DOMString")}} containing the value of the {{cssxref("animation-name")}} CSS property associated with the transition.
+
elapsedTimeArg
+
A float indicating the amount of time the animation has been running, in seconds, as of the time the event was fired, excluding any time the animation was paused. For an "animationstart" event, elapsedTime is 0.0 unless there was a negative value for animation-delay, in which case the event will be fired with elapsedTime containing  (-1 * delay).
+
+ +

Specifications

+ +

This method is non-standard and not part of any specification, though it was present in early drafts of {{SpecName("CSS3 Animations")}}.

+ +

Browser compatibility

+ +

{{ CompatibilityTable }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{ CompatGeckoDesktop("6.0") }}
+ Removed in {{ CompatGeckoDesktop("23.0") }}
10.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox 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/zh-tw/web/api/battery_status_api/index.html b/files/zh-tw/web/api/battery_status_api/index.html new file mode 100644 index 0000000000..cbf98d417d --- /dev/null +++ b/files/zh-tw/web/api/battery_status_api/index.html @@ -0,0 +1,38 @@ +--- +title: Battery Status API +slug: Web/API/Battery_Status_API +translation_of: Web/API/Battery_Status_API +--- +

Battery Status API 也就是所謂的 Battery API,將提供系統電池充電容量的資訊,並在電池容量變化時送出事件,以通知使用者。此 API 可調整 Apps 的資源耗用量,在電力偏低時縮減耗電量;或可在電力耗盡之前儲存檔案,避免資料遺失。

+

Battery Status API 是以 window.navigator.battery 屬性 (為 BatteryManager 物件) 而擴充了 window.navigator,並新增數項可讓使用者接收的新事件,以隨時監控電池狀態。

+

範例

+

在此範例中,我們將分別監聽 chargingchangelevelchange 事件,而看到充電狀態 (不論是否插電進行充電) 與電池容量的變化。

+
var battery = navigator.battery || navigator.mozBattery || navigator.webkitBattery;
+
+function updateBatteryStatus() {
+  console.log("Battery status: " + battery.level * 100 + " %");
+
+  if (battery.charging) {
+    console.log("Battery is charging");
+  }
+}
+
+battery.addEventListener("chargingchange", updateBatteryStatus);
+battery.addEventListener("levelchange", updateBatteryStatus);
+updateBatteryStatus();
+
+

另可參閱規格所提供之範例

+

規格

+

{{page("/en-US/docs/Web/API/BatteryManager","Specifications")}}

+

瀏覽器相容性

+

{{page("/en-US/docs/Web/API/BatteryManager","Browser_compatibility")}}

+

另請參閱

+ diff --git a/files/zh-tw/web/api/blob/blob/index.html b/files/zh-tw/web/api/blob/blob/index.html new file mode 100644 index 0000000000..26fb1e8ef7 --- /dev/null +++ b/files/zh-tw/web/api/blob/blob/index.html @@ -0,0 +1,125 @@ +--- +title: Blob() +slug: Web/API/Blob/Blob +translation_of: Web/API/Blob/Blob +--- +

{{APIRef("File API")}}

+ +

Blob() 建構式會回傳一個新建立的 {{domxref("Blob")}} 物件。新物件的內容是由 array 參數的成員值串連所構成。

+ +

語法

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

參數

+ + + +

範例

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

規範

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('File API', '#constructorBlob', 'Blob()')}}{{Spec2('File API')}}Initial definition.
+ +

瀏覽器相容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
功能ChromeFirefox (Gecko)Internet ExplorerOperaSafari
+

基礎支援

+
20{{CompatGeckoDesktop("13.0")}} [1]1012.108
在 Workers 中{{CompatUnknown}}{{CompatGeckoDesktop("14.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
功能AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
基礎支援{{CompatUnknown}}{{CompatGeckoMobile("13.0")}} [1]{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
在 Workers 中{{CompatUnknown}}{{CompatGeckoMobile("14.0")}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] 在 Firefox 16 以前,第二個參數若被設為 nullundefined 會導致錯誤而不是當成一個空鍵值。

+ +

參見

+ + + +

 

diff --git a/files/zh-tw/web/api/blob/index.html b/files/zh-tw/web/api/blob/index.html new file mode 100644 index 0000000000..457628556c --- /dev/null +++ b/files/zh-tw/web/api/blob/index.html @@ -0,0 +1,116 @@ +--- +title: Blob +slug: Web/API/Blob +translation_of: Web/API/Blob +--- +

{{APIRef("File API")}}

+ +

Blob(Binary Large Object)物件代表了一個相當於檔案(原始資料)的不可變物件。Blob 中的資料並不一定是 JavaScript 原生的格式。{{domxref("File")}} 介面基於 Blob,繼承 blob 並擴充其功能以支援操作使用者系統上的檔案。

+ +

從其它非 Blob 物件或資料來建構 Blob 物件,可以使用 {{domxref("Blob.Blob", "Blob()")}} 建構式。要建立一個包含目前 blob 內容子集的 blob,可使用 {{domxref("Blob.slice()", "slice()")}} 方法。若要自使用者系統上的檔案取得 Blob 物件,請參考 {{domxref("File")}} 文件。

+ +

接受 Blob 物件的 API 可以在 {{domxref("File")}} 上找到。

+ +
+

註:早期 slice() 方法擁有第二個參數 length 以指定在建立新 Blob 物件時要複製的位元組(byte)數量。假如指定的 start + length 超出了來源 Blob 的大小,則回傳的 Blob 會包含自索引 start 至結尾的完整來源內容。

+
+ +
+

註:需注意在部分瀏覽器版本中,slice() 方法帶有前綴:Firefox 12 與之前的版本為 blob.mozSlice(),Safari 中是 blob.webkitSlice()。舊的、無前綴字版本的 slice() 方法則有不同的語意(semantics),但這是已淘汰的方法。瀏覽器對 blob.mozSlice() 的支援已在 Firefox 30 時中止。

+
+ +

建構式

+ +
+
{{domxref("Blob.Blob", "Blob(blobParts[, options])")}}
+
回傳新建立的 Blob 物件,包含了建構式參數傳入之陣列所串聯後的值。第二個參數為 BlobPropertyBag 物件,其擁有 type 和 endings 屬性
+
+ +

屬性

+ +
+
{{domxref("Blob.size")}} {{readonlyinline}}
+
以 byte 為單位的 Blob 物件大小。
+
{{domxref("Blob.type")}} {{readonlyinline}}
+
Blob 物件中資料的型態,以 MIME 類型的字串表示。若型態為未知,則為空字串。
+
+ +

方法

+ +
+
{{domxref("Blob.slice()", "Blob.slice([start[, end[, contentType]]])")}}
+
回傳一個包含當前 Blob 物件之指定資料範圍(byte)內容的新 Blob 物件。
+
+ +

範例

+ +

Blob 建構函數用法範例

+ +

{{domxref("Blob.Blob", "Blob() constructor")}} 建構式允許由其它物件建立 blob 物件。以下的範例演示了以字串來建構 blob 物件:

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

在 Blob 建構式出現之前,可以透過 {{domxref("BlobBuilder")}} 來建立 blob 物件(目前已不建議使用):

+ +
var builder = new BlobBuilder();
+var fileParts = ['<a id="a"><b id="b">hey!</b></a>'];
+builder.append(fileParts[0]);
+var myBlob = builder.getBlob('text/xml');
+
+ +

藉型別陣列建構的 blob 來建立 URL

+ +

範例程式碼:

+ +
var typedArray = GetTheTypedArraySomehow();
+var blob = new Blob([typedArray], {type: 'application/octet-binary'}); // pass a useful mime type here
+var url = URL.createObjectURL(blob);
+// url will be something like: blob:d3958f5c-0777-0845-9dcf-2cb28783acaf
+// now you can use the url in any context that regular URLs can be used in, for example img.src, etc.
+
+ +

從 Blob 取出資料

+ +

從 Blob 讀取資料的唯一方式就是使用 {{domxref("FileReader")}}。以下範例展示了讀取 Blob 內容作為型別陣列:

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

藉由操作 {{domxref("FileReader")}} 的其他方法,將 Blob 讀取成字串或是 data URL 是有可能的。

+ +

規範

+ + + + + + + + + + + + + + +
規範狀態註解
{{SpecName('File API','#blob','Blob')}}{{Spec2('File API')}}Initial definition.
+ +

瀏覽器相容性

+ + + +

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

+ +

參見

+ + diff --git a/files/zh-tw/web/api/blob/size/index.html b/files/zh-tw/web/api/blob/size/index.html new file mode 100644 index 0000000000..0abccad27d --- /dev/null +++ b/files/zh-tw/web/api/blob/size/index.html @@ -0,0 +1,114 @@ +--- +title: Blob.size +slug: Web/API/Blob/size +tags: + - API + - Files + - Property + - Reference + - WebAPI + - 參考 + - 屬性 +translation_of: Web/API/Blob/size +--- +
{{APIRef("File API")}}
+ +

Blob.size 屬性回傳以 byte 為單位的 {{domxref("Blob")}} 或一個 {{domxref("File")}} 的大小。

+ +

語法

+ +
var sizeInBytes = blob.size
+
+ +

+ +

一個數字。

+ +

範例

+ +
// fileInput 是個 HTMLInputElement: <input type="file" multiple id="myfileinput">
+var fileInput = document.getElementById("myfileinput");
+
+// files 是個 FileList 物件 (類似 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");
+}
+ +

規格

+ + + + + + + + + + + + + + +
規格狀態附註
{{SpecName('File API', '#dfn-size', 'size')}}{{Spec2('File API')}}初定義
+ +

瀏覽器相容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
功能ChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
File.size5{{CompatVersionUnknown}}{{CompatGeckoDesktop("2")}}10.011.105.1
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
功能AndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
File.size{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

參見

+ + diff --git a/files/zh-tw/web/api/blob/type/index.html b/files/zh-tw/web/api/blob/type/index.html new file mode 100644 index 0000000000..ee2a231724 --- /dev/null +++ b/files/zh-tw/web/api/blob/type/index.html @@ -0,0 +1,114 @@ +--- +title: Blob.type +slug: Web/API/Blob/type +translation_of: Web/API/Blob/type +--- +
{{APIRef("File API")}}
+ +

Blob 物件的 type 屬性提供檔案的 MIME 類別。若無法辨明型別則回傳空字串。

+ +

語法

+ +
var mimetype = instanceOfFile.type
+ +

+ +

一個字串。

+ +

範例

+ +
var i, fileInput, files, allowedFileTypes;
+
+// fileInput 是個 HTMLInputElement: <input type="file" multiple id="myfileinput">
+fileInput = document.getElementById("myfileinput");
+
+// files 是個 FileList 物件 (類似 NodeList)
+files = fileInput.files;
+
+// 這範例接受 *.png, *.jpeg 和 *.gif 圖片。
+allowedFileTypes = ["image/png", "image/jpeg", "image/gif"];
+
+for (i = 0; i < files.length; i++) {
+  // 測試 file.type 是否是允許的類別。
+  if (allowedFileTypes.indexOf(files[i].type) > -1) {
+    // 若符合則執行這裡的程式碼。
+  }
+});
+
+ +

規格

+ + + + + + + + + + + + + + +
規格狀態備註
{{SpecName('File API', '#dfn-type', 'type')}}{{Spec2('File API')}}初定義
+ +

瀏覽器相容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
功能ChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
File.type5{{CompatVersionUnknown}}{{CompatGeckoDesktop("2")}}10.011.105.1
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
功能AndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
File.type{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

參見

+ + diff --git a/files/zh-tw/web/api/body/index.html b/files/zh-tw/web/api/body/index.html new file mode 100644 index 0000000000..82ba54e53d --- /dev/null +++ b/files/zh-tw/web/api/body/index.html @@ -0,0 +1,99 @@ +--- +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 {{domxref("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 {{domxref("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

+ +
var myImage = document.querySelector('.my-image');
+fetch('https://upload.wikimedia.org/wikipedia/commons/7/77/Delete_key1.jpg')
+	.then(res => res.blob())
+	.then(res => {
+		var 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/zh-tw/web/api/body/json/index.html b/files/zh-tw/web/api/body/json/index.html new file mode 100644 index 0000000000..70085afff7 --- /dev/null +++ b/files/zh-tw/web/api/body/json/index.html @@ -0,0 +1,73 @@ +--- +title: Body.json() +slug: Web/API/Body/json +translation_of: Web/API/Body/json +--- +
{{APIRef("Fetch")}}
+ +

{{domxref("Body")}} mixin 的 json() 會拿 {{domxref("Response")}} stream 並完整地讀取他。它會回傳一個能夠實現 (resolve) 把回傳的結果的 body text 解析成 {{jsxref("JSON")}} 型別的 Promise。

+ +

語法

+ +
response.json().then(function(data) {
+  // do something with your data
+});
+ +

參數

+ +

None.

+ +

回傳

+ +

一個能夠實現 (resolve) 把回傳的結果的 body text 解析成 JSON 型別的 Promise。這可以是任何能夠被 JSON 呈現的資料型別 — 物件 (object), 陣列 (array), 字串 (string), 數字 (number)...

+ +

範例

+ +

在我們的範例 fetch json example (run fetch json live) 中,我們用 constructor {{domxref("Request.Request")}} 產生一個新的請求,並且用它去取回 .json 檔案。 當成功取回 (fetch) 時,我們使用 json() 去讀取跟解析資料,然後依照我們期待的把回傳的結果物件 (resulting objects) 裡讀取到的數值存入 list 中藉以顯示我們的產品資料。

+ +
var myList = document.querySelector('ul');
+
+var myRequest = new Request('products.json');
+
+fetch(myRequest)
+  .then(function(response) { return response.json(); })
+  .then(function(data) {
+    for (var i = 0; i < data.products.length; i++) {
+      var listItem = document.createElement('li');
+      listItem.innerHTML = '<strong>' + data.products[i].Name + '</strong> can be found in ' +
+                           data.products[i].Location +
+                           '. Cost: <strong>£' + data.products[i].Price + '</strong>';
+      myList.appendChild(listItem);
+    }
+  });
+ +

規範

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fetch','#dom-body-json','json()')}}{{Spec2('Fetch')}}
+ +

瀏覽器相容性

+ + + +

{{Compat("api.Body.json")}}

+ +

參見

+ + diff --git a/files/zh-tw/web/api/canvas_api/drawing_graphics_with_canvas/index.html b/files/zh-tw/web/api/canvas_api/drawing_graphics_with_canvas/index.html new file mode 100644 index 0000000000..c93ad87e10 --- /dev/null +++ b/files/zh-tw/web/api/canvas_api/drawing_graphics_with_canvas/index.html @@ -0,0 +1,161 @@ +--- +title: Drawing graphics with canvas +slug: Web/API/Canvas_API/Drawing_graphics_with_canvas +translation_of: Web/API/Canvas_API/Tutorial +--- +
+

Most of this content (but not the documentation on drawWindow) has been rolled into the more expansive Canvas tutorial, this page should probably be redirected there as it's now redundant but some information may still be relevant.

+
+

介紹

+

  在 Firefox 1.5, Firefox 引入了新的 HTML 元素 <canvas> 來繪製圖形。<canvas> 是基於 WHATWG canvas specification 的技術 (其發軔於蘋果公司在 Safari 上的實做)。 我們可以用它來在使用者端進行圖形和 UI 元件的渲染。

+

  <canvas> 創建了一個具有一致多個 rendering contexts 的區域。在本文中,我們著重於 2D rendering context 的部份。對於 3D 圖形,您可以參考 WebGL rendering context

+

2D Rendering Context

+

先來個簡單的範例

+

  以下的程式碼做了一個簡單的展示:繪製兩個部份交疊的矩形 (其中一個矩形有透明屬性) :

+
function draw() {
+  var ctx = document.getElementById('canvas').getContext('2d');
+
+  ctx.fillStyle = "rgb(200,0,0)";
+  ctx.fillRect (10, 10, 55, 50);
+
+  ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
+  ctx.fillRect (30, 30, 55, 50);
+}
+
+ +

{{EmbedLiveSample('A_Simple_Example','150','150','/@api/deki/files/602/=Canvas_ex1.png')}}

+

  這個名為 draw 的函式從 canvas element 取得 2d context。物件 ctx 可以被用來在 canvas 上頭繪製圖形。從程式碼可以看出,我們簡單的藉由設定 fillStyle 繪製了兩個顏色不同的矩形,並透過 fillRect 設定其位置。此外,第二個矩形透過 rgba() 配置了透明屬性。

+

  關於更複雜的圖形繪製,我們可以使用 fillRect, strokeRect 和 clearRect,他們分別可以畫出填滿的矩形, 僅有外框的矩形以及矩形區域清除。

+

路徑的使用

+

  beginPath 函式用來初始一段路徑的繪製,並且可以透過 moveTo, lineTo, arcTo, arc 以及相關的函式來描述路徑內容。要結束的時候呼叫 closePath 即可。一旦路徑描述完畢,就可以透過 fill 或 stroke 來渲染該路徑在 canvas 上。

+
function draw() {
+  var ctx = document.getElementById('canvas').getContext('2d');
+
+  ctx.fillStyle = "red";
+
+  ctx.beginPath();
+  ctx.moveTo(30, 30);
+  ctx.lineTo(150, 150);
+  // was: ctx.quadraticCurveTo(60, 70, 70, 150); which is wrong.
+  ctx.bezierCurveTo(60, 70, 60, 70, 70, 150); // <- this is right formula for the image on the right ->
+  ctx.lineTo(30, 30);
+  ctx.fill();
+}
+
+ +

{{EmbedLiveSample('Using_Paths','190','190','/@api/deki/files/603/=Canvas_ex2.png')}}

+

  呼叫 fill() 或 stroke() 代表該路徑已經被使用。若要重新進行填滿等動作,則需要重頭創造一次路徑。

+

圖像狀態

+

  fillStyle, strokeStyle, lineWidth 和 lineJoin 等屬性是 graphics state 的一部分。關於這些屬性的修改,您可以透過 save() 及 restore() 來進行操作。

+

一個更為複雜的範例

+

  接著我們來看一個稍微複雜一點的範例,它同時引入了路徑, 狀態的修改以及變換矩陣。

+
function drawBowtie(ctx, fillStyle) {
+
+  ctx.fillStyle = "rgba(200,200,200,0.3)";
+  ctx.fillRect(-30, -30, 60, 60);
+
+  ctx.fillStyle = fillStyle;
+  ctx.globalAlpha = 1.0;
+  ctx.beginPath();
+  ctx.moveTo(25, 25);
+  ctx.lineTo(-25, -25);
+  ctx.lineTo(25, -25);
+  ctx.lineTo(-25, 25);
+  ctx.closePath();
+  ctx.fill();
+}
+
+function dot(ctx) {
+  ctx.save();
+  ctx.fillStyle = "black";
+  ctx.fillRect(-2, -2, 4, 4);
+  ctx.restore();
+}
+
+function draw() {
+  var ctx = document.getElementById('canvas').getContext('2d');
+
+  // note that all other translates are relative to this one
+  ctx.translate(45, 45);
+
+  ctx.save();
+  //ctx.translate(0, 0); // unnecessary
+  drawBowtie(ctx, "red");
+  dot(ctx);
+  ctx.restore();
+
+  ctx.save();
+  ctx.translate(85, 0);
+  ctx.rotate(45 * Math.PI / 180);
+  drawBowtie(ctx, "green");
+  dot(ctx);
+  ctx.restore();
+
+  ctx.save();
+  ctx.translate(0, 85);
+  ctx.rotate(135 * Math.PI / 180);
+  drawBowtie(ctx, "blue");
+  dot(ctx);
+  ctx.restore();
+
+  ctx.save();
+  ctx.translate(85, 85);
+  ctx.rotate(90 * Math.PI / 180);
+  drawBowtie(ctx, "yellow");
+  dot(ctx);
+  ctx.restore();
+}
+
+ +

{{EmbedLiveSample('A_More_Complicated_Example','215','215','/@api/deki/files/604/=Canvas_ex3.png')}}

+

  我們自定義了兩個函式: drawBowtie 以及 dot,並且個別呼叫了四次。在呼叫他們之前,我們使用了 translate()rotate() 來設定接著要繪製圖形的 transformation matrix,這將改變最終 dot 和 bowtie 的位置。dot 繪製了一個以 (0, 0) 為中心的小黑正方形,而 drawBowtie 產生了一個填滿的蝴蝶結樣貌的圖形。

+

  save() 和 restore() 規範了一系列動作的初始和結尾。一個值得注意的地方是,旋轉的動作是基於該圖形當下所在的位置, 所以 translate() -> rotate() -> translate() 的結果會和 translate() -> translate() -> rotate() 不同。

+

和 Apple <canvas> 的相容性

+

For the most part, <canvas> is compatible with Apple's and other implementations. There are, however, a few issues to be aware of, described here.

+

</canvas> tag 是必要的

+

In the Apple Safari implementation, <canvas> is an element implemented in much the same way <img> is; it does not have an end tag. However, for <canvas> to have widespread use on the web, some facility for fallback content must be provided. Therefore, Mozilla's implementation has a required end tag.

+

If fallback content is not needed, a simple <canvas id="foo" ...></canvas> will be fully compatible with both Safari and Mozilla -- Safari will simply ignore the end tag.

+

If fallback content is desired, some CSS tricks must be employed to mask the fallback content from Safari (which should render just the canvas), and also to mask the CSS tricks themselves from IE (which should render the fallback content).

+
canvas {
+  font-size: 0.00001px !ie;
+}
+

其他特性

+

藉由 Canvas 渲染網頁內容

+
+ This feature is only available for code running with Chrome privileges. It is not allowed in normal HTML pages. Read why.
+

Mozilla's canvas is extended with the drawWindow() method. This method draws a snapshot of the contents of a DOM window into the canvas. For example,

+
ctx.drawWindow(window, 0, 0, 100, 200, "rgb(255,255,255)");
+
+

would draw the contents of the current window, in the rectangle (0,0,100,200) in pixels relative to the top-left of the viewport, on a white background, into the canvas. By specifying "rgba(255,255,255,0)" as the color, the contents would be drawn with a transparent background (which would be slower).

+

It is usually a bad idea to use any background other than pure white "rgb(255,255,255)" or transparent, as this is what all browsers do, and many websites expect that transparent parts of their interface will be drawn on white background.

+

With this method, it is possible to fill a hidden IFRAME with arbitrary content (e.g., CSS-styled HTML text, or SVG) and draw it into a canvas. It will be scaled, rotated and so on according to the current transformation.

+

Ted Mielczarek's tab preview extension uses this technique in chrome to provide thumbnails of web pages, and the source is available for reference.

+
+ Note: Using canvas.drawWindow() while handling a document's onload event doesn't work. In Firefox 3.5 or later, you can do this in a handler for the MozAfterPaint event to successfully draw HTML content into a canvas on page load.
+

更多資訊

+ diff --git a/files/zh-tw/web/api/canvas_api/index.html b/files/zh-tw/web/api/canvas_api/index.html new file mode 100644 index 0000000000..c07ec36738 --- /dev/null +++ b/files/zh-tw/web/api/canvas_api/index.html @@ -0,0 +1,158 @@ +--- +title: Canvas API +slug: Web/API/Canvas_API +translation_of: Web/API/Canvas_API +--- +
{{CanvasSidebar}}
+ +

{{HTMLElement("canvas")}}HTML5 的新元素,可透過 Script(通常是 JavaScript)繪製圖形。例如,可以用來繪圖、合成圖照片、建立動畫、甚至處理即時的影片播放。

+ +

Mozilla 應用程式從 Gecko 1.8(也就是 Firefox 1.5)起開始支援 <canvas>。這個元素最初由蘋果 OS X Dashboard 和 Safari 引入。Internet Explorer 9 以上版本也有支援 <canvas>,但較舊的 IE 版本則須嵌入 Google Explorer Canvas 專案中的程式腳本,才能得到有效的支援。Opera 9 也支援 <canvas>

+ +

<canvas> 元素通常也被 WebGL 用來在網頁上顯示使用硬體加速繪製的 3D 圖形。

+ +

範例

+ +

這則簡單的範例使用了{{domxref("CanvasRenderingContext2D.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);
+
+ +

Edit the code below and see your changes update live in the canvas:

+ + + +

{{ EmbedLiveSample('Playable_code', 700, 360) }}

+ +

參考

+ +
+ +
+ +

這些與WebGLRenderingContext有關的標識,皆引用在WebGL

+ +

教程指南

+ +
+
Canvas tutorial
+
這個全部的課程包含 <canvas> 基礎的使用和高階的應用。
+
Code snippets: Canvas
+
一些延伸的開發功能,包含<canvas>
+
Demo: A basic ray-caster
+
使用<canvas>做的光線追蹤(ray-tracing )範例。
+
Drawing DOM objects into a canvas
+
如何在 DOM<canvas>之中,畫個物件。例如 HTML的元素。
+
Manipulating video using canvas
+
結合{{HTMLElement("video")}} 和 {{HTMLElement("canvas")}} 去控制影像資料的真實時間
+
+ +

資源

+ +

Generic

+ + + +

Libraries

+ + + +

規範

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "the-canvas-element.html", "Canvas")}}{{Spec2('HTML WHATWG')}} 
+ +

參見

+ + diff --git a/files/zh-tw/web/api/canvas_api/tutorial/advanced_animations/index.html b/files/zh-tw/web/api/canvas_api/tutorial/advanced_animations/index.html new file mode 100644 index 0000000000..caacb185aa --- /dev/null +++ b/files/zh-tw/web/api/canvas_api/tutorial/advanced_animations/index.html @@ -0,0 +1,376 @@ +--- +title: Advanced animations +slug: Web/API/Canvas_API/Tutorial/Advanced_animations +translation_of: Web/API/Canvas_API/Tutorial/Advanced_animations +--- +
{{CanvasSidebar}} {{PreviousNext("Web/API/Canvas_API/Tutorial/Basic_animations", "Web/API/Canvas_API/Tutorial/Pixel_manipulation_with_canvas")}}
+ +
+

在上一章節,我們做了一些基礎動畫且知道它的移動方式。在這部分我們更仔細的介紹它的動畫效果且並增加一些特效,使它看起來更高級。

+
+ +

畫一顆球

+ +

在這次的動畫練習中使用球來練習。照著下面的步驟完成 canvas 設定。

+ +
<canvas id="canvas" width="600" height="300"></canvas>
+
+ +

照常理,先在canvas上需要先畫一顆球。創造一個 ball object,它包含的屬性和draw()的方法,使canvas可以在上面繪圖。

+ +
var canvas = document.getElementById('canvas');
+var ctx = canvas.getContext('2d');
+
+var ball = {
+  x: 100,
+  y: 100,
+  radius: 25,
+  color: 'blue',
+  draw: function() {
+    ctx.beginPath();
+    ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, true);
+    ctx.closePath();
+    ctx.fillStyle = this.color;
+    ctx.fill();
+  }
+};
+
+ball.draw();
+ +

這裡沒什麼特別的,透過{{domxref("CanvasRenderingContext2D.arc()", "arc()")}}的方法,球事實上只是畫下簡單的圓。

+ +

添加速度

+ +

現在有了一顆球,準備添加基礎的動畫像我們從上章節學到的課程。再次使用{{domxref("window.requestAnimationFrame()")}}控制動畫。添加移動的向量速度使球移動到向量點。對於每個幀(frame),我們使用{{domxref("CanvasRenderingContext2D.clearRect", "clear", "", 1)}}來清除canvas舊的移動幀(frame)。

+ +
var canvas = document.getElementById('canvas');
+var ctx = canvas.getContext('2d');
+var raf;
+
+var ball = {
+  x: 100,
+  y: 100,
+  vx: 5,
+  vy: 2,
+  radius: 25,
+  color: 'blue',
+  draw: function() {
+    ctx.beginPath();
+    ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, true);
+    ctx.closePath();
+    ctx.fillStyle = this.color;
+    ctx.fill();
+  }
+};
+
+function draw() {
+  ctx.clearRect(0,0, canvas.width, canvas.height);
+  ball.draw();
+  ball.x += ball.vx;
+  ball.y += ball.vy;
+  raf = window.requestAnimationFrame(draw);
+}
+
+canvas.addEventListener('mouseover', function(e) {
+  raf = window.requestAnimationFrame(draw);
+});
+
+canvas.addEventListener('mouseout', function(e) {
+  window.cancelAnimationFrame(raf);
+});
+
+ball.draw();
+
+ +

邊界

+ +

沒有任何邊界碰撞下,球很快就會跑出canvas。這時需要確認球的 x and y 是否超出 canvas 尺寸,若超出則將球的向量顛倒。所以,我們添加了確認條件在draw方法:

+ +
if (ball.y + ball.vy > canvas.height || ball.y + ball.vy < 0) {
+  ball.vy = -ball.vy;
+}
+if (ball.x + ball.vx > canvas.width || ball.x + ball.vx < 0) {
+  ball.vx = -ball.vx;
+}
+ +

第一個示範

+ +

讓我們看看,看似很遠的行徑它如何行徑。移動你的滑鼠在canvas,使動畫開始。 

+ + + +

{{EmbedLiveSample("First_demo", "610", "310")}}

+ +

加速性能

+ +

為了使移動看起來更真實,你可以照著範例改變速度:

+ +
ball.vy *= .99;
+ball.vy += .25;
+ +

這個使每個幀(frame)的垂直向量減少,所以球將只會在地板彈跳直到結束。

+ + + +

{{EmbedLiveSample("Second_demo", "610", "310")}}

+ +

追蹤效果

+ +

直到現在我們已經使用{{domxref("CanvasRenderingContext2D.clearRect", "clearRect")}}方法清除之前的幀(frames)。如果使用重置半透明{{domxref("CanvasRenderingContext2D.fillRect", "fillRect")}}這個方法,可以更淺顯的看出創造追蹤效果。

+ +
ctx.fillStyle = 'rgba(255, 255, 255, 0.3)';
+ctx.fillRect(0, 0, canvas.width, canvas.height);
+ + + +

{{EmbedLiveSample("Third_demo", "610", "310")}}

+ +

增加滑鼠控制

+ +

為了能控制球使它跟著滑鼠移動,在這個範例使用mousemove 效果。當 click 事件觸發了這顆球,它又會開始彈跳。

+ + + +
var canvas = document.getElementById('canvas');
+var ctx = canvas.getContext('2d');
+var raf;
+var running = false;
+
+var ball = {
+  x: 100,
+  y: 100,
+  vx: 5,
+  vy: 1,
+  radius: 25,
+  color: 'blue',
+  draw: function() {
+    ctx.beginPath();
+    ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, true);
+    ctx.closePath();
+    ctx.fillStyle = this.color;
+    ctx.fill();
+  }
+};
+
+function clear() {
+  ctx.fillStyle = 'rgba(255, 255, 255, 0.3)';
+  ctx.fillRect(0,0,canvas.width,canvas.height);
+}
+
+function draw() {
+  clear();
+  ball.draw();
+  ball.x += ball.vx;
+  ball.y += ball.vy;
+
+  if (ball.y + ball.vy > canvas.height || ball.y + ball.vy < 0) {
+    ball.vy = -ball.vy;
+  }
+  if (ball.x + ball.vx > canvas.width || ball.x + ball.vx < 0) {
+    ball.vx = -ball.vx;
+  }
+
+  raf = window.requestAnimationFrame(draw);
+}
+
+canvas.addEventListener('mousemove', function(e) {
+  if (!running) {
+    clear();
+    ball.x = e.clientX;
+    ball.y = e.clientY;
+    ball.draw();
+  }
+});
+
+canvas.addEventListener('click', function(e) {
+  if (!running) {
+    raf = window.requestAnimationFrame(draw);
+    running = true;
+  }
+});
+
+canvas.addEventListener('mouseout', function(e) {
+  window.cancelAnimationFrame(raf);
+  running = false;
+});
+
+ball.draw();
+
+ +

用你的滑鼠移動這顆球且點擊鬆放它。

+ +

{{EmbedLiveSample("Adding_mouse_control", "610", "310")}}

+ +

突破性(遊戲)

+ +

這個小章節只有解釋一些創造高級動畫的技巧。這裡還有更多!如何增加槳,磚塊,到這個 到 Breakout game demo去看,有我們更多遊戲研發的文章! 

+ +

延伸閱讀

+ + + +

{{PreviousNext("Web/API/Canvas_API/Tutorial/Basic_animations", "Web/API/Canvas_API/Tutorial/Pixel_manipulation_with_canvas")}}

diff --git a/files/zh-tw/web/api/canvas_api/tutorial/applying_styles_and_colors/index.html b/files/zh-tw/web/api/canvas_api/tutorial/applying_styles_and_colors/index.html new file mode 100644 index 0000000000..86e41e3476 --- /dev/null +++ b/files/zh-tw/web/api/canvas_api/tutorial/applying_styles_and_colors/index.html @@ -0,0 +1,669 @@ +--- +title: 套用樣式與顏色 +slug: Web/API/Canvas_API/Tutorial/Applying_styles_and_colors +translation_of: Web/API/Canvas_API/Tutorial/Applying_styles_and_colors +--- +
{{CanvasSidebar}} {{PreviousNext("Web/API/Canvas_API/Tutorial/Drawing_shapes", "Web/API/Canvas_API/Tutorial/Drawing_text")}}
+ +

繪畫圖形章節中,我們只用了預設的線條與填滿樣式,而在本章,我們將進一步看看所有可用的樣式選項,畫出更吸引人的圖。

+ +

顏色

+ +

U截至目前為止我們只有看到繪圖環境的方法(methods),如果我們想要設定圖形的顏色,我們有兩個屬性能用: fillStylestorkeStyle.

+ +
+
fillStyle = color
+
設定填滿圖形時用的顏色.
+
strokeStyle = color
+
設定勾勒圖形時用的顏色.
+
+ +

其中color可以是CSS{{cssxref("<color>")}}表示字串、漸層色物件(gradient color)或是模式物件(pattern object),現在先看一下CSS{<color>}表示字串,稍後再看另外兩個項目.

+ +

預設上勾勒和填滿色是黑色(CSS顏色值為#000000).

+ +
+

Note: 一旦改變了strokeStyle的顏色值,那麼之後圖形勾勒顏色都會變成新顏色,同樣狀況一樣適用於fillStyle.

+
+ +

合格的顏色值請參照CSS3{{cssxref("<color>")}}規範,下面範例所標示的顏色都指向同一個顏色.

+ +
// these all set the fillStyle to 'orange'
+
+ctx.fillStyle = "orange";
+ctx.fillStyle = "#FFA500";
+ctx.fillStyle = "rgb(255,165,0)";
+ctx.fillStyle = "rgba(255,165,0,1)";
+
+ +
+

Note: 目前Gecko引擎並不支援CSS3全部的顏色值,例如hsl(100%,25%,0)和rgb(0,100%,0)就不被支援.

+
+ +

fillStyle範例

+ +

這裡我們利用兩個for迴圈來畫出一個矩形陣列,而且陣列中每一個矩形的顏色都不相同。下面程式碼透過改變i和j兩個變數來分別變換RGB中的紅色值和綠色值,然後為每一個矩形產生自己專屬的顏色值。透過改變RGB的各顏色值,我們可以產生各式各樣的調色盤,像是逐步調整顏色值,你也可以做出像Photoshop內建一樣的調色盤。

+ +
function draw() {
+  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);
+    }
+  }
+}
+ + + +

結果如下:

+ +

{{EmbedLiveSample("A_fillStyle_example", 160, 160, "https://mdn.mozillademos.org/files/5417/Canvas_fillstyle.png")}}

+ +

strokeStyle範例

+ +

本例和前例相當類似,不同的是我們改用arc()方法畫圓形而不是矩形、改設定strokeStyle變換圖形輪廓顏色。

+ +
  function draw() {
+    var ctx = document.getElementById('canvas').getContext('2d');
+    for (var i=0;i<6;i++){
+      for (var j=0;j<6;j++){
+        ctx.strokeStyle = 'rgb(0,' + Math.floor(255-42.5*i) + ',' +
+                         Math.floor(255-42.5*j) + ')';
+        ctx.beginPath();
+        ctx.arc(12.5+j*25,12.5+i*25,10,0,Math.PI*2,true);
+        ctx.stroke();
+      }
+    }
+  }
+
+ + + +

結果如下:

+ +

{{EmbedLiveSample("A_strokeStyle_example", "180", "180", "https://mdn.mozillademos.org/files/253/Canvas_strokestyle.png")}}

+ +

透明度

+ +

透過設定globalAlpha屬性或是以半透明顏色值設定strokeStyle與fillStyle屬性,除了畫不透明的圖形,我們還可以畫半透明的圖形。

+ +
+
globalAlpha = transparencyValue
+
允許值介於0.0(全透明)到1.0(不透明)。一旦設定後,之後畫布上畫的所有圖形的不透明度都會套用此設定值。預設值為1.0。
+
+ +

當我們想畫一系列相同不透明度的圖,設定globalAlpha值是一個方便的作法。

+ +

由CSS3顏色值能夠指定不透明度,我們也可以如下面一般,設定strokeStyle以及fillStyle來變更不透明度。

+ +
// Assigning transparent colors to stroke and fill style
+
+ctx.strokeStyle = "rgba(255,0,0,0.5)";
+ctx.fillStyle = "rgba(255,0,0,0.5)";
+
+ +

rgba()函數比rgb()函數多出一個不透明度參數,允許值介於0.0(全透明)到1.0(不透明).

+ +

globalAlpha範例

+ +

下面我們將在四個方格色塊背景上畫一系列半透明圓形。對於所有圓形,我們藉由設置globalAlpha屬性值為0.2使得圓形變成半透明,然後for迴圈裡我們逐一增加圓形繪圖半徑,最終結果看起來便像是輻射狀漸層圖案,而且圓形相互疊加在彼此之上後,又加深了重疊區域的不透明度,只要我們不斷增加圓形數量,最後圖片中央將被完全遮蓋,看不到背後的背景。

+ +
function draw() {
+  var ctx = document.getElementById('canvas').getContext('2d');
+  // draw background
+  ctx.fillStyle = '#FD0';
+  ctx.fillRect(0,0,75,75);
+  ctx.fillStyle = '#6C0';
+  ctx.fillRect(75,0,75,75);
+  ctx.fillStyle = '#09F';
+  ctx.fillRect(0,75,75,75);
+  ctx.fillStyle = '#F30';
+  ctx.fillRect(75,75,150,150);
+  ctx.fillStyle = '#FFF';
+
+  // set transparency value
+  ctx.globalAlpha = 0.2;
+
+  // Draw semi transparent circles
+  for (i=0;i<7;i++){
+    ctx.beginPath();
+    ctx.arc(75,75,10+10*i,0,Math.PI*2,true);
+    ctx.fill();
+  }
+}
+ + + +

{{EmbedLiveSample("A_globalAlpha_example", "180", "180", "https://mdn.mozillademos.org/files/232/Canvas_globalalpha.png")}}

+ +

rgba()使用範例

+ +

這個範例類似於上面的範例,但不同的是我們改畫半透明的矩形。rgba()在使用上會多一點彈性,因為我們可以分別設置勾勒和填滿圖形的不透明度。

+ +
function draw() {
+  var ctx = document.getElementById('canvas').getContext('2d');
+
+  // Draw background
+  ctx.fillStyle = 'rgb(255,221,0)';
+  ctx.fillRect(0,0,150,37.5);
+  ctx.fillStyle = 'rgb(102,204,0)';
+  ctx.fillRect(0,37.5,150,37.5);
+  ctx.fillStyle = 'rgb(0,153,255)';
+  ctx.fillRect(0,75,150,37.5);
+  ctx.fillStyle = 'rgb(255,51,0)';
+  ctx.fillRect(0,112.5,150,37.5);
+
+  // Draw semi transparent rectangles
+  for (var i=0;i<10;i++){
+    ctx.fillStyle = 'rgba(255,255,255,'+(i+1)/10+')';
+    for (var j=0;j<4;j++){
+      ctx.fillRect(5+i*14,5+j*37.5,14,27.5)
+    }
+  }
+}
+ + + +

{{EmbedLiveSample("An_example_using_rgba()", "180", "180", "https://mdn.mozillademos.org/files/246/Canvas_rgba.png")}}

+ +

線條樣式

+ +

有數種屬性可以讓我們設定線條樣式.

+ +
+
lineWidth = value
+
設定線條寬度。
+
lineCap = type
+
設定線條結尾的樣式。
+
lineJoin = type
+
設定線條和線條間接合處的樣式。
+
miterLimit = value
+
限制當兩條線相交時交接處最大長度;所謂交接處長度(miter length)是指線條交接處內角頂點到外角頂點的長度。
+
+ +

底下我們將一一示範這些屬性的用途。

+ +

lineWidth範例

+ +

此屬性決定線條寬度,必須為正數,預設值為1.0單位。

+ +

線條寬度的起算點是從繪圖路徑中央開始往兩旁各延伸一半設定寬度,由於畫布座標不直接對應到像素(pixel),所以要比較小心設定好取得清晰的直線。

+ +

由下方例子可以明顯看到,畫布上有10條直線,由左至右,從最小的1.0單位寬開始逐漸加寬,請注意奇數寬度直線會因為繪圖路徑位置關係而比較模糊。

+ +
function draw() {
+  var ctx = document.getElementById('canvas').getContext('2d');
+  for (var i = 0; i < 10; i++){
+    ctx.lineWidth = 1+i;
+    ctx.beginPath();
+    ctx.moveTo(5+i*14,5);
+    ctx.lineTo(5+i*14,140);
+    ctx.stroke();
+  }
+}
+
+ + + +

{{EmbedLiveSample("A_lineWidth_example", "180", "180", "https://mdn.mozillademos.org/files/239/Canvas_linewidth.png")}}

+ +

為了畫出清晰的直線,我們需要了解繪圖路徑是如何產生;如下方圖示,網格代表畫布座標軸,網格所框出的方格則代表螢幕上的像素,第一張圖片填滿了座標(2,1)到(5,5)的紅色區域,而這個紅色區域的邊際正好符合像素間的邊際,所以會產生出清晰的影像。

+ +

+ +

第二張圖片中,有一條寬1.0單位的直線從座標(3,1)到(3,5)被畫在畫布上,不過由於線條寬度的起算點是從繪圖路徑中央開始往兩旁各延伸一半設定寬度,所以當勾勒線條時,繪圖路徑兩旁的像素格只有一半會被填滿暗藍色,至於另外一半則會經由計算填入近似色(淡藍色),結果就是整格像素並非全部填入相同的暗藍色,進而產生出邊緣較為模糊的線條,上面程式碼範例中的奇數寬度直線就是因此而產生不清晰的線條。

+ +

為了避免劃出邊緣模糊直線,我們必須精準設定繪圖路徑位置,就本範例而言,如果我們的直線繪圖路徑是從座標(3.5, 1)到(3.5, 5)的話(如第三張圖),那麼1.0單位寬的直線將剛好填滿像素格,所以我們將可以畫出清晰的直線。

+ +
+

Note: 請注意本範例的Y軸座標都是整數點,若非如此,一樣會導致線條端點的像素格無法剛好被填滿的現象,而且同時最後產生的結果也會被lineCap給影響;倘若lineCap值為預設butt時,我們會需要為奇數寬度直線計算一下非整數的座標點,倘若lineCap樣式為square,那麼線段端點的像素格將自動被完整填滿。

+ +

還有一點需要注意,只要繪圖路徑被closePath()函數閉合起來,這樣便沒有了線條端點,所有的線條端點都會依據lineJoin樣式全部前後互相連接起來,這會自動延伸端點邊緣到線段接合處,如果此時接合端點是水平或垂直的話,位於中央的像素格將會被完整填滿。後面的說明會介紹lineCap和lineJoin樣式。

+
+ +

至於本例中偶數寬度的直線,為了避免模糊,繪圖路徑最好是落在整數座標點上。

+ +

雖然處裡2D繪圖縮放有些麻煩,但只要仔細計算像素格和繪圖路徑位置,縱使進行圖像縮放或變形,圖像輸出還是可以保持正確。一條寬1.0單位的直線,只要位置計算正確,放大兩倍後會變成一條2個像素寬的清晰直線,而且還是會保持正確位置。

+ +

lineCap範例

+ +

這個屬性決定線條端點的樣式,總共有三種樣式可選:

+ +

+ +
+
butt
+
線條端點樣式為方形
+
round
+
線條端點樣式為圓形
+
square
+
增加寬同線條寬度、高線條寬度一半的的方塊於線條端點
+
+ +

下面程式碼會畫出三條線,每條線的lineCap值皆不同。然後為了看清差異點,我們加上了兩條淡藍色的輔助線,線條的繪圖起始點和終點都剛好落在輔助線上。

+ +

最左邊的線條其lineCap為butt,不難看出它完全介於輔助線之間;第二條線其lineCap為round,端點樣式為半徑等於線條寬度一半的半圓;最右邊的線條其lineCap為square,端點樣式為寬同線條寬度、高線條寬度一半的的方塊。

+ +
function draw() {
+  var ctx = document.getElementById('canvas').getContext('2d');
+  var lineCap = ['butt','round','square'];
+
+  // Draw guides
+  ctx.strokeStyle = '#09f';
+  ctx.beginPath();
+  ctx.moveTo(10,10);
+  ctx.lineTo(140,10);
+  ctx.moveTo(10,140);
+  ctx.lineTo(140,140);
+  ctx.stroke();
+
+  // Draw lines
+  ctx.strokeStyle = 'black';
+  for (var i=0;i<lineCap.length;i++){
+    ctx.lineWidth = 15;
+    ctx.lineCap = lineCap[i];
+    ctx.beginPath();
+    ctx.moveTo(25+i*50,10);
+    ctx.lineTo(25+i*50,140);
+    ctx.stroke();
+  }
+}
+
+ + + +

{{EmbedLiveSample("A_lineCap_example", "180", "180", "https://mdn.mozillademos.org/files/236/Canvas_linecap.png")}}

+ +

lineJoin範例

+ +

lineJoin屬性決定兩個連接區端(如線條、弧形或曲線)如何連接(對於長度為零,亦即終點和控制點為同一點的圖形無效)。

+ +

lineJoin屬性共有三個屬性值如下,其中miter為預設值,請注意一點若是兩個連接區段的繪圖方向一致,那代表不會有連接處,所以測定是無效的。

+ +

+ +
+
round
+
代表圓弧型連接樣式。
+
bevel
+
代表斜面型連接樣式。在連接區段的共同終點處填滿一個三角形區域,將原本的外接角處形成一個切面。
+
miter
+
代表斜交型連接樣式。向外延伸連結區段外緣直到相交於一點,然後形成菱形區域,而miterLimit屬性會影響miter屬性。
+
+ +

下方程式碼和圖形輸出展示了lineJoin在不同屬性值下呈現的不同結果

+ +
function draw() {
+  var ctx = document.getElementById('canvas').getContext('2d');
+  var lineJoin = ['round','bevel','miter'];
+  ctx.lineWidth = 10;
+  for (var i=0;i<lineJoin.length;i++){
+    ctx.lineJoin = lineJoin[i];
+    ctx.beginPath();
+    ctx.moveTo(-5,5+i*40);
+    ctx.lineTo(35,45+i*40);
+    ctx.lineTo(75,5+i*40);
+    ctx.lineTo(115,45+i*40);
+    ctx.lineTo(155,5+i*40);
+    ctx.stroke();
+  }
+}
+
+ + + +

{{EmbedLiveSample("A_lineJoin_example", "180", "180", "https://mdn.mozillademos.org/files/237/Canvas_linejoin.png")}}

+ +

miterLimit屬性

+ +

前面範例顯示出,當lineJoin值為miter時,兩條線的外緣會延伸相交,所以,當這兩條相交線的相交角度越小的話,他們的延伸交會點就會越遠離內緣連接點,而且隨著角度變小,距離呈指數型增長。

+ +

miterLimit會限制延伸交會點最遠可以離內緣連接點到多遠,當延伸交會點的落點超出這個範圍,那麼便以斜面(bevel)作為交接樣式。請注意,最大miter長度為線寬乘於miterLimit值,所以miterLimit可以獨立於目前顯示縮放尺寸或其他變形設定。

+ +

miterLimit預設值為10.0。

+ +

更精確來說,miter限制是指延伸長度(在HTML畫布上,這個長度是外緣相交角到連接區段的共同繪圖路經終點)相對於一半線寬的最大允許比率;也等同於,外緣距內緣相交點之距離相對於線寬的的最大允許比率;相當於,連接區最小內緣角的一半角度的餘割(cosecant)值, 小於此值則便以斜面(bevel)作為交接樣式:

+ + + +

下面是一個範例,其中藍線標示出各個線條繪圖路徑的起始點與終點。

+ +

倘若設定範例程式碼中的miterLimit低於4.2,所有的miter交接都會被移除,取而代之的是出現在藍線附近的bevel交接;倘若設定miterLimit大於10,那麼大部分的miter交接都會出現,而且你會發現,由左到右,miter長度逐漸縮短,這是由於線條相交角度逐漸加大之故;倘若設定中間值,那麼左邊會出現bevel交接,右邊會出現miter交接。

+ +
function draw() {
+  var ctx = document.getElementById('canvas').getContext('2d');
+
+  // Clear canvas
+  ctx.clearRect(0,0,150,150);
+
+  // Draw guides
+  ctx.strokeStyle = '#09f';
+  ctx.lineWidth   = 2;
+  ctx.strokeRect(-5,50,160,50);
+
+  // Set line styles
+  ctx.strokeStyle = '#000';
+  ctx.lineWidth = 10;
+
+  // check input
+  if (document.getElementById('miterLimit').value.match(/\d+(\.\d+)?/)) {
+    ctx.miterLimit = parseFloat(document.getElementById('miterLimit').value);
+  } else {
+    alert('Value must be a positive number');
+  }
+
+  // Draw lines
+  ctx.beginPath();
+  ctx.moveTo(0,100);
+  for (i=0;i<24;i++){
+    var dy = i%2==0 ? 25 : -25 ;
+    ctx.lineTo(Math.pow(i,1.5)*2,75+dy);
+  }
+  ctx.stroke();
+  return false;
+}
+
+ + + +

{{EmbedLiveSample("A_demo_of_the_miterLimit_property", "400", "180", "https://mdn.mozillademos.org/files/240/Canvas_miterlimit.png")}}

+ +

漸層

+ +

如同其他繪圖軟體可以畫出線性和放射狀的漸層圖案,透過設定fillStyle和strokeStyle屬性為canvasGradient漸層物件,我們也可以在canvas上做到一樣的效果。要創造漸層物件,可以使用下面的方法:

+ +
+
createLinearGradient(x1, y1, x2, y2)
+
產生一個線性漸層物件,其漸層起始點為(x1, y1)、終點為(x2, y2)。
+
createRadialGradient(x1, y1, r1, x2, y2, r2)
+
產生一個放射狀漸層物件,第一個圓之圓心落在(x1, y1)、半徑為r1,第一個圓之圓心落在(x2, y2)、半徑為r2。
+
+ +

例如:

+ +
var lineargradient = ctx.createLinearGradient(0, 0, 150, 150);
+var radialgradient = ctx.createRadialGradient(75, 75, 0, 75, 75, 100);
+
+ +

一旦產生了canvasGradient漸層物件,我們用addColorStop()方法可以添加顏色上去。

+ +
+
gradient.addColorStop(position, color)
+
於gradient漸層物件建立一個顏色點,其中color是CSS{{cssxref("<color>")}}的字串表示,而position介於0.0到1.0之間,定義了該顏色在漸層中的相對位置。呼叫這個方法會指定當進行到設定的位置時,漸層需要完全轉變成設定的顏色。
+
+ +

我們可以按照需要設定無數個顏色點,下面是一個簡單的由白到黑的簡單漸層範例程式碼。

+ +
var lineargradient = ctx.createLinearGradient(0,0,150,150);
+lineargradient.addColorStop(0, 'white');
+lineargradient.addColorStop(1, 'black');
+
+ +

createLinearGradient範例

+ +

本範例中,我們將建立兩種漸層,如範例所示,strokeStyle和fillSyle屬性都可以接受canvasGradient物件作為屬性值。

+ +
function draw() {
+  var ctx = document.getElementById('canvas').getContext('2d');
+
+  // Create gradients
+  var lingrad = ctx.createLinearGradient(0,0,0,150);
+  lingrad.addColorStop(0, '#00ABEB');
+  lingrad.addColorStop(0.5, '#fff');
+  lingrad.addColorStop(0.5, '#26C000');
+  lingrad.addColorStop(1, '#fff');
+
+  var lingrad2 = ctx.createLinearGradient(0,50,0,95);
+  lingrad2.addColorStop(0.5, '#000');
+  lingrad2.addColorStop(1, 'rgba(0,0,0,0)');
+
+  // assign gradients to fill and stroke styles
+  ctx.fillStyle = lingrad;
+  ctx.strokeStyle = lingrad2;
+
+  // draw shapes
+  ctx.fillRect(10,10,130,130);
+  ctx.strokeRect(50,50,50,50);
+
+}
+
+ + + +

第一個漸層為背景漸層,範例中我們在一個位置上指定了兩種顏色(白色到綠色),這樣做會產生非常突然的顏色轉換,一般來說,不管如何設定顏色點順序都沒關係,然而就這個例子而言,這種作法太過強烈了,但是如果這是你想要的顏色漸層順序,那其實也是可以。

+ +

第二個漸層起始位置(position 0.0)的顏色並沒有被指定,所以下一個漸層顏色會自動被設為起始位置顏色,因此即使我們沒有指定漸層起始位置顏色也沒有關係,就像本範例自動會設定起始位置的顏色等於位置0.5的黑色。

+ +

{{EmbedLiveSample("A_createLinearGradient_example", "180", "180", "https://mdn.mozillademos.org/files/235/Canvas_lineargradient.png")}}

+ +

createRadialGradient範例

+ +

這邊我們定義了四種放射狀漸層,相較於一般在Photoshop看到的”經典”放射狀漸層圖案(漸層從一個圖案中心點向外呈圓心狀延伸),因為我們可以控制漸層起始和終止點,我們可以做到更好的效果。

+ +
function draw() {
+  var ctx = document.getElementById('canvas').getContext('2d');
+
+  // Create gradients
+  var radgrad = ctx.createRadialGradient(45,45,10,52,50,30);
+  radgrad.addColorStop(0, '#A7D30C');
+  radgrad.addColorStop(0.9, '#019F62');
+  radgrad.addColorStop(1, 'rgba(1,159,98,0)');
+
+  var radgrad2 = ctx.createRadialGradient(105,105,20,112,120,50);
+  radgrad2.addColorStop(0, '#FF5F98');
+  radgrad2.addColorStop(0.75, '#FF0188');
+  radgrad2.addColorStop(1, 'rgba(255,1,136,0)');
+
+  var radgrad3 = ctx.createRadialGradient(95,15,15,102,20,40);
+  radgrad3.addColorStop(0, '#00C9FF');
+  radgrad3.addColorStop(0.8, '#00B5E2');
+  radgrad3.addColorStop(1, 'rgba(0,201,255,0)');
+
+  var radgrad4 = ctx.createRadialGradient(0,150,50,0,140,90);
+  radgrad4.addColorStop(0, '#F4F201');
+  radgrad4.addColorStop(0.8, '#E4C700');
+  radgrad4.addColorStop(1, 'rgba(228,199,0,0)');
+
+  // draw shapes
+  ctx.fillStyle = radgrad4;
+  ctx.fillRect(0,0,150,150);
+  ctx.fillStyle = radgrad3;
+  ctx.fillRect(0,0,150,150);
+  ctx.fillStyle = radgrad2;
+  ctx.fillRect(0,0,150,150);
+  ctx.fillStyle = radgrad;
+  ctx.fillRect(0,0,150,150);
+}
+
+ + + +

程式碼範例中,為了營造出3D效果,我們讓起始點和終止點位於不同位置,請注意,最好不要讓內外圈相重疊,以避免難以預測的奇怪效果。

+ +

每一個漸層圖案最後一個漸層色都是全透明的,如果希望倒數第二個漸層色能夠平順地轉換到這個最後一個漸層色,那麼兩者應該設定一樣的顏色值,像是程式碼範例中的漸層色 #019F62 其實就等於 rgba(1,159,98,1)。

+ +

{{EmbedLiveSample("A_createRadialGradient_example", "180", "180", "https://mdn.mozillademos.org/files/244/Canvas_radialgradient.png")}}

+ +

樣式(Patterns)

+ +

先前的範例中,我們都是藉由迴圈來重複產生影像樣式,不過其實有一條更簡單的方法,那就是呼叫createPattern方法。

+ +
+
createPattern(image, type)
+
呼叫createPattern()會產一個畫布樣式物件,然後回傳出來。
+ 其中image是CanvasImageSource類別物件(像是{{domxref("HTMLImageElement")}},、<canvas>元素、{{HTMLElement("video")}} 元素等)
+
+ +

Type是一串字串,定義了如何產生樣式,允許的值有:

+ +
+
repeat
+
沿垂直與水平方向重複排列影像
+
repeat-x
+
只沿水平方向重複排列影像
+
repeat-y
+
只沿垂直方向重複排列影像
+
no-repeat
+
不重複排列影像,只使用一次
+
+ +
+

Note: Firefox現在只支援repeat,所以其他值都是無效的

+
+ +
Note: 傳入尺寸為0x0像素的畫布會引起錯誤
+ +

利用createPattern()的方法和前面利用漸層的方法十分類似,我們呼叫createPattern()產生{{domxref("CanvasPattern")}}物件,然後將{CanvasPattern}物件設成fillStyle或strokeStyle的屬性值,例如:

+ +
var img = new Image();
+img.src = 'someimage.png';
+var ptrn = ctx.createPattern(img,'repeat');
+
+ +
+

Note: 不像drawImage()方法,呼叫createPattern()方法前影像必須要先載入完成,否則可能圖像的程生會有問題。

+
+ +

createPattern範例

+ +

這個範例中我們把fillStyle屬性值存為樣式物件,比較值得注意的是影像onload事件處理器,這是為了確保影像載入完成後再進行。

+ +
function draw() {
+  var ctx = document.getElementById('canvas').getContext('2d');
+
+  // create new image object to use as pattern
+  var img = new Image();
+  img.src = '/files/222/Canvas_createpattern.png';
+  img.onload = function(){
+
+    // create pattern
+    var ptrn = ctx.createPattern(img,'repeat');
+    ctx.fillStyle = ptrn;
+    ctx.fillRect(0,0,150,150);
+
+  }
+}
+
+ + + +

{{EmbedLiveSample("A_createPattern_example", "180", "180", "https://mdn.mozillademos.org/files/222/Canvas_createpattern.png")}}

+ +

陰影

+ +

要產生陰影只需要四個屬性:

+ +
+
shadowOffsetX = float
+
代表陰影從物件延伸出來的水平距離,預設為0,不受變形矩陣影響。
+
shadowOffsetY = float
+
代表陰影從物件延伸出來的垂直距離,預設為0,不受變形矩陣影響。
+
shadowBlur = float
+
代表陰影模糊大小範圍,預設為0,不受變形矩陣影響,不等同於像素值。
+
shadowColor = {{cssxref("<color>")}}
+
CSS顏色值,代表陰影顏色,預設為全透明。
+
+ +

shadowOffsetX和shadowOffsetY會決定陰影延伸大小,若是為正值,則陰影會往右(沿X軸)和往下(沿Y軸)延伸,若是為負值,則會往正值相反方向延伸。

+ +
+

{{gecko_callout_heading("7.0")}}

+ +

Note: 基於HTML5提議規格變更,從{{Gecko("7.0")}}開始,陰影只會在source-over的構圖排列下產生

+
+ +

文字陰影範例

+ +

本程式碼範例會產生一串帶有陰影的文字。

+ +
function draw() {
+  var ctx = document.getElementById('canvas').getContext('2d');
+
+  ctx.shadowOffsetX = 2;
+  ctx.shadowOffsetY = 2;
+  ctx.shadowBlur = 2;
+  ctx.shadowColor = "rgba(0, 0, 0, 0.5)";
+
+  ctx.font = "20px Times New Roman";
+  ctx.fillStyle = "Black";
+  ctx.fillText("Sample String", 5, 30);
+}
+
+ + + +

{{EmbedLiveSample("A_shadowed_text_example", "180", "100", "https://mdn.mozillademos.org/files/2505/shadowed-string.png")}}

+ +

{{PreviousNext("Web/Guide/HTML/Canvas_tutorial/Using_images", "Web/Guide/HTML/Canvas_tutorial/Transformations")}}

+ +
 
diff --git a/files/zh-tw/web/api/canvas_api/tutorial/basic_animations/index.html b/files/zh-tw/web/api/canvas_api/tutorial/basic_animations/index.html new file mode 100644 index 0000000000..336fadbce0 --- /dev/null +++ b/files/zh-tw/web/api/canvas_api/tutorial/basic_animations/index.html @@ -0,0 +1,347 @@ +--- +title: 基礎動畫 +slug: Web/API/Canvas_API/Tutorial/Basic_animations +translation_of: Web/API/Canvas_API/Tutorial/Basic_animations +--- +
{{CanvasSidebar}} {{PreviousNext("Web/API/Canvas_API/Tutorial/Compositing", "Web/API/Canvas_API/Tutorial/Advanced_animations")}}
+ +

控制{{HTMLElement("canvas")}}元素來產生互動式動畫不是一件難事,當然,如果產生的動畫越複雜越需要多費一些力氣,未來如果有機會我們將說明這一塊。

+ +

由於圖形一但產生後便靜止不動,所以我們必須重新繪圖好移動圖案,產生動畫效果,所以如果繪圖越複雜,繪圖運算也需要消耗越多運算資源和時間,換句話說,電腦效能的好壞將大大影響動畫順暢度,或許這也是畫布動畫最大的限制。

+ +

動畫基本步驟

+ +

產生一個畫面基本上需要以下步驟 :

+ +
    +
  1. 清除畫布
    + 除了不變的背景畫面,所有先前畫的圖案都要先清除,這個步驟可以透過clearRect()方法達成。
  2. +
  3. 儲存畫布狀態
    + 若是想要每一次重新繪圖時畫布起始狀態都是原始狀態,那麼就需要先行儲存畫布原始狀態。
  4. +
  5. 畫出畫面
    + 畫出需要畫面。
  6. +
  7. 復原畫布狀態
    + 復原畫布狀態以備下次繪圖使用。
  8. +
+ +

控制動畫

+ +

一般來說當程式碼執行完畢後我們才會看到繪圖結果,所以說我們無法靠執行for迴圈來產生動畫,我們得靠每隔一段時間繪圖來產生動畫,下面將介紹兩種作法。

+ +

排程更新

+ +

第一種作法是利用{{domxref("window.setInterval()")}}與{{domxref("window.setTimeout()")}}方法。

+ +
+

Note: 針對新版瀏覽器建議採用{{domxref("window.requestAnimationFrame()")}}方法。

+
+ +
+
setInterval(function, delay)
+
每隔delay毫秒,執行輸入function(函數)
+
setTimeout(function, delay)
+
過delay毫秒後,執行輸入function(函數)
+
requestAnimationFrame(callback)
+
告訴瀏覽器你希望執行動畫的時候,要求瀏覽器在重繪下一張畫面之前,呼叫callback函數來更新動畫
+
+ +

如果希望不要有任何的使用者互動影響,請使用setInterval(),因為它會確實地每隔一段時間就執行程式碼。如果你想製作遊戲 , 我們能夠使用keyboard 或是 mouse event來控制動畫,並使用setTimeout()函數一起。藉由設定EventListeners,我們能夠捕捉任何使用者的動作,並執行我們的動畫函數。

+ +
+

在下面的範例,我們將使用window.requestAnimationFrame()方法來控制動畫,window.requestAnimationFrame()方法為動畫提供更順暢更有效率的方式來執行,當系統準備好繪製畫面時,藉由呼叫動畫andmation frame()的callback函數 。callback通常每秒鐘執行60次,當執行background tab時,執行次數會更低,想知道更多關於動畫迴圈(animation loop)的資訊,尤其是遊戲的應用,請查看我們在 Game development zone 的主題 Anatomy of a video game 。

+
+ +

從使用者輸入操作控制動畫

+ +

我們也可以從使用者輸入操作控制動畫,就像是電玩遊戲一般;像是在鍵盤上設置事件處理器{{domxref("EventListener")}}捕捉使用者輸入並執行對應動畫。

+ +

你可以利用我們的次要版主要版動畫框架

+ +
var myAnimation = new MiniDaemon(null, animateShape, 500, Infinity);
+ +

+ +
var myAnimation = new Daemon(null, animateShape, 500, Infinity);
+ +

在後面的範例我們主要將使用window.setInterval()方法控制動畫,然後於本頁底部是一些使用widnow.setTimeout()的範例連結。

+ +

太陽系動畫

+ +

本例會產生一個小型太陽系運行動畫。

+ +
var sun = new Image();
+var moon = new Image();
+var earth = new Image();
+function init(){
+  sun.src = 'https://mdn.mozillademos.org/files/1456/Canvas_sun.png';
+  moon.src = 'https://mdn.mozillademos.org/files/1443/Canvas_moon.png';
+  earth.src = 'https://mdn.mozillademos.org/files/1429/Canvas_earth.png';
+  setInterval(draw,100);
+}
+
+function draw() {
+  var ctx = document.getElementById('canvas').getContext('2d');
+
+  ctx.globalCompositeOperation = 'destination-over';
+  ctx.clearRect(0,0,300,300); // clear canvas
+
+  ctx.fillStyle = 'rgba(0,0,0,0.4)';
+  ctx.strokeStyle = 'rgba(0,153,255,0.4)';
+  ctx.save();
+  ctx.translate(150,150);
+
+  // Earth
+  var time = new Date();
+  ctx.rotate( ((2*Math.PI)/60)*time.getSeconds() + ((2*Math.PI)/60000)*time.getMilliseconds() );
+  ctx.translate(105,0);
+  ctx.fillRect(0,-12,50,24); // Shadow
+  ctx.drawImage(earth,-12,-12);
+
+  // Moon
+  ctx.save();
+  ctx.rotate( ((2*Math.PI)/6)*time.getSeconds() + ((2*Math.PI)/6000)*time.getMilliseconds() );
+  ctx.translate(0,28.5);
+  ctx.drawImage(moon,-3.5,-3.5);
+  ctx.restore();
+
+  ctx.restore();
+
+  ctx.beginPath();
+  ctx.arc(150,150,105,0,Math.PI*2,false); // Earth orbit
+  ctx.stroke();
+
+  ctx.drawImage(sun,0,0,300,300);
+}
+
+ + + +

{{EmbedLiveSample("An_animated_solar_system", "310", "310", "https://mdn.mozillademos.org/files/202/Canvas_animation1.png")}}

+ +

時鐘動畫

+ +

本例會產生一個時鐘指向現在時間。

+ +
function init(){
+  clock();
+  setInterval(clock,1000);
+}
+
+function clock(){
+  var now = new Date();
+  var ctx = document.getElementById('canvas').getContext('2d');
+  ctx.save();
+  ctx.clearRect(0,0,150,150);
+  ctx.translate(75,75);
+  ctx.scale(0.4,0.4);
+  ctx.rotate(-Math.PI/2);
+  ctx.strokeStyle = "black";
+  ctx.fillStyle = "white";
+  ctx.lineWidth = 8;
+  ctx.lineCap = "round";
+
+  // Hour marks
+  ctx.save();
+  for (var i=0;i<12;i++){
+    ctx.beginPath();
+    ctx.rotate(Math.PI/6);
+    ctx.moveTo(100,0);
+    ctx.lineTo(120,0);
+    ctx.stroke();
+  }
+  ctx.restore();
+
+  // Minute marks
+  ctx.save();
+  ctx.lineWidth = 5;
+  for (i=0;i<60;i++){
+    if (i%5!=0) {
+      ctx.beginPath();
+      ctx.moveTo(117,0);
+      ctx.lineTo(120,0);
+      ctx.stroke();
+    }
+    ctx.rotate(Math.PI/30);
+  }
+  ctx.restore();
+
+  var sec = now.getSeconds();
+  var min = now.getMinutes();
+  var hr  = now.getHours();
+  hr = hr>=12 ? hr-12 : hr;
+
+  ctx.fillStyle = "black";
+
+  // write Hours
+  ctx.save();
+  ctx.rotate( hr*(Math.PI/6) + (Math.PI/360)*min + (Math.PI/21600)*sec )
+  ctx.lineWidth = 14;
+  ctx.beginPath();
+  ctx.moveTo(-20,0);
+  ctx.lineTo(80,0);
+  ctx.stroke();
+  ctx.restore();
+
+  // write Minutes
+  ctx.save();
+  ctx.rotate( (Math.PI/30)*min + (Math.PI/1800)*sec )
+  ctx.lineWidth = 10;
+  ctx.beginPath();
+  ctx.moveTo(-28,0);
+  ctx.lineTo(112,0);
+  ctx.stroke();
+  ctx.restore();
+
+  // Write seconds
+  ctx.save();
+  ctx.rotate(sec * Math.PI/30);
+  ctx.strokeStyle = "#D40000";
+  ctx.fillStyle = "#D40000";
+  ctx.lineWidth = 6;
+  ctx.beginPath();
+  ctx.moveTo(-30,0);
+  ctx.lineTo(83,0);
+  ctx.stroke();
+  ctx.beginPath();
+  ctx.arc(0,0,10,0,Math.PI*2,true);
+  ctx.fill();
+  ctx.beginPath();
+  ctx.arc(95,0,10,0,Math.PI*2,true);
+  ctx.stroke();
+  ctx.fillStyle = "rgba(0,0,0,0)";
+  ctx.arc(0,0,3,0,Math.PI*2,true);
+  ctx.fill();
+  ctx.restore();
+
+  ctx.beginPath();
+  ctx.lineWidth = 14;
+  ctx.strokeStyle = '#325FA2';
+  ctx.arc(0,0,142,0,Math.PI*2,true);
+  ctx.stroke();
+
+  ctx.restore();
+}
+ + + +

{{EmbedLiveSample("An_animated_clock", "180", "180", "https://mdn.mozillademos.org/files/203/Canvas_animation2.png")}}

+ +

循環景色

+ +

本例會產一個由左到右循環捲動美國優勝美地國家公園景色,你也可以自行替換其他比畫布還大的圖片。

+ +
var img = new Image();
+
+// User Variables - customize these to change the image being scrolled, its
+// direction, and the speed.
+
+img.src = '/files/4553/Capitan_Meadows,_Yosemite_National_Park.jpg';
+var CanvasXSize = 800;
+var CanvasYSize = 200;
+var speed = 30; //lower is faster
+var scale = 1.05;
+var y = -4.5; //vertical offset
+
+// Main program
+
+var dx = 0.75;
+var imgW;
+var imgH;
+var x = 0;
+var clearX;
+var clearY;
+var ctx;
+
+img.onload = function() {
+    imgW = img.width*scale;
+    imgH = img.height*scale;
+    if (imgW > CanvasXSize) { x = CanvasXSize-imgW; } // image larger than canvas
+    if (imgW > CanvasXSize) { clearX = imgW; } // image larger than canvas
+    else { clearX = CanvasXSize; }
+    if (imgH > CanvasYSize) { clearY = imgH; } // image larger than canvas
+    else { clearY = CanvasYSize; }
+    //Get Canvas Element
+    ctx = document.getElementById('canvas').getContext('2d');
+    //Set Refresh Rate
+    return setInterval(draw, speed);
+}
+
+function draw() {
+    //Clear Canvas
+    ctx.clearRect(0,0,clearX,clearY);
+    //If image is <= Canvas Size
+    if (imgW <= CanvasXSize) {
+        //reset, start from beginning
+        if (x > (CanvasXSize)) { x = 0; }
+        //draw aditional image
+        if (x > (CanvasXSize-imgW)) { ctx.drawImage(img,x-CanvasXSize+1,y,imgW,imgH); }
+    }
+    //If image is > Canvas Size
+    else {
+        //reset, start from beginning
+        if (x > (CanvasXSize)) { x = CanvasXSize-imgW; }
+        //draw aditional image
+        if (x > (CanvasXSize-imgW)) { ctx.drawImage(img,x-imgW+1,y,imgW,imgH); }
+    }
+    //draw image
+    ctx.drawImage(img,x,y,imgW,imgH);
+    //amount to move
+    x += dx;
+}
+
+ +

循環景色就是在下方的{{HTMLElement("canvas")}}中捲動,請注意其中的width和height和程式碼中的CanvasXZSize與CanvasYSize一樣。

+ +
<canvas id="canvas" width="800" height="200"></canvas>
+ +

Live sample

+ +

{{EmbedLiveSample("A_looping_panorama", "830", "230")}}

+ +

其他範例

+ +
+
Gartic
+
+

多人繪圖遊戲

+
+
Canvascape
+
+

第一人稱3D冒險遊戲

+
+
A basic ray-caster
+
透過鍵盤控制動畫範例
+
canvas adventure
+
+

另一個透過鍵盤控制動畫範例

+
+
An interactive Blob
+
和Blob遊戲
+
Flying through a starfield
+
+

飛越星河

+
+
iGrapher
+
+

股票市場圖

+
+
+ +

See also

+ + + +

{{PreviousNext("Web/Guide/HTML/Canvas_tutorial/Compositing", "Web/Guide/HTML/Canvas_tutorial/Optimizing_canvas")}}

diff --git a/files/zh-tw/web/api/canvas_api/tutorial/basic_usage/index.html b/files/zh-tw/web/api/canvas_api/tutorial/basic_usage/index.html new file mode 100644 index 0000000000..9d39027c96 --- /dev/null +++ b/files/zh-tw/web/api/canvas_api/tutorial/basic_usage/index.html @@ -0,0 +1,158 @@ +--- +title: Canvas 基本用途 +slug: Web/API/Canvas_API/Tutorial/Basic_usage +translation_of: Web/API/Canvas_API/Tutorial/Basic_usage +--- +
{{CanvasSidebar}} {{PreviousNext("Web/API/Canvas_API/Tutorial", "Web/API/Canvas_API/Tutorial/Drawing_shapes")}}
+ +
+

Let's start this tutorial by looking at the {{HTMLElement("canvas")}} {{Glossary("HTML")}} element itself. At the end of this page, you will know how to set up a canvas 2D context and have drawn a first example in your browser.

+
+ +

<canvas> 元素

+ +
<canvas id="tutorial" width="150" height="150"></canvas>
+
+ +

首先,先來看看 {{HTMLElement("canvas")}},它看起來有點像 {{HTMLElement("img")}} 元素,其中的差異點在於 <canvas> 沒有 src alt 屬性,<canvas> 只有 {{htmlattrxref("width", "canvas")}} 與 {{htmlattrxref("height", "canvas")}} 這兩個屬性,這兩個屬性皆為非必須、能透過 DOM屬性設定;若是沒有設定 width 和 height 屬性,畫布寬預設值為 300 pixels、高預設值為 150 pixels,我們可以用 CSS 強制設定元素尺寸,但當渲染時,影像會縮放以符合元素的尺寸。

+ +
+

Note:如果繪圖結果看起來有些扭曲,可以改試著用<canvas>自身的widthheight屬性而不要用CSS來設定寬高。

+
+ +

幾乎所有HTML元素都有id屬性,<canvas>也不例外,為了方便於程式碼腳本找到需要的<canvas>,每次都設定id是一項不錯的作法。

+ +

如同一般的影像可以設定如邊界(margin)、邊框(border)、背景(background)等等,<canvas>元素一樣可以設定這些樣式,然而,這些樣式規則不會影響canvas實際繪圖,稍後我們會看到相關範例。當沒有套用樣式規定時,<canvas>會被初始成全透明。

+ +

 

+ +
+

錯誤替代內容(Fallback content)

+ +

因為舊版瀏覽器(特別是IE9之前的IE)不支援{<canvas>}元素,我們應該為這些瀏覽器準備錯誤替代內容。

+ +

當不支援<canvas>的瀏覽器看到不認識的<canvas>時會忽略<canvas>,而此時在<canvas>下瀏覽器認識的替代內容則會被瀏覽器解析顯示,至於支援<canvas>的瀏覽器則是會正常解析<canvas>,忽略替代內容。

+ +

例如,我們可以準備一段canvas內容的說明文字或canvas繪圖完成後的靜態圖片,如下所示:

+ +
<canvas id="stockGraph" width="150" height="150">
+  current stock price: $3.15 +0.15
+</canvas>
+
+<canvas id="clock" width="150" height="150">
+  <img src="images/clock.png" width="150" height="150" alt=""/>
+</canvas>
+
+ +
 
+ +

需要</canvas>標籤

+ +

不像{{HTMLElement("img")}}元素,{{HTMLElement("canvas")}}元素必須要有</canvas>結束標籤。

+ +

 

+ +
+

縱使早期AppleSafari瀏覽器不需要結束標籤,但是基於規範,這是必須的,所以,為了相容性考量,應該要有結束標籤。Safari 2.0以前的版本會同時解析canvas以及替代內容,除非我們用CSS去遮蓋內容,不過幸運的是,現在已經沒有甚麼人在用這些舊版Safari

+
+ +

如果不需要錯誤替代內容,簡單的<canvas id="foo" ...></canvas>便可以完全相容於所有支援的瀏覽器。

+ +

 

+ +

渲染環境(rendering context)

+ +

{{HTMLElement("canvas")}}產生一個固定大小的繪圖畫布,這個畫布上有一或多個渲染環境(rendering context),我們可以用渲染環境來產生或操作顯示內容的渲染環境(rendering context)不同環境(context)可能會提供不同型態的渲染方式,好比說WebGL使用OpenGL ES3D環境(context),而這裡我們主要將討論2D渲染環境(rendering context)

+ +

一開始canvas為空白,程式碼腳本需要先存取渲染環境,在上面繪圖,然後才會顯現影像。{{HTMLElement("canvas")}} 素有一個方法(method)getContext(),透過此方法可以取得渲染環境及其繪圖函數(function)getContext()輸入參數只有渲染環境類型一項,像本教學所討論的2D繪圖,就是輸入”2d”

+ +
var canvas = document.getElementById('tutorial');
+var ctx = canvas.getContext('2d');
+
+ +

上面第一行先呼叫{{domxref("document.getElementById()")}}來取得{{HTMLElement("canvas")}}元素,一旦取得元素後,便可以用其getContext()取得渲染環境。

+ +

 

+ +
+

支援性檢查

+ +

替代內容會被不支援{{HTMLElement("canvas")}}.的瀏覽器所顯示。程式碼腳本也可以利用檢查getContext()方法是否存在來檢查是否支援<canvas>,我們可以修改上面例子成如下:

+ +
var canvas = document.getElementById('tutorial');
+
+if (canvas.getContext){
+  var ctx = canvas.getContext('2d');
+  // drawing code here
+} else {
+  // canvas-unsupported code here
+}
+
+
+
+ +
 
+ +

一個範本

+ +

這裡是一個最簡單的範本,之後就是我們範例的起始點。

+ +
<html>
+  <head>
+    <title>Canvas tutorial</title>
+    <script type="text/javascript">
+      function draw(){
+        var canvas = document.getElementById('tutorial');
+        if (canvas.getContext){
+          var ctx = canvas.getContext('2d');
+        }
+      }
+    </script>
+    <style type="text/css">
+      canvas { border: 1px solid black; }
+    </style>
+  </head>
+  <body onload="draw();">
+    <canvas id="tutorial" width="150" height="150"></canvas>
+  </body>
+</html>
+
+ +

一旦網頁載入完成後,程式碼會呼叫draw()函數(這是利用document上的load事件完成),這類draw()函數也可以透過{{domxref("window.setTimeout()")}}, {{domxref("window.setInterval()")}}或其他事件處理函數來呼叫,只要呼叫的時間點是在網頁載入完後。

+ +

這是我們的範本實際看起來的樣子:

+ +

{{EmbedLiveSample("A_skeleton_template", 160, 160)}}

+ +

一個簡單的範例

+ +

首先,讓我們先來畫兩個相交的正方形,其中一個正方形有alpha透明值,之後我們會說明這是如何達成的。

+ +
<html>
+ <head>
+  <script type="application/javascript">
+    function draw() {
+      var canvas = document.getElementById("canvas");
+      if (canvas.getContext) {
+        var ctx = canvas.getContext("2d");
+
+        ctx.fillStyle = "rgb(200,0,0)";
+        ctx.fillRect (10, 10, 55, 50);
+
+        ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
+        ctx.fillRect (30, 30, 55, 50);
+      }
+    }
+  </script>
+ </head>
+ <body onload="draw();">
+   <canvas id="canvas" width="150" height="150"></canvas>
+ </body>
+</html>
+
+ +

本範例的結果如下:

+ +

{{EmbedLiveSample("A_simple_example", 160, 160, "https://mdn.mozillademos.org/files/228/canvas_ex1.png")}}

+ +

{{PreviousNext("Web/Guide/HTML/Canvas_tutorial", "Web/Guide/HTML/Canvas_tutorial/Drawing_shapes")}}

diff --git a/files/zh-tw/web/api/canvas_api/tutorial/compositing/index.html b/files/zh-tw/web/api/canvas_api/tutorial/compositing/index.html new file mode 100644 index 0000000000..e5453c93a5 --- /dev/null +++ b/files/zh-tw/web/api/canvas_api/tutorial/compositing/index.html @@ -0,0 +1,207 @@ +--- +title: 合成效果 +slug: Web/API/Canvas_API/Tutorial/Compositing +translation_of: Web/API/Canvas_API/Tutorial/Compositing +--- +
{{CanvasSidebar}} {{PreviousNext("Web/API/Canvas_API/Tutorial/Transformations", "Web/API/Canvas_API/Tutorial/Basic_animations")}}
+ +

在前述的範例中,新繪製的圖形總會覆蓋在之前的圖形上,對大多數情況來說這相當正常,不過它也限制了圖形繪製的順序。其實我們可以透過 globalCompositeOperation 屬性來改變這項預設行為。

+ +

globalCompositeOperation

+ +

利用 globalCompositeOperation,我們可以將新圖形繪製在舊圖形之下、遮蓋部分區域、清除畫布部分區域 (不同於 clearRect() 函式只能清除矩形區域)。

+ +
+
globalCompositeOperation = type
+
type 字串可指定為以下 12 種合成設定之一,每一種合成設定均將套用到新繪製的圖形上。
+
+ +
+

Note: 下列圖例的藍色矩形是舊圖形,紅色圓形是新圖形。

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

source-over 預設值。將新圖形畫在舊圖形之上。

+
+

Image:Canvas_composite_srcovr.png

+
+

destination-over
+ 將新圖形畫在舊圖形之下。

+
+

Image:Canvas_composite_destovr.png

+
+

source-in
+ 只保留新、舊圖形重疊的新圖形區域,其餘皆變為透明。

+
+

Image:Canvas_composite_srcin.png

+
+

destination-in
+ 只保留新、舊圖形重疊的舊圖形區域,其餘皆變為透明。

+
+

Image:Canvas_composite_destin.png

+
+

source-out
+ 只保留新、舊圖形非重疊的新圖形區域,其餘皆變為透明。

+
+

Image:Canvas_composite_srcout.png

+
+

destination-out
+ 只保留新、舊圖形非重疊的舊圖形區域,其餘皆變為透明。

+
+

Image:Canvas_composite_destout.png

+
+

source-atop
+ 新圖形只繪製在新、舊圖形重疊的新圖形區域,然後蓋在舊圖形之上。

+
+

Image:Canvas_composite_srcatop.png

+
+

destination-atop
+ 舊圖形只保留在新、舊圖形重疊的舊圖形區域,然後蓋在新圖形之上。

+
+

Image:Canvas_composite_destatop.png

+
+

lighter
+ 新舊圖形重疊區域的顏色,由新、舊圖形的顏色碼相加而得。

+
+

Image:Canvas_composite_lighten.png

+
+

darker {{obsolete_inline}}

+ +

新舊圖形重疊區域的顏色,由新、舊圖形的顏色碼相減而得。此屬性值已經從畫布規格中移除了,不再支援。

+
+

Image:Canvas_composite_darken.png

+
+

xor
+ 新舊圖形重疊區域設為透明。

+
+

Image:Canvas_composite_xor.png

+
+

copy
+ 移除其他圖形,只保留新圖形。

+
+

Image:Canvas_composite_copy.png

+
+ +

這裡有這些構圖組合的實際範例輸出結果在此。

+ +

裁剪路徑

+ +

裁剪路徑就像是一般畫布圖形繪圖,但就如同遮罩一樣,會蓋掉不需要的部分,如右圖所示。紅邊星星是我們的裁剪路徑,在路徑區域以外部分都不會出現在畫布上。

+ +

和上述 globalCompositeOperation 相比,可以發現 source-in 和 source-atop 這兩種構圖組合所達到的效果,和裁剪路徑類似,而其中最大差異在於裁剪路徑不需加入新圖形,消失的部分也不會出現在畫布上,所以,如果想要限定繪圖區域,裁剪路徑會是更理想的作法。

+ +

繪畫圖形一章中,我們只提到 stroke() 和 fill() 函式,但其實還有第三個函式,那就是 clip() 函式。

+ +
+
clip()
+
轉換目前繪圖路徑為裁剪路徑。
+
+ +

呼叫 clip() 除了會替代 closePath() 來關閉路徑之外,還會轉換目前填滿或勾勒繪圖路徑為裁剪路徑。

+ +

 {{HTMLElement("canvas")}} 畫布預設有一個等同於本身大小的裁剪路徑,等同於無裁剪效果。

+ +

clip 範例

+ +

本範例使用了圓形的裁剪路徑,來限定畫星星時的繪圖區域。

+ +
function draw() {
+  var ctx = document.getElementById('canvas').getContext('2d');
+  ctx.fillRect(0,0,150,150);
+  ctx.translate(75,75);
+
+  // Create a circular clipping path
+  ctx.beginPath();
+  ctx.arc(0,0,60,0,Math.PI*2,true);
+  ctx.clip();
+
+  // draw background
+  var lingrad = ctx.createLinearGradient(0,-75,0,75);
+  lingrad.addColorStop(0, '#232256');
+  lingrad.addColorStop(1, '#143778');
+
+  ctx.fillStyle = lingrad;
+  ctx.fillRect(-75,-75,150,150);
+
+  // draw stars
+  for (var j=1;j<50;j++){
+    ctx.save();
+    ctx.fillStyle = '#fff';
+    ctx.translate(75-Math.floor(Math.random()*150),
+                  75-Math.floor(Math.random()*150));
+    drawStar(ctx,Math.floor(Math.random()*4)+2);
+    ctx.restore();
+  }
+
+}
+
+function drawStar(ctx,r){
+  ctx.save();
+  ctx.beginPath()
+  ctx.moveTo(r,0);
+  for (var i=0;i<9;i++){
+    ctx.rotate(Math.PI/5);
+    if(i%2 == 0) {
+      ctx.lineTo((r/0.525731)*0.200811,0);
+    } else {
+      ctx.lineTo(r,0);
+    }
+  }
+  ctx.closePath();
+  ctx.fill();
+  ctx.restore();
+}
+
+ + + +

一開始我們先畫了一個黑色矩形作為畫布背景,然後移動畫布原點到中央,接著我們繪製弧線並呼叫 clip(),藉以建立圓形的裁剪路徑。畫布儲存狀態亦可儲存裁剪路徑。若要保留原本的裁剪路徑,則可於繪製新的裁剪路徑之前,先行儲存畫布狀態。

+ +

繪製裁剪路徑之後,所產生的所有圖形都只會出現在路徑以內,從後來繪製的漸層背景中可看出此特性。我們用自訂的 drawStar() 函數產生 50 個隨機散佈、大小不一的星星。這些星星同樣只會出現在裁剪路徑的範圍之內。

+ +

{{EmbedLiveSample("A_clip_example", "180", "180", "https://mdn.mozillademos.org/files/208/Canvas_clip.png")}}

+ +

{{PreviousNext("Web/Guide/HTML/Canvas_tutorial/Transformations", "Web/Guide/HTML/Canvas_tutorial/Basic_animations")}}

diff --git a/files/zh-tw/web/api/canvas_api/tutorial/drawing_shapes/index.html b/files/zh-tw/web/api/canvas_api/tutorial/drawing_shapes/index.html new file mode 100644 index 0000000000..96fe2b9615 --- /dev/null +++ b/files/zh-tw/web/api/canvas_api/tutorial/drawing_shapes/index.html @@ -0,0 +1,551 @@ +--- +title: 繪製圖形 +slug: Web/API/Canvas_API/Tutorial/Drawing_shapes +translation_of: Web/API/Canvas_API/Tutorial/Drawing_shapes +--- +
{{CanvasSidebar}} {{PreviousNext("Web/API/Canvas_API/Tutorial/Basic_usage", "Web/API/Canvas_API/Tutorial/Applying_styles_and_colors")}}
+ +

網格(Grid)

+ +

在開始繪圖前,我們必須先了解畫布 (canvas) 網格,或著是說座標空間。在前一頁教學中的 HTML 範本有一個寬150 pixels (像素)、高150 pixels 的畫布。如右圖,你在畫布預設網格上繪圖,網格上 1 單位相當於畫布上 1 pixel,網格的原點 (座標 (0, 0) ) 坐落於左上角,所有元素定位皆相對於此左上角原點,所以藍色方塊的位置為從左往右推 x pixels、從上往下推 y pixels (亦即座標 (x, y) )。現在我們先專注在預設設定上,之後我們會看到如何轉換原點位置、旋轉網格以及縮放網格。

+ +

 

+ +

 

+ +

 

+ +

畫矩形

+ +

不同於SVG,{{HTMLElement("canvas")}}只支援一種原始圖形,矩形。所有的圖形都必須由一或多個繪圖路徑構成,而我們正好有一些繪圖路徑函數可以讓我們畫出複雜的圖形。

+ +
+

首先來看看矩形,共有三個矩形繪圖函數:

+ +
+
fillRect(x, y, width, height)
+
畫出一個填滿的矩形。
+
strokeRect(x, y, width, height)
+
畫出一個矩形的邊框
+
clearRect(x, y, width, height)
+
清除指定矩形區域內的內容,使其變為全透明。
+
+ +

這三個函數都接受一樣的參數: x, y代表從原點出發的座標位置,width, height代表矩形的寬高。

+ +

矩形範例

+ + + +
function draw() {
+  var canvas = document.getElementById('canvas');
+  if (canvas.getContext) {
+    var ctx = canvas.getContext('2d');
+
+    ctx.fillRect(25,25,100,100);
+    ctx.clearRect(45,45,60,60);
+    ctx.strokeRect(50,50,50,50);
+  }
+}
+ +

本例結果如下:

+ +

{{EmbedLiveSample("Rectangular_shape_example", 160, 160, "https://mdn.mozillademos.org/files/245/Canvas_rect.png")}}

+ +

fillRect()函數畫出一個寬高都100 pixels的矩形,clearRect()函數清除中央60 x 60 pixels大的正方形區域,接著strokeRect()在被清除區域內畫上一個50 x 50 pixels的矩形邊框。

+ +

之後我們會看到另外兩種代替clearRect()的方法,還有如何改變圖形顏色與筆畫樣式。

+ +

不像之後會看到的路徑繪圖函數,這三個函數會立即在畫布上畫出矩形。

+ +

路徑繪製

+ +

使用路徑 (path) 來畫圖形需要多一點步驟,一開始先產生路徑,然後用繪圖指令畫出路徑,然後再結束路徑,一旦路徑產生後便可以用畫筆或填滿方式來渲染生成,這裡是一些可用函數:

+ +
+
{{domxref("CanvasRenderingContext2D.beginPath", "beginPath()")}}
+
產生一個新路徑,產生後再使用繪圖指令來設定路徑。
+
{{domxref("CanvasRenderingContext2D.closePath", "closePath()")}}
+
閉合路徑好讓新的繪圖指令來設定路徑。
+
路徑 API
+
路徑 API,這些 API 便是繪圖指令
+
+ +
+
{{domxref("CanvasRenderingContext2D.stroke", "stroke()")}}
+
畫出圖形的邊框。
+
{{domxref("CanvasRenderingContext2D.fill", "fill()")}}
+
填滿路徑內容區域來產生圖形。
+
+ +

第一步呼叫 beginPath() 產生一個路徑,表面下,路徑會被存在一個次路徑 (sub-path) 清單中,例如直線、曲線等,這些次路徑集合起來就形成一塊圖形。每一次呼叫這個方法,次路徑清單就會被重設,然後我們便能夠畫另一個新圖形。

+ +
Note: 當目前路徑為空(例如接著呼叫beginPath()完後)或是在一個新畫布上,不論為何,第一個路徑繪圖指令總是moveTo();因為每當重設路徑後,你幾乎都會需要設定繪圖起始點。
+ +

第二步是呼叫各式方法來實際設定繪圖路徑,稍後我們將會介紹這部分。

+ +

第三步,也是非必要的一步,就是呼叫closePath()。這個方法會在現在所在點到起始點間畫一條直線以閉合圖形,如果圖形已經閉合或是只含一個點,這個方法不會有任何效果。

+ +
Note: 當呼叫fill(),任何開放的圖形都會自動閉合,所以不需要再呼叫closePath(),但是stroke()並非如此。
+ +

畫一個三角形

+ +

這是一個畫出三角形的程式碼範例。

+ + + +
function draw() {
+  var canvas = document.getElementById('canvas');
+  if (canvas.getContext){
+    var ctx = canvas.getContext('2d');
+
+    ctx.beginPath();
+    ctx.moveTo(75,50);
+    ctx.lineTo(100,75);
+    ctx.lineTo(100,25);
+    ctx.fill();
+  }
+}
+
+ +

結果如下:

+ +

{{EmbedLiveSample("Drawing_a_triangle", 110, 110, "https://mdn.mozillademos.org/files/9847/triangle.png")}}

+ +

移動畫筆

+ +

moveTo()是一個很有用的函數,moveTo()不會畫任何圖形,但卻是上述路徑清單的一部分,這大概有點像是把筆從紙上一點提起來,然後放到另一個點。

+ +
+
{{domxref("CanvasRenderingContext2D.moveTo", "moveTo(x, y)")}}
+
移動畫筆到指定的(x, y)座標點
+
+ +

當初始化畫布或是呼叫beginPath(),通常會想要使用moveTo()來指定起始點,我們可以用moveTo()畫不連結的路徑,看一下笑臉圖範例,圖中紅線即為使用到moveTo()的位置。

+ +

你可以拿下面的程式碼,放進先前的draw()函數,自己試試看效果。

+ + + +
function draw() {
+  var canvas = document.getElementById('canvas');
+  if (canvas.getContext){
+    var ctx = canvas.getContext('2d');
+
+    ctx.beginPath();
+    ctx.arc(75,75,50,0,Math.PI*2,true); // Outer circle
+    ctx.moveTo(110,75);
+    ctx.arc(75,75,35,0,Math.PI,false);   // Mouth (clockwise)
+    ctx.moveTo(65,65);
+    ctx.arc(60,65,5,0,Math.PI*2,true);  // Left eye
+    ctx.moveTo(95,65);
+    ctx.arc(90,65,5,0,Math.PI*2,true);  // Right eye
+    ctx.stroke();
+  }
+}
+
+ +

結果如下:

+ +

{{EmbedLiveSample("Moving_the_pen", 160, 160, "https://mdn.mozillademos.org/files/252/Canvas_smiley.png")}}

+ +

移除moveTo()便可以看到線條連結起來。

+ +
+

Note: 有關arc(),請參照下方 {{anch("Arcs")}} .

+
+ +

線條

+ +

用lineTo()方法畫直線。

+ +
+
{{domxref("CanvasRenderingContext2D.lineTo", "lineTo(x, y)")}}
+
從目前繪圖點畫一條直線到指定的(x, y)座標點。
+
+ +

本方法接受x, y參數作為線條結束點的座標位置,至於起始點則視前一個繪圖路徑,由前一個繪圖路徑的結束點作為起始點,當然,起始點也可以用moveTo()方法來變更。

+ +

下面畫兩個三角形,一個填滿,一個空心。

+ + + +
function draw() {
+  var canvas = document.getElementById('canvas');
+  if (canvas.getContext){
+    var ctx = canvas.getContext('2d');
+
+    // Filled triangle
+    ctx.beginPath();
+    ctx.moveTo(25,25);
+    ctx.lineTo(105,25);
+    ctx.lineTo(25,105);
+    ctx.fill();
+
+    // Stroked triangle
+    ctx.beginPath();
+    ctx.moveTo(125,125);
+    ctx.lineTo(125,45);
+    ctx.lineTo(45,125);
+    ctx.closePath();
+    ctx.stroke();
+  }
+}
+
+ +

從呼叫beginPath()起始一個新圖形路徑,然後用moveTo()移到我們想要的起始點,然後再畫兩條線形成三角形的兩邊。

+ +

{{EmbedLiveSample("Lines", 160, 160, "https://mdn.mozillademos.org/files/238/Canvas_lineTo.png")}}

+ +

我們可以看到填滿(fill)三角形和勾勒(stroke)三角形的區別;當填滿時,圖形會自動閉合,不過勾勒則不會,所以如果沒有呼叫closePaht()的話,只會畫出兩條線而非三角形。

+ +

弧形

+ +

用arc()方法來畫弧形或圓形。雖然也可以用arcTo(),但這個方法比較不可靠,所以這裡我們不討論arcTo()。

+ +
+
{{domxref("CanvasRenderingContext2D.arc", "arc(x, y, radius, startAngle, endAngle, anticlockwise)")}}
+
畫一個弧形
+
+ +

本方法接受五個參數: x, y代表圓心座標點,radius代表半徑,startAngle, endAngle分別代表沿著弧形曲線上的起始點與結束點的弧度,弧度測量是相對於x軸,anticlockwise為true代表逆時針作圖、false代表順時針作圖。

+ +
+

Note: arc()方法用的是弧度(radians)而非角度(degrees),如果要在弧度與角度間換算,可以利用以下javascript程式碼: radians = (Math.PI/180) * degrees.

+
+ +

以下例子比較複雜,它會畫出12個不同的弧形。

+ +

兩個for迴圈走一遍弧形圖列的列跟行,每一個弧形由呼叫beginPath()開始新的繪圖路徑,為了清楚,我們在程式範例中用變數儲存參數,你不一定要這麼做。

+ +

x, y座標點的部分應該相當淺顯,radius和startAngle是定值,endAngle從180度(半圓)開始,然後每一行增加90度,最後一行便會形成一個完整的圓。

+ +

第1, 3列的anticlockwise 為false,所以會順時針作圖,2, 4列的anticlockwise 為true,所以會逆時針作圖。最後的if決定下半部是用填滿圖形,上半部是勾勒圖形。

+ + + +
function draw() {
+  var canvas = document.getElementById('canvas');
+  if (canvas.getContext){
+    var ctx = canvas.getContext('2d');
+
+    for(var i=0;i<4;i++){
+      for(var j=0;j<3;j++){
+        ctx.beginPath();
+        var x              = 25+j*50;               // x coordinate
+        var y              = 25+i*50;               // y coordinate
+        var radius         = 20;                    // Arc radius
+        var startAngle     = 0;                     // Starting point on circle
+        var endAngle       = Math.PI+(Math.PI*j)/2; // End point on circle
+        var anticlockwise  = i%2==0 ? false : true; // clockwise or anticlockwise
+
+        ctx.arc(x, y, radius, startAngle, endAngle, anticlockwise);
+
+        if (i>1){
+          ctx.fill();
+        } else {
+          ctx.stroke();
+        }
+      }
+    }
+  }
+}
+
+{{EmbedLiveSample("Arcs", 160, 210, "https://mdn.mozillademos.org/files/204/Canvas_arc.png")}} + +

貝茲曲線(Bezier curve)與二次曲線(quadratic curve)

+ +

二次與三次貝茲曲線(Bézier curves)是另一種可用來構成複雜有機圖形的路徑。

+ +
+
{{domxref("CanvasRenderingContext2D.quadraticCurveTo", "quadraticCurveTo(cp1x, cp1y, x, y)")}}
+
從目前起始點畫一條二次貝茲曲線到x, y指定的終點,控制點由cp1x, cp1y指定。
+
{{domxref("CanvasRenderingContext2D.bezierCurveTo", "bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y)")}}
+
從目前起始點畫一條三次貝茲曲線到x, y指定的終點,控制點由(cp1x, cp1y)和(cp2x, cp2y)指定。
+
+ +

二次和三次的差別可以從右圖看出;貝茲曲線的起始和終點以藍點標示,其中二次貝茲曲線只有一個控制點(如紅點標示)而三次貝茲曲線有兩個控制點。

+ +

二次和三次貝茲曲線都用x, y參數定義終點座標,然後用cp1x, xp1y定義第一個控制點座標、cp2x, xp2y定義第二個控制點座標。

+ +

用二次和三次貝茲曲線作圖相當具有挑戰性,因為不像使用 Adobe illustrator 的向量繪圖軟體,我們在繪圖時無法即時看到繪圖狀況,所以畫複雜的圖形十分困難。下面的範例我們畫了一些圖形,如果你有時間與耐心,可以畫出更複雜的圖形。

+ +

二次貝茲曲線

+ +

本例用了數個二次貝茲曲線畫了一個會話框。

+ + + +
function draw() {
+  var canvas = document.getElementById('canvas');
+  if (canvas.getContext) {
+    var ctx = canvas.getContext('2d');
+
+    // Quadratric curves example
+    ctx.beginPath();
+    ctx.moveTo(75,25);
+    ctx.quadraticCurveTo(25,25,25,62.5);
+    ctx.quadraticCurveTo(25,100,50,100);
+    ctx.quadraticCurveTo(50,120,30,125);
+    ctx.quadraticCurveTo(60,120,65,100);
+    ctx.quadraticCurveTo(125,100,125,62.5);
+    ctx.quadraticCurveTo(125,25,75,25);
+    ctx.stroke();
+  }
+}
+
+ +

{{EmbedLiveSample("Quadratic_Bezier_curves", 160, 160, "https://mdn.mozillademos.org/files/243/Canvas_quadratic.png")}}

+ +

三次貝茲曲線

+ +

這個範例畫了一個愛心。

+ + + +
function draw() {
+  var canvas = document.getElementById('canvas');
+  if (canvas.getContext){
+    var ctx = canvas.getContext('2d');
+
+    // Quadratric curves example
+    ctx.beginPath();
+    ctx.moveTo(75,40);
+    ctx.bezierCurveTo(75,37,70,25,50,25);
+    ctx.bezierCurveTo(20,25,20,62.5,20,62.5);
+    ctx.bezierCurveTo(20,80,40,102,75,120);
+    ctx.bezierCurveTo(110,102,130,80,130,62.5);
+    ctx.bezierCurveTo(130,62.5,130,25,100,25);
+    ctx.bezierCurveTo(85,25,75,37,75,40);
+    ctx.fill();
+  }
+}
+
+ +

{{EmbedLiveSample("Cubic_Bezier_curves", 160, 160, "https://mdn.mozillademos.org/files/207/Canvas_bezier.png")}}

+ +

矩形

+ +

除了在{畫矩形}段落中提到的三個方法,還有rect()方法能夠在畫布上畫矩形;rect()方法會在目前路徑下加入一個矩形繪圖路徑。

+ +
+
{{domxref("CanvasRenderingContext2D.bezierCurveTo", "rect(x, y, width, height)")}}
+
畫一個左上角位於(x, y)、寬width、高height的矩形。
+
+ +

呼叫這個方法,moveTo()方法會以(0, 0)參數被自動呼叫,所以目前的下筆點跟者自動被設為預設座標。

+ +

多樣組合

+ +

截至目前為止,我們都只用一種路徑函數在各個範例裡作圖,不過,其實繪圖時並沒有任何使用數量或種類上的路徑函數限制,所以最後我們來試著組合各樣路徑繪圖函數來畫一些十分有名的遊戲角色。

+ + + +
function draw() {
+  var canvas = document.getElementById('canvas');
+  if (canvas.getContext){
+    var ctx = canvas.getContext('2d');
+
+    roundedRect(ctx,12,12,150,150,15);
+    roundedRect(ctx,19,19,150,150,9);
+    roundedRect(ctx,53,53,49,33,10);
+    roundedRect(ctx,53,119,49,16,6);
+    roundedRect(ctx,135,53,49,33,10);
+    roundedRect(ctx,135,119,25,49,10);
+
+    ctx.beginPath();
+    ctx.arc(37,37,13,Math.PI/7,-Math.PI/7,false);
+    ctx.lineTo(31,37);
+    ctx.fill();
+
+    for(var i=0;i<8;i++){
+      ctx.fillRect(51+i*16,35,4,4);
+    }
+
+    for(i=0;i<6;i++){
+      ctx.fillRect(115,51+i*16,4,4);
+    }
+
+    for(i=0;i<8;i++){
+      ctx.fillRect(51+i*16,99,4,4);
+    }
+
+    ctx.beginPath();
+    ctx.moveTo(83,116);
+    ctx.lineTo(83,102);
+    ctx.bezierCurveTo(83,94,89,88,97,88);
+    ctx.bezierCurveTo(105,88,111,94,111,102);
+    ctx.lineTo(111,116);
+    ctx.lineTo(106.333,111.333);
+    ctx.lineTo(101.666,116);
+    ctx.lineTo(97,111.333);
+    ctx.lineTo(92.333,116);
+    ctx.lineTo(87.666,111.333);
+    ctx.lineTo(83,116);
+    ctx.fill();
+
+    ctx.fillStyle = "white";
+    ctx.beginPath();
+    ctx.moveTo(91,96);
+    ctx.bezierCurveTo(88,96,87,99,87,101);
+    ctx.bezierCurveTo(87,103,88,106,91,106);
+    ctx.bezierCurveTo(94,106,95,103,95,101);
+    ctx.bezierCurveTo(95,99,94,96,91,96);
+    ctx.moveTo(103,96);
+    ctx.bezierCurveTo(100,96,99,99,99,101);
+    ctx.bezierCurveTo(99,103,100,106,103,106);
+    ctx.bezierCurveTo(106,106,107,103,107,101);
+    ctx.bezierCurveTo(107,99,106,96,103,96);
+    ctx.fill();
+
+    ctx.fillStyle = "black";
+    ctx.beginPath();
+    ctx.arc(101,102,2,0,Math.PI*2,true);
+    ctx.fill();
+
+    ctx.beginPath();
+    ctx.arc(89,102,2,0,Math.PI*2,true);
+    ctx.fill();
+  }
+}
+
+// A utility function to draw a rectangle with rounded corners.
+
+function roundedRect(ctx,x,y,width,height,radius){
+  ctx.beginPath();
+  ctx.moveTo(x,y+radius);
+  ctx.lineTo(x,y+height-radius);
+  ctx.quadraticCurveTo(x,y+height,x+radius,y+height);
+  ctx.lineTo(x+width-radius,y+height);
+  ctx.quadraticCurveTo(x+width,y+height,x+width,y+height-radius);
+  ctx.lineTo(x+width,y+radius);
+  ctx.quadraticCurveTo(x+width,y,x+width-radius,y);
+  ctx.lineTo(x+radius,y);
+  ctx.quadraticCurveTo(x,y,x,y+radius);
+  ctx.stroke();
+}
+
+ +
+

結果如下:

+ +

{{EmbedLiveSample("Making_combinations", 160, 160)}}

+ +

畫出這樣的圖其實沒有想像中的困難,所以我們就不再描述細節了,其中比較需要注意的是,我們在繪圖環境上用了fillStyle屬性以及一個自定義的效用函數(roundedRect()),利用效用函數來執行時常重複的繪圖工作可以幫忙減少程式碼數量與複雜度。

+ +

稍後我們會更進一步介紹fillStyle屬性,這個範例我們所做是的透過fillStyle屬性來改變路徑填滿色為白色,然後再改回預設黑色,來變換填滿顏色,。

+ +

{{PreviousNext("Web/Guide/HTML/Canvas_tutorial/Basic_usage", "Web/Guide/HTML/Canvas_tutorial/Using_images")}}

+
+
+ +

Path2D objects

+ +

如同前面的範例,canvas 上常常會畫上一連串的繪圖路徑,為了簡化程式碼還有改善效能,我們可以利用 {{domxref("Path2D")}} 物件 (目前在較先進的瀏覽器上已經有提供了)。Path2D 讓我們可以快取和記錄繪圖指令,方便快速重複地繪圖,底下我就來看看如何使用 Path2D :

+ +

{{domxref("Path2D.Path2D", "Path2D()")}}

+ +

    Path2D 的建構子,可接受的參數有無參數、另一個 Path2D 物件、 字元表式的 SVG path:

+ +
new Path2D();     // 不傳入參數會回傳一個空的 Path2D 物件
+new Path2D(path); // 複製傳入的 Path2D 物件,然後以之建立 Path2D 物件
+new Path2D(d);    // 以傳入的 SVG 路徑建立 Path2D 物件
+ +

所有已知的 路徑 API,如 rect, arc 等等,都可以在 Path2D 上找到。

+ +

Path2D 物件還可以加入其他 Path2D 物件,這讓我們可以很方便的組合多個物件使用。

+ +

{{domxref("Path2D.addPath", "Path2D.addPath(path [, transform])")}}

+ +

    addPath 增加一個 Path2D 物件,其中的非必要參數是變形矩陣。

+ +

Path2D example

+ +

這個例子用 Path2D 物件將矩形和圓形的繪圖路徑存起來,以供之後使用。而配合新的 Path2D API,有一些繪圖方法更接受傳入 Path2D 作為繪圖路徑使用,例如下方本例所用到的 stroke 和 fill。

+ +
function draw() {
+  var canvas = document.getElementById('canvas');
+  if (canvas.getContext){
+    var ctx = canvas.getContext('2d');
+
+    var rectangle = new Path2D();
+    rectangle.rect(10, 10, 50, 50);
+
+    var circle = new Path2D();
+    circle.moveTo(125, 35);
+    circle.arc(100, 35, 25, 0, 2 * Math.PI);
+
+    ctx.stroke(rectangle);
+    ctx.fill(circle);
+  }
+}
+ +

{{EmbedLiveSample("Path2D_example", 130, 110, "https://mdn.mozillademos.org/files/9851/path2d.png")}}

+ +

使用向量路徑 (SVG paths)

+ +

另一個強而有力的特色是在 SVG 和 Canvas 中我們都可以使用 SVG path。

+ +

下面的路徑會移到座標點 (10, 10) (M10, 10),然後水平右移 80 點 (h 80),垂至下移 80 點 (v 80) 水平左移 80 點 (h -80) 最後回到起始點 (z),請到Path2D 建構子頁面看繪圖範例結果。

+ +
var p = new Path2D("M10 10 h 80 v 80 h -80 Z");
+ +
{{PreviousNext("Web/API/Canvas_API/Tutorial/Basic_usage", "Web/API/Canvas_API/Tutorial/Applying_styles_and_colors")}}
+ +

 

diff --git a/files/zh-tw/web/api/canvas_api/tutorial/drawing_text/index.html b/files/zh-tw/web/api/canvas_api/tutorial/drawing_text/index.html new file mode 100644 index 0000000000..cfafa8a5a8 --- /dev/null +++ b/files/zh-tw/web/api/canvas_api/tutorial/drawing_text/index.html @@ -0,0 +1,397 @@ +--- +title: 使用canvas繪製文字 +slug: Web/API/Canvas_API/Tutorial/Drawing_text +translation_of: Web/API/Canvas_API/Tutorial/Drawing_text +--- +
{{CanvasSidebar}} {{PreviousNext("Web/API/Canvas_API/Tutorial/Applying_styles_and_colors", "Web/API/Canvas_API/Tutorial/Using_images")}}
+ +

{{ gecko_minversion_header("1.9") }}

+ +

canvas元素支援在標準 HTML 5 特色以及少許實驗性的Mozilla方法和功能上繪製文字。

+ +

文字可以包括任何Unicode字元,即使用那些超出“基本多文種平面”的字元也可以。

+ +

{{ fx_minversion_note("3.5", '在Firefox 3.5或之後的版本,當繪圖時,任何對於 shadow effects(陰影效果)的處理可以使用在文字上。') }}

+ +

方法概述

+ + + + + + + + + + + + + + + + + + + + + + + + + +
void fillText(in DOMString text, in float x, in float y, [optional] in float maxWidth); {{ gecko_minversion_inline("1.9.1") }}
nsIDOMTextMetrics measureText(in DOMString textToMeasure); {{ gecko_minversion_inline("1.9.1") }}
void mozDrawText(in DOMString textToDraw); {{ deprecated_inline() }}
float mozMeasureText(in DOMString textToMeasure); {{ deprecated_inline() }}
void mozPathText(in DOMString textToPath);
void mozTextAlongPath(in DOMString textToDraw, in boolean stroke);
void strokeText(in DOMString text, in float x, in float y, [optional] in float maxWidth); {{ gecko_minversion_inline("1.9.1") }}
+ +

 

+ +

屬性

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
屬性型別描述
font {{ gecko_minversion_inline("1.9.1") }}DOMString +

當前的文字樣式被用在繪製文字。該字串使用和 CSS font(樣式表字型)相同的語法。要改變繪製文字的樣式,只要簡單的改變它的屬性值即可,就像下面展示的,預設的字型是10px(像素) sans-serif(字型名稱)

+ +

例如:

+ +
+ctx.font = "20pt Arial";
+
mozTextStyle {{ deprecated_inline() }}DOMString +

由上面的Html5字型 屬性取代

+
textAlign {{ gecko_minversion_inline("1.9.1") }}DOMString +

當前繪製文字所使用的文字對齊方式。  可使用的值:

+ +
+
left
+
文字靠左對齊。
+
right
+
文字靠右對齊。
+
center
+
文字置中對齊。
+
start
+
文字依照行首對齊 (書寫習慣由左到右的地區就靠左對齊,書寫習慣由右到左的就靠右對齊。).
+
end
+
文字依照行尾對齊(書寫習慣由左到右的地區就靠右對齊,書寫習責由右到左的地區就靠左對齊。)
+
+ +

預設的值是 start.

+
textBaseline {{ gecko_minversion_inline("1.9.1") }}DOMString +

當前繪製文字的基線位置  可使用的值:

+ +
+
top
+
基線在字元區塊的頂部(圖中top of the squre位置)。
+
hanging(懸掛)
+
文字基線在拼音文字頂部的位置(圖中hanging baseline)  當前仍未支援;會顯示 alphabetic代替。
+
middle
+
文字基線在字元區塊的中間。
+
alphabetic(拼音文字)
+
這是一般拼音文字底線的位置。
+
ideographic(表意文字)
+
文字在表意文字(如漢字)底部的位置  當前仍未支援;會顯示alphabetic代替。
+
bottom
+
基線在拼音文字下伸部的位置 這與ideographic的基線位置不同,因為表意文字沒有下伸部
+
+ +

預設使用 alphabetic.

+
+ +

下圖展示了textBaseline屬性所支援的各種基線,感謝 WHATWG.

+ +

top of em squre(字元區塊頂部)大致在字型中所有字母的最頂部位置,hanging basline(懸掛基線)則是在一些特殊(較小的,像是“आ”)字母頂部,middle則是在top of em squre(字元區塊頂部和bottom of em squre(字元區塊底部)的中間,alphabetic(拼音文字)的基線位置則是在一般拼音字母如Á,ÿ,f,Ω的底線位置。ideographic(表意文字)的基線在字元的底部位置,bottom of em squre(字元區塊底部)則大致是字型中所有字母的最底部位置。而top and bottom of the bounding box(上下的區域範圍線)則比這些基線都來得更遠,基於字母的高度可能超過字元區塊頂部和底部的範圍。

+ +

方法

+ +

fillText()

+ +

繪製文字使用font屬性指定的文字樣式,對齊則使用textAlign屬性,而指定基線則使用textBaseline.  填充文字當前使用fillStyle,而strokeStyle則被忽略

+ +
注意:這個方法在 Gecko 1.9.1 (Firefox 3.5)時引進,且是HTML 5標準的一部分.
+ +
void fillText(
+   in DOMString textToDraw,
+   in float x,
+   in float y,
+   [optional] in float maxWidth
+);
+
+ +
參數
+ +
+
textToDraw
+
將文字繪製到文本中。
+
x
+
繪製位置的x座標。
+
y
+
繪製位置的y座標。
+
maxWidth
+
最大寬度,可選用的;繪製字串最大長度 如果指定此參數,當字串被計算出比這個值更寬,它會自動選擇水平方向更窄的字型(如果有可用的字型或是有可讀的字型可以嵌入當前字型之中),或者縮小字型。
+
+ +
範例
+ +
ctx.fillText("Sample String", 10, 50);
+
+ +

measureText()

+ +

測量文字。返回一個物件包含了寬度,像素值,所指定的文字會以當前的文字樣式繪製。

+ +
注意: 這個方法在 Gecko 1.9.1 (Firefox 3.5) 引進,且是HTML 5標準的一部分。
+ +
nsIDOMTextMetrics measureText(
+  in DOMString textToMeasure
+);
+
+ +
參數
+ +
+
textToMeasure
+
該字串的像素值。
+
+ +
返回值
+ +

nsIDOMTextMetrics物件的width屬性在繪製時會將數字設定給CSS 的像素值寬度。

+ +

mozDrawText()

+ +

{{ deprecated_header() }}

+ +

繪製文字使用由mozTextStyle屬性的文字樣式。文本當前的填充顏色被用來當做文字顏色。

+ +
注意:這個方法已經不被建議使用,請使用正式的HTML 5方法 fillText() and strokeText().
+ +
void mozDrawText(
+   in DOMString textToDraw
+);
+
+ +
參數
+ +
+
textToDraw
+
將文字繪製到文本。
+
+ +
範例
+ +
ctx.translate(10, 50);
+ctx.fillStyle = "Red";
+ctx.mozDrawText("Sample String");
+
+ +

這個範例將文字“Sample String”繪製到畫布(canvas)上。

+ +

mozMeasureText()

+ +

{{ deprecated_header() }}

+ +

返回寬度,像素值,指定文字

+ +
注意:這個方法已經已宣告棄用,請使用正式的HTML 5方法measureText().
+ +
float mozMeasureText(
+  in DOMString textToMeasure
+);
+
+ +
參數
+ +
+
textToMeasure
+
字串的寬度像素值
+
+ +
返回值
+ +

文字的寬度像素值

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

這個範例測量了字串的寬度,接著使用這個資訊將它畫在畫布(canvas)的水平中心。

+ +

mozPathText()

+ +

給文字路徑加上外框線,如果你想要的話,它允許你替文字加上框線代替填充它。

+ +
void mozPathText(
+  in DOMString textToPath
+);
+
+ +
參數
+ +
+
textToPath
+
為當前的文字路徑加上框線
+
+ +
Example
+ +
ctx.fillStyle = "green";
+ctx.strokeStyle = "black";
+ctx.mozPathText("Sample String");
+ctx.fill()
+ctx.stroke()
+
+ +

這個範例繪出文字“Sample String”,填充顏色是綠色,外框顏色是黑色。

+ +

mozTextAlongPath()

+ +

Adds (or draws) the specified text along the current path.

+ +
void mozTextAlongPath(
+  in DOMString textToDraw,
+  in boolean stroke
+);
+
+ +
參數
+ +
+
textToDraw
+
沿著指定路徑繪出文字
+
stroke
+
如果參數是 true(真值),文字會沿著指定路徑繪製。如果 false(假值),這個文字則會加入到路徑之中,再沿著當前路徑繪製。
+
+ +
備註
+ +

字體不會沿著路徑曲線縮放或變形,反而在彎曲路徑下,字體每次計算都會當成是直線在處理。這可以用來建立一些特殊的效果。

+ +

strokeText()

+ +

繪製文字使用font屬性指定的文字樣式,對齊則使用textAlign屬性,而指定基線則使用textBaseline.  當前使用strokeStyle來建立文字外框。

+ +
注意: 這個方法在 Gecko 1.9.1 (Firefox 3.5)時引進,且是HTML 5標準的一部分。
+ +
void strokeText(
+   in DOMString textToDraw,
+   in float x,
+   in float y,
+   [optional] in float maxWidth
+);
+
+ +
參數
+ +
+
textToDraw
+
將文字繪製到文本中。
+
x
+
繪製位置的x座標。
+
y
+
繪製位置的y座標
+
maxWidth
+
最大寬度,可選用的;繪製字串最大長度 如果指定此參數,當字串被計算出比這個值更寬,它會自動選擇水平方向更窄的字型(如果有可用的字型或是有可讀的字型可以嵌入當前字型之中),或者縮小字型。
+
+ +
範例
+ +
ctx.strokeText("Sample String", 10, 50);
+
+ +

備註

+ + + +

其它範例

+ + + +

瀏覽器兼容性

+ +

{{ CompatibilityTable() }}

+ +
+
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1+3.5+9.010.54.0
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support2.1{{ CompatUnknown() }}9.011.03.2
+
+
+ +

 

diff --git a/files/zh-tw/web/api/canvas_api/tutorial/index.html b/files/zh-tw/web/api/canvas_api/tutorial/index.html new file mode 100644 index 0000000000..15280a881d --- /dev/null +++ b/files/zh-tw/web/api/canvas_api/tutorial/index.html @@ -0,0 +1,69 @@ +--- +title: Canvas 教學文件 +slug: Web/API/Canvas_API/Tutorial +translation_of: Web/API/Canvas_API/Tutorial +--- +
{{CanvasSidebar}}
+ +

+ +
+

<canvas> 是一個 HTML 元素,我們可以利用程式腳本在這個元素上繪圖(通常是用 JavaScript)。除了繪圖,我們還可以合成圖片或做一些簡單(或是不那麼簡單)的動畫。右方的影像便是一些運用 <canvas> 的例子,接下來我們將會在教學文件中一一說明

+
+ +

本教學從基礎知識開始,描述如何利用 <canvas> 進行 2D 繪圖。教學中的範例會讓各位清楚瞭解 <canvas> 該如何運用,另外也會提供程式碼範例,讓大家嘗試製作自己的內容。

+ +

<canvas> 最早是由 Apple 為 Mac OS X Dashboard 所提出,之後 Safari 和 Google Chrome 也都採用。Gecko 1.8 作基礎的瀏覽器,如 Firefox 1.5 也都提供了支援。<canvas> 元素是 WhatWG Web applications 1.0(也就是 HTML5)規範的一部分,目前所有主流的瀏覽器都已支援。

+ +

在開始之前

+ +

<canvas> 並不困難,但你需要了解基本的 HTMLJavaScript。部分舊版瀏覽器不支援 <canvas>,不過基本上現今所有主流的瀏覽器都有支援。預設的畫布大小是 300px * 150px(寬 * 高)。但你也可以透過 HTML 寬、高屬性({{Glossary("attribute")}})自訂。為了在畫布上作畫,我們使用了一個 JavaScript context 物件來即時繪製圖形。

+ +

教學文件

+ + + +

參見

+ + + +

致歉各位貢獻者

+ +

由於 2013/6/17 那一週的不幸技術錯誤,所有有關本教學的歷史紀錄,包括過去所有貢獻者的紀錄都遺失了,我們深感抱歉,希望各位可以原諒這一次不幸的意外。

+ +
{{ Next("Web/Guide/HTML/Canvas_tutorial/Basic_usage") }}
+ +
 
diff --git a/files/zh-tw/web/api/canvas_api/tutorial/optimizing_canvas/index.html b/files/zh-tw/web/api/canvas_api/tutorial/optimizing_canvas/index.html new file mode 100644 index 0000000000..7fb8b35666 --- /dev/null +++ b/files/zh-tw/web/api/canvas_api/tutorial/optimizing_canvas/index.html @@ -0,0 +1,26 @@ +--- +title: 最佳化canvas +slug: Web/API/Canvas_API/Tutorial/Optimizing_canvas +translation_of: Web/API/Canvas_API/Tutorial/Optimizing_canvas +--- +

{{HTMLElement("canvas")}}在網頁2D繪圖上被大量運用於遊戲和複雜視覺化效果上。隨著繪圖複雜度越來越高,效能問題也會逐一浮現,所以最後我們在這邊列出一些最佳化畫布的方法,避免一些效能問題:

+ +

{{PreviousNext("Web/Guide/HTML/Canvas_tutorial/Basic_animations")}}

diff --git a/files/zh-tw/web/api/canvas_api/tutorial/pixel_manipulation_with_canvas/index.html b/files/zh-tw/web/api/canvas_api/tutorial/pixel_manipulation_with_canvas/index.html new file mode 100644 index 0000000000..398ef70484 --- /dev/null +++ b/files/zh-tw/web/api/canvas_api/tutorial/pixel_manipulation_with_canvas/index.html @@ -0,0 +1,265 @@ +--- +title: Pixel manipulation with canvas +slug: Web/API/Canvas_API/Tutorial/Pixel_manipulation_with_canvas +translation_of: Web/API/Canvas_API/Tutorial/Pixel_manipulation_with_canvas +--- +
{{CanvasSidebar}} {{PreviousNext("Web/API/Canvas_API/Tutorial/Advanced_animations", "Web/API/Canvas_API/Tutorial/Hit_regions_and_accessibility")}}
+ +
+

直到目前為止,我們還沒真正了解 pixels 在 canvas上的運用。使用ImageData物件,可直接對pixel 裡的陣列資料讀(read)寫(write)。在接下的內容中,也可了解到如何使影像平滑化(反鋸齒)及如何將影像保存在canvas之中。

+
+ +

ImageData物件

+ +

{{domxref("ImageData")}} 物件代表canvas區中最基礎的像素。

+ +

包含它只可讀的屬性:

+ +
+
width
+
影像中的寬度,以pixels為單位
+
height
+
影像中的高度,以pixels為單位
+
data
+
{{jsxref("Uint8ClampedArray")}} 代表一維陣列包含RGBA 格式。整數值介於0到255之間(包含255)。
+
+ +

data 屬性返回一個{{jsxref("Uint8ClampedArray")}},它可被當作為pixel的初始資料。每個pixel用4個1byte值做代表分別為透明值(也就是RGBA格式)。每個顏色組成皆是介於整數值介於0到255之間。而每個組成在一個陣列中被分配為一個連續的索引。從左上角 pixel 的紅色組成中的陣列由索引 0 為始。Pixels 執行順序為從左到右,再由上到下,直到整個陣列。

+ +

{{jsxref("Uint8ClampedArray")}}  包含height × width× 4 bytes的資料,同索引值從0到 (height×width×4)-1

+ +

例如,讀取影像的藍色組成的值。從pixel 的第200欄、第50行,你可以照著下面的步驟:

+ +
blueComponent = imageData.data[((50 * (imageData.width * 4)) + (200 * 4)) + 2];
+ +

使用Uint8ClampedArray.length屬性來讀取影像pixel的陣列大小

+ +
var numBytes = imageData.data.length;
+
+ +

創造一個 ImageData物件

+ +

可以使用{{domxref("CanvasRenderingContext2D.createImageData", "createImageData()")}}方法創造一個全新空白的ImageData 物件。

+ +

這裡有兩種createImageData()的方法:

+ +
var myImageData = ctx.createImageData(width, height);
+ +

這個方法是有規定大小尺寸.所有pixels預設是透明的黑色。

+ +

下面的方法一樣是由anotherImageData參考尺寸大小,由ImageData 物件創造一個與新的一樣的大小。這些新的物件的pixel皆預設為透明的黑色。

+ +
var myImageData = ctx.createImageData(anotherImageData);
+ +

得到pixel資料的內容

+ +

可以使用getImageData()這個方法,去取得canvas內容中ImageData 物件的資料含pixel 數據(data) 

+ +
var myImageData = ctx.getImageData(left, top, width, height);
+ +

這個方法會返回ImageData物件,它代表著在這canvas區域之中pixel 的數據(data) 。從各角落的點代表著 (left,top), (left+width, top), (left, top+height), and (left+width, top+height)。這些作標被設定為canvas 的空間座標單位。

+ +
+

注釋: 在ImageData 物件中,任何超出canvas外的pixels皆會返回透明的黑色的形式。

+
+ +

這個方法也被展示在使用canvas操作影像之中。

+ +

調色盤

+ +

這個範例使用getImageData() 方法去顯示在鼠標下的顏色。

+ +

首先,需要一個正確的滑鼠點layerX​​​​​​​和 layerY。在從getImageData() 提供pixel 陣列中(array)該點的pixel 數據(data) 。最後,使用陣列數據(array data)在<div>中設置背景色和文字去顯示該色。

+ + + +
var img = new Image();
+img.src = 'https://mdn.mozillademos.org/files/5397/rhino.jpg';
+var canvas = document.getElementById('canvas');
+var ctx = canvas.getContext('2d');
+img.onload = function() {
+  ctx.drawImage(img, 0, 0);
+  img.style.display = 'none';
+};
+var color = document.getElementById('color');
+function pick(event) {
+  var x = event.layerX;
+  var y = event.layerY;
+  var pixel = ctx.getImageData(x, y, 1, 1);
+  var data = pixel.data;
+  var rgba = 'rgba(' + data[0] + ', ' + data[1] +
+             ', ' + data[2] + ', ' + (data[3] / 255) + ')';
+  color.style.background =  rgba;
+  color.textContent = rgba;
+}
+canvas.addEventListener('mousemove', pick);
+
+ +

{{ EmbedLiveSample('A_color_picker', 610, 240) }}

+ +

在內容中寫入pixel 資料

+ +

可以使用putImageData() 方法將自訂pixel 數據(data) 放入內容中:

+ +
ctx.putImageData(myImageData, dx, dy);
+
+ +

dx 和 dy參數表示填入你所希望的座標,將它代入內容中左上角的pixel 數據(data)。

+ +

For example, to paint the entire image represented by myImageData to the top left corner of the context, you can simply do the following:

+ +
ctx.putImageData(myImageData, 0, 0);
+
+ +

灰階和負片效果

+ +

In this example we iterate over all pixels to change their values, then we put the modified pixel array back to the canvas using putImageData(). The invert function simply subtracts each color from the max value 255. The grayscale function simply uses the average of red, green and blue. You can also use a weighted average, given by the formula x = 0.299r + 0.587g + 0.114b, for example. See Grayscale on Wikipedia for more information.

+ + + +
var img = new Image();
+img.src = 'https://mdn.mozillademos.org/files/5397/rhino.jpg';
+img.onload = function() {
+  draw(this);
+};
+
+function draw(img) {
+  var canvas = document.getElementById('canvas');
+  var ctx = canvas.getContext('2d');
+  ctx.drawImage(img, 0, 0);
+  img.style.display = 'none';
+  var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
+  var data = imageData.data;
+
+  var invert = function() {
+    for (var i = 0; i < data.length; i += 4) {
+      data[i]     = 255 - data[i];     // red
+      data[i + 1] = 255 - data[i + 1]; // green
+      data[i + 2] = 255 - data[i + 2]; // blue
+    }
+    ctx.putImageData(imageData, 0, 0);
+  };
+
+  var grayscale = function() {
+    for (var i = 0; i < data.length; i += 4) {
+      var avg = (data[i] + data[i + 1] + data[i + 2]) / 3;
+      data[i]     = avg; // red
+      data[i + 1] = avg; // green
+      data[i + 2] = avg; // blue
+    }
+    ctx.putImageData(imageData, 0, 0);
+  };
+
+  var invertbtn = document.getElementById('invertbtn');
+  invertbtn.addEventListener('click', invert);
+  var grayscalebtn = document.getElementById('grayscalebtn');
+  grayscalebtn.addEventListener('click', grayscale);
+}
+
+ +

{{ EmbedLiveSample('Grayscaling_and_inverting_colors', 330, 270) }}

+ +

放大和平滑化(反鋸齒)

+ +

With the help of the {{domxref("CanvasRenderingContext2D.drawImage", "drawImage()")}} method, a second canvas and the {{domxref("CanvasRenderingContext2D.imageSmoothingEnabled", "imageSmoothingEnabled")}} property, we are able to zoom into our picture and see the details.

+ +

We get the position of the mouse and crop an image of 5 pixels left and above to 5 pixels right and below. Then we copy that one over to another canvas and resize the image to the size we want it to. In the zoom canvas we resize a 10×10 pixel crop of the original canvas to 200×200.

+ +
zoomctx.drawImage(canvas,
+                  Math.abs(x - 5), Math.abs(y - 5),
+                  10, 10, 0, 0, 200, 200);
+ +

Because anti-aliasing is enabled by default, we might want to disable the smoothing to see clear pixels. You can toggle the checkbox to see the effect of the imageSmoothingEnabled property (which needs prefixes for different browsers).

+ + + + + +
var img = new Image();
+img.src = 'https://mdn.mozillademos.org/files/5397/rhino.jpg';
+img.onload = function() {
+  draw(this);
+};
+
+function draw(img) {
+  var canvas = document.getElementById('canvas');
+  var ctx = canvas.getContext('2d');
+  ctx.drawImage(img, 0, 0);
+  img.style.display = 'none';
+  var zoomctx = document.getElementById('zoom').getContext('2d');
+
+  var smoothbtn = document.getElementById('smoothbtn');
+  var toggleSmoothing = function(event) {
+    zoomctx.imageSmoothingEnabled = this.checked;
+    zoomctx.mozImageSmoothingEnabled = this.checked;
+    zoomctx.webkitImageSmoothingEnabled = this.checked;
+    zoomctx.msImageSmoothingEnabled = this.checked;
+  };
+  smoothbtn.addEventListener('change', toggleSmoothing);
+
+  var zoom = function(event) {
+    var x = event.layerX;
+    var y = event.layerY;
+    zoomctx.drawImage(canvas,
+                      Math.abs(x - 5),
+                      Math.abs(y - 5),
+                      10, 10,
+                      0, 0,
+                      200, 200);
+  };
+
+  canvas.addEventListener('mousemove', zoom);
+}
+ +

{{ EmbedLiveSample('Zoom_example', 620, 490) }}

+ +

儲存圖片

+ +

The {{domxref("HTMLCanvasElement")}} provides a toDataURL() method, which is useful when saving images. It returns a data URI 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 96 dpi.

+ +
+
{{domxref("HTMLCanvasElement.toDataURL", "canvas.toDataURL('image/png')")}}
+
Default setting. Creates a PNG image.
+
{{domxref("HTMLCanvasElement.toDataURL", "canvas.toDataURL('image/jpeg', quality)")}}
+
Creates a JPG image. Optionally, you can provide a quality in the range from 0 to 1, with one being the best quality and with 0 almost not recognizable but small in file size.
+
+ +

Once you have generated a data URI from you canvas, you are able to use it as the source of any {{HTMLElement("image")}} or put it into a hyper link with a download attribute to save it to disc, for example.

+ +

You can also create a {{domxref("Blob")}} from the canvas.

+ +
+
{{domxref("HTMLCanvasElement.toBlob", "canvas.toBlob(callback, type, encoderOptions)")}}
+
Creates a Blob object representing the image contained in the canvas.
+
+ +

延伸閱讀

+ + + +

{{PreviousNext("Web/API/Canvas_API/Tutorial/Advanced_animations", "Web/API/Canvas_API/Tutorial/Hit_regions_and_accessibility")}}

diff --git a/files/zh-tw/web/api/canvas_api/tutorial/transformations/index.html b/files/zh-tw/web/api/canvas_api/tutorial/transformations/index.html new file mode 100644 index 0000000000..b25a2248dd --- /dev/null +++ b/files/zh-tw/web/api/canvas_api/tutorial/transformations/index.html @@ -0,0 +1,336 @@ +--- +title: 變形效果 +slug: Web/API/Canvas_API/Tutorial/Transformations +translation_of: Web/API/Canvas_API/Tutorial/Transformations +--- +
{{CanvasSidebar}} {{PreviousNext("Web/API/Canvas_API/Tutorial/Using_images", "Web/API/Canvas_API/Tutorial/Compositing")}}
+ +

畫布狀態儲存與復原

+ +

在使用變形效果等複雜繪圖方法之前,有兩個不可或缺的方法(method)必須要先了解一下:

+ +
+
save()
+
儲存現階段畫布完整狀態。
+
restore()
+
復原最近一次儲存的畫布狀態。
+
+ +

每一次呼叫save(),畫布狀態便會存進一個堆疊(stack)之中。畫布狀態包含了:

+ + + +

我們可以呼叫save()的次數不限,而每一次呼叫restore(),最近一次儲存的畫布狀態便會從堆疊中被取出,然後還原畫布到此畫布狀態。

+ +

畫布狀態儲存與復原範例

+ +

本例會畫一連串矩形圖案來說明畫布狀態堆疊是如何運作。

+ +
function draw() {
+  var ctx = document.getElementById('canvas').getContext('2d');
+
+  ctx.fillRect(0,0,150,150);   // Draw a rectangle with default settings
+  ctx.save();                  // Save the default state
+
+  ctx.fillStyle = '#09F'       // Make changes to the settings
+  ctx.fillRect(15,15,120,120); // Draw a rectangle with new settings
+
+  ctx.save();                  // Save the current state
+  ctx.fillStyle = '#FFF'       // Make changes to the settings
+  ctx.globalAlpha = 0.5;
+  ctx.fillRect(30,30,90,90);   // Draw a rectangle with new settings
+
+  ctx.restore();               // Restore previous state
+  ctx.fillRect(45,45,60,60);   // Draw a rectangle with restored settings
+
+  ctx.restore();               // Restore original state
+  ctx.fillRect(60,60,30,30);   // Draw a rectangle with restored settings
+}
+ + + +

 

+ +

* 預設用黑色填滿這個矩形

+ +

* 每種狀態可以看成是一層層堆疊的步驟紀錄

+ +

第一步:畫出黑色矩形 接著把第一個狀態儲存下來(用黑色填滿)

+ +

第二步:畫出藍色矩形 接著把第二個狀態儲存下來(用藍色填滿)

+ +

第三步:畫出半透明矩形

+ +

第四步:再畫出矩形  這時候我們取用最新儲存過的藍色(第二狀態)

+ +

第五步:再畫一個矩形 我們再取出更早之前儲存的黑色(第一狀態)

+ +

{{EmbedLiveSample("A_save_and_restore_canvas_state_example", "180", "180", "https://mdn.mozillademos.org/files/249/Canvas_savestate.png")}}

+ +

移動畫布

+ +

第一個變形效果方法是translate()。translate()是用來移動畫布,如右圖,原先畫布的原點在網格(0, 0)位置,我們可以移動畫布,使其原點移到(x, y)位置。

+ +
+
translate(x, y)
+
移動網格上的畫布,其中x代表水平距離、y代表垂直距離。
+
+ +

最好在做任何變形效果前先儲存一下畫布狀態,如此當我們需要復原先前的狀態時,只需要呼叫一下restore()即可,而且有一種情況是當我們在迴圈中移動畫布,如果不記得儲存和回復畫布狀態,繪圖區域很容易最後就超出邊界,然後出現圖案不見的狀況。

+ +

移動畫布範例

+ +

下面程式碼示範了利用translate()畫圖的好處,裡面,我們用了drawSpirograph()函數畫萬花筒類的圖案,如果沒有移動畫布原點,那麼每個圖案只會有四分之一會落在可視範圍,藉由移動畫布原點我們便可以自由變換每個圖案的位置,使圖案完整出現,而且省去手動計算調整每個圖案的座標位置。

+ +

另外一個draw()函數透過兩個for迴圈移動畫布原點、呼叫drawSpirograph()函數、復歸畫布圓點位置共九次。

+ +
function draw() {
+  var ctx = document.getElementById('canvas').getContext('2d');
+  ctx.fillRect(0,0,300,300);
+  for (var i=0;i<3;i++) {
+    for (var j=0;j<3;j++) {
+      ctx.save();
+      ctx.strokeStyle = "#9CFF00";
+      ctx.translate(50+j*100,50+i*100);
+      drawSpirograph(ctx,20*(j+2)/(j+1),-8*(i+3)/(i+1),10);
+      ctx.restore();
+    }
+  }
+}
+
+function drawSpirograph(ctx,R,r,O){
+  var x1 = R-O;
+  var y1 = 0;
+  var i  = 1;
+  ctx.beginPath();
+  ctx.moveTo(x1,y1);
+  do {
+    if (i>20000) break;
+    var x2 = (R+r)*Math.cos(i*Math.PI/72) - (r+O)*Math.cos(((R+r)/r)*(i*Math.PI/72))
+    var y2 = (R+r)*Math.sin(i*Math.PI/72) - (r+O)*Math.sin(((R+r)/r)*(i*Math.PI/72))
+    ctx.lineTo(x2,y2);
+    x1 = x2;
+    y1 = y2;
+    i++;
+  } while (x2 != R-O && y2 != 0 );
+  ctx.stroke();
+}
+
+ + + +

{{EmbedLiveSample("A_translate_example", "330", "330", "https://mdn.mozillademos.org/files/256/Canvas_translate.png")}}

+ +

旋轉

+ +

rotate()函數可以畫布原點作中心,旋轉畫布。

+ +
+
rotate(x)
+
以畫布原點為中心,順時針旋轉畫布x弧度(弧度 = Math.PI * 角度 / 180)。
+
+ +

我們可以呼叫translate()方法來移動旋轉中心(亦即畫布原點)。

+ +

旋轉範例

+ +

本範例我們呼叫rotate()方法來畫一系列環狀圖案。如果不用rotate(),同樣的效果也可以藉由個別計算x, y座標點(x = r*Math.cos(a); y = r*Math.sin(a))達成;呼叫rotate()和個別計算x, y座標點不同之處在於,個別計算x, y座標點只有旋轉圓形圓心,而圓形並沒有旋轉,呼叫rotate()則會旋轉圓形和圓心,不過因為我們的圖案是圓形,所以兩種作法產生的效果不會有差異。

+ +

我們執行了兩個迴圈來作圖,第一個迴圈決定的圓環個數和該圓環上圓環上圓點的個數的顏色,第二個迴圈決定了圓環上圓點的個數,每一次作圖前我們都儲存了原始畫布狀態,以便結束時可以復原狀態。畫布旋轉的弧度則以圓環上圓點的個數決定,像是最內圈的圓環共有六個圓點,所以每畫一個原點,畫布就旋轉60度(360度/6),第二的圓環有12個原點,所以畫布一次旋轉度數為30度(360度/12),以此類推。

+ +
function draw() {
+  var ctx = document.getElementById('canvas').getContext('2d');
+  ctx.translate(75,75);
+
+  for (var i=1;i<6;i++){ // Loop through rings (from inside to out)
+    ctx.save();
+    ctx.fillStyle = 'rgb('+(51*i)+','+(255-51*i)+',255)';
+
+    for (var j=0;j<i*6;j++){ // draw individual dots
+      ctx.rotate(Math.PI*2/(i*6));
+      ctx.beginPath();
+      ctx.arc(0,i*12.5,5,0,Math.PI*2,true);
+      ctx.fill();
+    }
+
+    ctx.restore();
+  }
+}
+
+ + + +

{{EmbedLiveSample("A_rotate_example", "180", "180", "https://mdn.mozillademos.org/files/248/Canvas_rotate.png")}}

+ +

縮放

+ +

接下來這一個變形效果為縮放圖形。

+ +
+
scale(x, y)
+
x代表縮放畫布水平網格單位x倍,y代表縮放畫布垂直網格單位y倍,輸入1.0不會造成縮放。如果輸入負值會造成座標軸鏡射,假設輸入x為-1,那麼原本畫布網格X軸上的正座標點都會變成負座標點、負座標點則變成正座標點。
+
+ +

只要利用scale(),我們可以建立著名的笛卡兒座標系;執行translate(0,canvas.height)先移動畫布原點到左下角,再執行scale(1,-1)顛倒Y軸正負值,一個笛卡兒座標系便完成了。

+ +

預設上畫布網格前進一單位等於前進一像素大小,所以縮小0.5倍,就會變成前進0.5的像素大小,亦即縮小圖像一半大小,反之,放大2倍將放大圖像2倍。

+ +

縮放範例

+ +

本程式碼範例會畫出一系列不同縮放比例的萬花筒樣式圖案。

+ +
function draw() {
+  var ctx = document.getElementById('canvas').getContext('2d');
+  ctx.strokeStyle = "#fc0";
+  ctx.lineWidth = 1.5;
+  ctx.fillRect(0,0,300,300);
+
+  // Uniform scaling
+  ctx.save()
+  ctx.translate(50,50);
+  drawSpirograph(ctx,22,6,5);
+
+  ctx.translate(100,0);
+  ctx.scale(0.75,0.75);
+  drawSpirograph(ctx,22,6,5);
+
+  ctx.translate(133.333,0);
+  ctx.scale(0.75,0.75);
+  drawSpirograph(ctx,22,6,5);
+  ctx.restore();
+
+  // Non uniform scaling (y direction)
+  ctx.strokeStyle = "#0cf";
+  ctx.save()
+  ctx.translate(50,150);
+  ctx.scale(1,0.75);
+  drawSpirograph(ctx,22,6,5);
+
+  ctx.translate(100,0);
+  ctx.scale(1,0.75);
+  drawSpirograph(ctx,22,6,5);
+
+  ctx.translate(100,0);
+  ctx.scale(1,0.75);
+  drawSpirograph(ctx,22,6,5);
+  ctx.restore();
+
+  // Non uniform scaling (x direction)
+  ctx.strokeStyle = "#cf0";
+  ctx.save()
+  ctx.translate(50,250);
+  ctx.scale(0.75,1);
+  drawSpirograph(ctx,22,6,5);
+
+  ctx.translate(133.333,0);
+  ctx.scale(0.75,1);
+  drawSpirograph(ctx,22,6,5);
+
+  ctx.translate(177.777,0);
+  ctx.scale(0.75,1);
+  drawSpirograph(ctx,22,6,5);
+  ctx.restore();
+
+}
+function drawSpirograph(ctx,R,r,O){
+  var x1 = R-O;
+  var y1 = 0;
+  var i  = 1;
+  ctx.beginPath();
+  ctx.moveTo(x1,y1);
+  do {
+    if (i>20000) break;
+    var x2 = (R+r)*Math.cos(i*Math.PI/72) - (r+O)*Math.cos(((R+r)/r)*(i*Math.PI/72))
+    var y2 = (R+r)*Math.sin(i*Math.PI/72) - (r+O)*Math.sin(((R+r)/r)*(i*Math.PI/72))
+    ctx.lineTo(x2,y2);
+    x1 = x2;
+    y1 = y2;
+    i++;
+  } while (x2 != R-O && y2 != 0 );
+  ctx.stroke();
+}
+
+ + + +

第一排第一個黃色圖案是沒有縮放的圖案,然後往右到了第二個圖案,我們程式碼中輸入了 (0.75, 0.75)的縮放倍率,到了第三個圖案,我們還是輸入了 (0.75, 0.75)的縮放倍率,而基於之前有縮小過一次,所以第三個圖案相對於第一個沒有縮放的圖案是0.75 × 0.75 = 0.5625倍。

+ +

第二排藍色圖案我們只改變Y軸的縮放倍率,X軸維持不變,因而產生一個比一個更扁的橢圓圖形。同理,第三排綠色圖案改變X軸的縮放倍率,Y軸維持不變。

+ +

{{EmbedLiveSample("A_scale_example", "330", "330", "https://mdn.mozillademos.org/files/250/Canvas_scale.png")}}

+ +

變形

+ +

最後一個方法是設定變形矩陣,藉由改變變形矩陣,我們因此可以營造各種變形效果;其實先前所提到的rotate, translate, scale都是在設定變形矩陣,而這邊的這個方法就是直接去改變變形矩陣。

+ +
+
transform(m11, m12, m21, m22, dx, dy)
+
呼叫Transform會拿目前的變形矩陣乘以下列矩陣:
+
+
+
m11 	m21 	dx
+m12 	m22 	dy
+0 	0 	1
+
+
+
+ +
+
運算後的新矩陣將取代目前的變形矩陣。
+
其中m11代表水平縮放圖像,m12代表水平偏移圖像,m21代表垂直偏移圖像,m22代表垂直縮放圖像,dx代表水平移動圖像,dy代表垂直移動圖像。
+
如果輸入Infinity 值,不會引起例外錯誤,矩陣值會依照輸入設成無限。
+
setTransform(m11, m12, m21, m22, dx, dy)
+
復原目前矩陣為恆等矩陣(Identiy matrix,也就是預設矩陣),然後再以輸入參數呼叫transform()。
+
+ +

transform / setTransform範例

+ +
function draw() {
+  var ctx = document.getElementById('canvas').getContext('2d');
+
+  var sin = Math.sin(Math.PI/6);
+  var cos = Math.cos(Math.PI/6);
+  ctx.translate(100, 100);
+  var c = 0;
+  for (var i=0; i <= 12; i++) {
+    c = Math.floor(255 / 12 * i);
+    ctx.fillStyle = "rgb(" + c + "," + c + "," + c + ")";
+    ctx.fillRect(0, 0, 100, 10);
+    ctx.transform(cos, sin, -sin, cos, 0, 0);
+  }
+
+  ctx.setTransform(-1, 0, 0, 1, 100, 100);
+  ctx.fillStyle = "rgba(255, 128, 255, 0.5)";
+  ctx.fillRect(0, 50, 100, 100);
+}
+
+ + + +

{{EmbedLiveSample("transform_.2F_setTransform_examples", "230", "280", "https://mdn.mozillademos.org/files/255/Canvas_transform.png")}}

+ +

{{PreviousNext("Web/Guide/HTML/Canvas_tutorial/Applying_styles_and_colors", "Web/Guide/HTML/Canvas_tutorial/Compositing")}}

diff --git a/files/zh-tw/web/api/canvas_api/tutorial/using_images/index.html b/files/zh-tw/web/api/canvas_api/tutorial/using_images/index.html new file mode 100644 index 0000000000..7bb6bf791f --- /dev/null +++ b/files/zh-tw/web/api/canvas_api/tutorial/using_images/index.html @@ -0,0 +1,342 @@ +--- +title: 使用影像 +slug: Web/API/Canvas_API/Tutorial/Using_images +translation_of: Web/API/Canvas_API/Tutorial/Using_images +--- +
{{CanvasSidebar}} {{PreviousNext("Web/API/Canvas_API/Tutorial/Drawing_text", "Web/API/Canvas_API/Tutorial/Transformations" )}}
+ +

使用影像是{{HTMLElement("canvas")}}另一個有趣的功能,這個功能可以用來動態組合圖片或作為背景等等。任何瀏覽器支援的外部圖片格式都可以使用,例如PNG, GIF, JPEG,甚至也可以利用同一份頁面上其他畫布元素產生的影像.

+ +

載入影像到畫布中基本上需要兩個步驟:

+ +
    +
  1. +

    取得{{domxref("HTMLImageElement")}}物件或其他畫布元素的參照(reference)作為來源,透過單純提供URL或圖片位置的方式是行不通的.

    +
  2. +
  3. +

    drawImage()函數在畫布上畫影像.

    +
  4. +
+ +

接下來便來看看要怎麼做.

+ +

取得影像

+ +

畫布API能接受以下資料型態作為影像來源:

+ +
+
{{domxref("HTMLImageElement")}}
+
+

Image()建構成的影像或是{{HTMLElement("img")}}元素.

+
+
{{domxref("HTMLVideoElement")}}
+
+

{{domxref("HTMLVideoElement")}}元素作影像來源,抓取影片目前的影像畫格當作影像使用.

+
+
{{domxref("HTMLCanvasElement")}}
+
+

用另一個{{domxref("HTMLCanvasElement")}}元素當影像來源.

+
+
{{domxref("ImageBitmap")}}
+
+

可以被快速渲染的點陣圖(bitmap),點陣圖能由上述所有來源產生.

+
+
+ +

這些來源統一參照 CanvasImageSource型態.

+ +

有好幾種方法能夠取得影像用於畫布.

+ +

 

+ +

使用同一份網頁上的影像

+ +

我們能透過下面幾個方法取得影像:

+ + + +

使用來自其他網域的影像

+ +

Using the crossOrigin attribute on an 透過{{HTMLElement("HTMLImageElement")}}的crossOrigin屬性, 我們可以要求從另一個網域載入影像來使用,若是寄存網域(thehosting domain)准許跨網路存取該影像,那麼我們便可以使用它而不用污染(taint)我們的畫布,反之,使用該影像會污染畫布(taint the canvas)。

+ +

使用其他畫布元素

+ +

如同取得其他影像,我們一樣能用{{domxref("document.getElementsByTagName()")}}或{{domxref("document.getElementById()")}}方法取得其他畫布元素,但是在使用之前請記得來源畫布上已經有繪上圖了。

+ +

使用其他畫布元素作為影像來源有很多有用的應用用途,其中之一便是建立第二個小畫布作為另一個大畫布的縮小影像.

+ +

創造全新的影像

+ +

產生新的{{domxref("HTMLImageElement")}}物件也能當作影像來源,這邊,我們可以用Image()來建構一個新影像元素:

+ +
var img = new Image();   // Create new img element
+img.src = 'myImage.png'; // Set source path
+
+ +

上述程式碼執行後會載入影像.

+ +

在影像載入完成前呼叫drawImage()不會有任何效果,甚至某些瀏覽器還會拋出例外狀況,所以應該要透過利用載入事件來避免這類問題:

+ +
var img = new Image();   // Create new img element
+img.addEventListener("load", function() {
+  // execute drawImage statements here
+}, false);
+img.src = 'myImage.png'; // Set source path
+
+ +

若是只要載入一份影像,可以用上面的方法,不過當需要載入、追蹤多個影像時,我們就需要更好的方法了,雖然管理多個影像載入已經超出本教學的範疇,然而如果有興趣的話,可以參考JavaScript Image Preloader這份文件.

+ +

以data:URL嵌入影像

+ +

另一個載入影像的方法是利用data: url,透過data URL可以直接將影像定義成Base64編碼的字串,然後嵌入程式碼之中.

+ +
var img_src = 'data:image/gif;base64,R0lGODlhCwALAIAAAAAA3pn/ZiH5BAEAAAEALAAAAAALAAsAAAIUhA+hkcuO4lmNVindo7qyrIXiGBYAOw==';
+
+ +

data URL的好處之一是立即產生影像而不用再和伺服器連線,另一個好處是這樣便能夠將影像包入你的CSS, JavaScript, HTML之中,讓影像更具可攜性.

+ +

壞處則是影像將不會被快取起來,而且對大影像來說編碼後的URL會很長.

+ +

Using frames from a video

+ +

我們還能夠使用{{HTMLElement("video")}}元素中的影片的影片畫格(縱使影片為隱藏),例如,現在我們有一個ID為”myvideo” 的{{HTMLElement("video")}}元素:

+ +
function getMyVideo() {
+  var canvas = document.getElementById('canvas');
+  if (canvas.getContext) {
+    var ctx = canvas.getContext('2d');
+
+    return document.getElementById('myvideo');
+  }
+}
+
+ +

上面的方法會回傳一個{{domxref("HTMLVideoElement")}}的影像物件,如前所述,這個物件可以被視為CanvasImageSource類別的物件來使用。
+ 關於如何利用<video>元素於畫布上的進階說明,可以參考html5Doctor的“video + canvas = magic”一文.

+ +

影像繪圖

+ +

一旦我們取得來源影像物件的參照(reference),便可以用drawImage()方法將影像渲染到畫布上,drawImage()方法是一個多載(overload)方法,有數個型態,待會我們會看到這項特性,現在我們先來看drawImage()最基本的型態:

+ +
+
drawImage(image, x, y)
+
從座標點(x, y)開始畫上image參數指定的來源影像(CanvasImageSource).
+
+ +

範例: 一條簡單的線段影像

+ +

這個範例會使用外部影像作為一個小型線圖的背景。利用預先劃好的圖作為背景的話就不用再靠程式來產生背景,如此一來可以顯著地減少程式碼。下面藉由影像物件的load事件處理器來處理繪圖作業,其中drawImage()方法把背景圖片放置在畫布左上角,座標點(0, 0)位置.

+ + + +
function draw() {
+  var ctx = document.getElementById('canvas').getContext('2d');
+  var img = new Image();
+  img.onload = function(){
+    ctx.drawImage(img,0,0);
+    ctx.beginPath();
+    ctx.moveTo(30,96);
+    ctx.lineTo(70,66);
+    ctx.lineTo(103,76);
+    ctx.lineTo(170,15);
+    ctx.stroke();
+  };
+  img.src = 'https://mdn.mozillademos.org/files/5395/backdrop.png';
+}
+ +

結果如下:

+ +

{{EmbedLiveSample("Example.3A_A_simple_line_graph", 220, 160, "https://mdn.mozillademos.org/files/206/Canvas_backdrop.png")}}

+ +

縮放

+ +

drawImage()的第二個型態增加了兩個新參數,讓我們在畫布上放置影像的同時並縮放影像.

+ +
+
drawImage(image, x, y, width, height)
+
當放置影像於畫布上時,會按照參數width(寬)、height(高)來縮放影像.
+
+ +

範例: 排列影像

+ +

本例我們會取一張影像作為桌布,然後透過簡單的迴圈來重複縮放、貼上影像於畫布上。在程式碼中,第一個迴圈走一遍每一列,第二個迴圈走一遍每一行,影像則縮小成原始影像的三分之一,50 x 38像素.

+ +
+

Note: 過度縮放影像可能會造成影像模糊或產生顆粒感,所以如果影像中有文字需要閱讀,最好不要縮放影像.

+
+ + + +
function draw() {
+  var ctx = document.getElementById('canvas').getContext('2d');
+  var img = new Image();
+  img.onload = function(){
+    for (var i=0;i<4;i++){
+      for (var j=0;j<3;j++){
+        ctx.drawImage(img,j*50,i*38,50,38);
+      }
+    }
+  };
+  img.src = 'https://mdn.mozillademos.org/files/5397/rhino.jpg';
+}
+ +

結果如下:

+ +

{{EmbedLiveSample("Example.3A_Tiling_an_image", 160, 160, "https://mdn.mozillademos.org/files/251/Canvas_scale_image.png")}}

+ +

切割影像

+ +

drawImage()第三個型態接受9個參數,其中8個讓我們從原始影像中切出一部分影像、縮放並畫到畫布上.

+ +
+
drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)
+
image參數是來源影像物件,(sx, sy)代表在來源影像中以(sx, sy)座標點作為切割的起始點,sWidth和sHeight代表切割寬和高,(dx, dy)代表放到畫布上的座標點,dWidth和dHeight代表縮放影像至指定的寬和高.
+
+ +

請參照右圖,前四個參數定義了在來源影像上切割的起始點和切割大小,後四個參數定義了畫到畫布上的位置和影像大小.

+ +

切割是一個很有用的工具,我們可以把所有影像放到一張影像上,然後利用切割來組成最終完整的影像,比如說,我們可以把所有需要用來組成一張圖表的文字放到一張PNG圖檔內,之後只需要單純地再依據資料來縮放圖表,另外,我們也不用多次載入多張影像,這樣對提升載入影像效能頗有幫助.

+ +

 

+ +

 

+ +

範例: 畫一個有畫框的影像

+ +

本例用和前一個範例一樣的犀牛圖,然後切出犀牛頭部影像部分再放入一個影像畫框,這個影像畫框是一個有陰影的24位元PNG圖檔,因為24位元PNG影像具備完整的8位元不透明色版(alpha channel),所以不像GIF影像和8位元PNG影像,它能夠放任何背景之上而無須擔心產生消光色(matte color).

+ +
<html>
+ <body onload="draw();">
+   <canvas id="canvas" width="150" height="150"></canvas>
+   <div style="display:none;">
+     <img id="source" src="https://mdn.mozillademos.org/files/5397/rhino.jpg" width="300" height="227">
+     <img id="frame" src="https://mdn.mozillademos.org/files/242/Canvas_picture_frame.png" width="132" height="150">
+   </div>
+ </body>
+</html>
+
+ +
function draw() {
+  var canvas = document.getElementById('canvas');
+  var ctx = canvas.getContext('2d');
+
+  // Draw slice
+  ctx.drawImage(document.getElementById('source'),
+                33, 71, 104, 124, 21, 20, 87, 104);
+
+  // Draw frame
+  ctx.drawImage(document.getElementById('frame'),0,0);
+}
+ +

這次我們不產生新的{{domxref("HTMLImageElement")}}物件,改採用直接把影像包入HTML的{{HTMLElement("img")}}標籤,然後再取得影像元素,其中HTML上的影像已經透過設定CSS屬性{{cssxref("display")}}為none來隱藏起來了.

+ +

{{EmbedLiveSample("Example.3A_Framing_an_image", 160, 160, "https://mdn.mozillademos.org/files/226/Canvas_drawimage2.jpg")}}

+ +

程式碼相當簡單,每個{{HTMLElement("img")}}有自己的ID屬性,這樣便可以利用{{domxref("document.getElementById()")}}輕易取得,之後再簡單地用drawImage()方法切割犀牛影像然後縮放並放到畫布上,最後第二個drawImage()再把畫框放到上面.

+ +

畫廊範例

+ +

在本章的最後一個範例,我們將建造一個小畫廊。當網頁載入完成時,我們會為每一張影像產生一個{{HTMLElement("canvas")}}元素,並且加上畫框.

+ +

本範例中,每一張影像的寬高是固定的,畫框也是一樣,你可以嘗試看看改進程式碼,依據影像的寬高來設定畫框,使畫框能剛剛好框住影像.

+ +

從下方的程式碼範例可以很清楚看到,我們為{{domxref("document.images")}}容器內的影像,一張一張地新建畫布,其中,對於不熟悉文件物件模型 (DOM)的人來說,大慨比較值得注意之處在於使用到{{domxref("Node.insertBefore")}} 方法;insertBefore()是影像元素的父節點(亦即<td>元素)的一個方法,這個方法會把新畫布元素插入於影像元素之前.

+ +
<html>
+ <body onload="draw();">
+     <table>
+      <tr>
+        <td><img src="https://mdn.mozillademos.org/files/5399/gallery_1.jpg"></td>
+        <td><img src="https://mdn.mozillademos.org/files/5401/gallery_2.jpg"></td>
+        <td><img src="https://mdn.mozillademos.org/files/5403/gallery_3.jpg"></td>
+        <td><img src="https://mdn.mozillademos.org/files/5405/gallery_4.jpg"></td>
+      </tr>
+      <tr>
+        <td><img src="https://mdn.mozillademos.org/files/5407/gallery_5.jpg"></td>
+        <td><img src="https://mdn.mozillademos.org/files/5409/gallery_6.jpg"></td>
+        <td><img src="https://mdn.mozillademos.org/files/5411/gallery_7.jpg"></td>
+        <td><img src="https://mdn.mozillademos.org/files/5413/gallery_8.jpg"></td>
+      </tr>
+     </table>
+     <img id="frame" src="https://mdn.mozillademos.org/files/242/Canvas_picture_frame.png" width="132" height="150">
+ </body>
+</html>
+
+ +

這些是一些設定樣式的CSS:

+ +
body {
+  background: 0 -100px repeat-x url(https://mdn.mozillademos.org/files/5415/bg_gallery.png) #4F191A;
+  margin: 10px;
+}
+
+img {
+  display: none;
+}
+
+table {
+  margin: 0 auto;
+}
+
+td {
+  padding: 15px;
+}
+
+ +

綜合起來這就是建造出我們小畫廊的程式碼:

+ +
function draw() {
+
+  // Loop through all images
+  for (var i=0;i<document.images.length;i++){
+
+    // Don't add a canvas for the frame image
+    if (document.images[i].getAttribute('id')!='frame'){
+
+      // Create canvas element
+      canvas = document.createElement('canvas');
+      canvas.setAttribute('width',132);
+      canvas.setAttribute('height',150);
+
+      // Insert before the image
+      document.images[i].parentNode.insertBefore(canvas,document.images[i]);
+
+      ctx = canvas.getContext('2d');
+
+      // Draw image to canvas
+      ctx.drawImage(document.images[i],15,20);
+
+      // Add frame
+      ctx.drawImage(document.getElementById('frame'),0,0);
+    }
+  }
+}
+ +

{{EmbedLiveSample("Art_gallery_example", 725, 400, "https://mdn.mozillademos.org/files/205/Canvas_art_gallery.jpg")}}

+ +

控制影像縮放行為

+ +

如前所述,縮放影像會導致影像模糊化或是顆粒化,你可以嘗試透過繪圖環境的imageSmoothingEnabled屬性來控制影像平滑演算法的使用,預設上這個屬性的值為true,也就是說當縮放時,影像會經過平滑處理。如果要關掉這個功能,你可以這麼做:

+ +
ctx.mozImageSmoothingEnabled = false;
+
+ +

{{PreviousNext("Web/Guide/HTML/Canvas_tutorial/Drawing_shapes", "Web/Guide/HTML/Canvas_tutorial/Applying_styles_and_colors")}}

diff --git a/files/zh-tw/web/api/canvasrenderingcontext2d/clearrect/index.html b/files/zh-tw/web/api/canvasrenderingcontext2d/clearrect/index.html new file mode 100644 index 0000000000..e5792ffade --- /dev/null +++ b/files/zh-tw/web/api/canvasrenderingcontext2d/clearrect/index.html @@ -0,0 +1,189 @@ +--- +title: CanvasRenderingContext2D.clearRect() +slug: Web/API/CanvasRenderingContext2D/clearRect +translation_of: Web/API/CanvasRenderingContext2D/clearRect +--- +
{{APIRef}}
+ +

Canvas 2D API 的 CanvasRenderingContext2D.clearRect() 方法可以設定指定矩形(經由坐標 (x, y) 及大小 (width, height))範圍內的所有像素為透明,清除所有先前繪製的內容。

+ +

語法

+ +
void ctx.clearRect(x, y, width, height);
+
+ +

參數

+ +
+
x
+
The x axis of the coordinate for the rectangle starting point.
+
y
+
The y axis of the coordinate for the rectangle starting point.
+
width
+
The rectangle's width.
+
height
+
The rectangle's height.
+
+ +

Usage notes

+ +

A common problem with clearRect is that it may appear it does not work when not using paths properly. Don't forget to call {{domxref("CanvasRenderingContext2D.beginPath", "beginPath()")}} before starting to draw the new frame after calling clearRect.

+ +

範例

+ +

Using the clearRect method

+ +

This is just a simple code snippet which uses the clearRect method.

+ +

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

Edit the code below and see your changes update live in the 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) }}

+ +

規範

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "scripting.html#dom-context-2d-clearrect", "CanvasRenderingContext2D.clearRect")}}{{Spec2('HTML WHATWG')}} 
+ +

瀏覽器相容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
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}}{{CompatVersionUnknown}}
+
+ +

參見

+ + diff --git a/files/zh-tw/web/api/canvasrenderingcontext2d/index.html b/files/zh-tw/web/api/canvasrenderingcontext2d/index.html new file mode 100644 index 0000000000..31aa34ecdf --- /dev/null +++ b/files/zh-tw/web/api/canvasrenderingcontext2d/index.html @@ -0,0 +1,459 @@ +--- +title: CanvasRenderingContext2D +slug: Web/API/CanvasRenderingContext2D +translation_of: Web/API/CanvasRenderingContext2D +--- +
{{APIRef}}
+ +
CanvasRenderingContext2D 介面被使用於繪製矩形、文字、影像以及其它基於 canvas 元素的物件。此介面提供了繪製 {{ HTMLElement("canvas") }} 元素外觀的 2D 渲染環境。
+ +
 
+ +

要取得此實作此介面的實體物件,可以於一個 <canvas> 元素上以 "2d" 為參數呼叫 {{domxref("HTMLCanvasElement.getContext()", "getContext()")}} 方法:

+ +
var canvas = document.getElementById('mycanvas'); // in your HTML this element appears as <canvas id="mycanvas"></canvas>
+var ctx = canvas.getContext('2d');
+
+ +

只要你有了 canvas 的 2D 繪製背景物件,你就可以在其中繪圖。 舉個例子:

+ +
ctx.fillStyle = "rgb(200,0,0)"; // sets the color to fill in the rectangle with
+ctx.fillRect(10, 10, 55, 50);   // draws the rectangle at position 10, 10 with a width of 55 and a height of 50
+
+ +

canvas 教學有更多資訊、範例,以及資源。

+ +

繪製矩形

+ +

有三個函式可以馬上在點陣圖上畫出長方形。

+ +
+
{{domxref("CanvasRenderingContext2D.clearRect()")}}
+
Sets all pixels in the rectangle defined by starting point (x, y) and size (width, height) to transparent black, erasing any previously drawn content.
+
{{domxref("CanvasRenderingContext2D.fillRect()")}}
+
Draws a filled rectangle at (x, y) position whose size is determined by width and height.
+
{{domxref("CanvasRenderingContext2D.strokeRect()")}}
+
Paints a rectangle which has a starting point at (x, y) and has a w width and an h height onto the canvas, using the current stroke style.
+
+ +

繪製文字

+ +

The following methods are provided for drawing text. See also the {{domxref("TextMetrics")}} object for text properties.

+ +
+
{{domxref("CanvasRenderingContext2D.fillText()")}}
+
Draws (fills) a given text at the given (x,y) position.
+
{{domxref("CanvasRenderingContext2D.strokeText()")}}
+
Draws (strokes) a given text at the given (x, y) position.
+
{{domxref("CanvasRenderingContext2D.measureText()")}}
+
Returns a {{domxref("TextMetrics")}} object.
+
+ +

線條樣式

+ +

The following methods and properties control how lines are drawn.

+ +
+
{{domxref("CanvasRenderingContext2D.lineWidth")}}
+
Width of lines. Default 1.0
+
{{domxref("CanvasRenderingContext2D.lineCap")}}
+
Type of endings on the end of lines. Possible values: butt (default), round, square.
+
{{domxref("CanvasRenderingContext2D.lineJoin")}}
+
Defines the type of corners where two lines meet. Possible values: round, bevel, miter (default).
+
{{domxref("CanvasRenderingContext2D.miterLimit")}}
+
Miter limit ratio. Default 10.
+
{{domxref("CanvasRenderingContext2D.getLineDash()")}}
+
Returns the current line dash pattern array containing an even number of non-negative numbers.
+
{{domxref("CanvasRenderingContext2D.setLineDash()")}}
+
Sets the current line dash pattern.
+
{{domxref("CanvasRenderingContext2D.lineDashOffset")}}
+
Specifies where to start a dash array on a line.
+
+ +

文字樣式

+ +

The following properties control how text is laid out.

+ +
+
{{domxref("CanvasRenderingContext2D.font")}}
+
Font setting. Default value 10px sans-serif.
+
{{domxref("CanvasRenderingContext2D.textAlign")}}
+
Text alignment setting. Possible values: start (default), end, left, right or center.
+
{{domxref("CanvasRenderingContext2D.textBaseline")}}
+
Baseline alignment setting. Possible values: top, hanging, middle, alphabetic (default), ideographic, bottom.
+
{{domxref("CanvasRenderingContext2D.direction")}}
+
Directionality. Possible values: ltr, rtl, inherit (default).
+
+ +

填充及邊線樣式

+ +

Fill styling is used for colors and styles inside shapes and stroke styling is used for the lines around shapes.

+ +
+
{{domxref("CanvasRenderingContext2D.fillStyle")}}
+
Color or style to use inside shapes. Default #000 (black).
+
{{domxref("CanvasRenderingContext2D.strokeStyle")}}
+
Color or style to use for the lines around shapes. Default #000 (black).
+
+ +

漸層填色及圖案填充

+ +
+
{{domxref("CanvasRenderingContext2D.createLinearGradient()")}}
+
Creates a linear gradient along the line given by the coordinates represented by the parameters.
+
{{domxref("CanvasRenderingContext2D.createRadialGradient()")}}
+
Creates a radial gradient given by the coordinates of the two circles represented by the parameters.
+
{{domxref("CanvasRenderingContext2D.createPattern()")}}
+
Creates a pattern using the specified image (a {{domxref("CanvasImageSource")}}). It repeats the source in the directions specified by the repetition argument. This method returns a {{domxref("CanvasPattern")}}.
+
+ +

陰影

+ +
+
{{domxref("CanvasRenderingContext2D.shadowBlur")}}
+
Specifies the blurring effect. Default 0
+
{{domxref("CanvasRenderingContext2D.shadowColor")}}
+
Color of the shadow. Default fully-transparent black.
+
{{domxref("CanvasRenderingContext2D.shadowOffsetX")}}
+
Horizontal distance the shadow will be offset. Default 0.
+
{{domxref("CanvasRenderingContext2D.shadowOffsetY")}}
+
Vertical distance the shadow will be offset. Default 0.
+
+ +

路徑

+ +

The following methods can be used to manipulate paths of objects.

+ +
+
{{domxref("CanvasRenderingContext2D.beginPath()")}}
+
Starts a new path by emptying the list of sub-paths. Call this method when you want to create a new path.
+
{{domxref("CanvasRenderingContext2D.closePath()")}}
+
Causes the point of the pen to move back to the start of the current sub-path. It tries to draw a straight line from the current point to the start. If the shape has already been closed or has only one point, this function does nothing.
+
{{domxref("CanvasRenderingContext2D.moveTo()")}}
+
Moves the starting point of a new sub-path to the (x, y) coordinates.
+
{{domxref("CanvasRenderingContext2D.lineTo()")}}
+
Connects the last point in the subpath to the x, y coordinates with a straight line.
+
{{domxref("CanvasRenderingContext2D.bezierCurveTo()")}}
+
Adds a cubic Bézier curve to the path. It requires three points. The first two points are control points and the third one is the end point. The starting point is the last point in the current path, which can be changed using moveTo() before creating the Bézier curve.
+
{{domxref("CanvasRenderingContext2D.quadraticCurveTo()")}}
+
Adds a quadratic Bézier curve to the current path.
+
{{domxref("CanvasRenderingContext2D.arc()")}}
+
Adds an arc to the path which is centered at (x, y) position with radius r starting at startAngle and ending at endAngle going in the given direction by anticlockwise (defaulting to clockwise).
+
{{domxref("CanvasRenderingContext2D.arcTo()")}}
+
Adds an arc to the path with the given control points and radius, connected to the previous point by a straight line.
+
{{domxref("CanvasRenderingContext2D.ellipse()")}} {{experimental_inline}}
+
Adds an ellipse to the path which is centered at (x, y) position with the radii radiusX and radiusY starting at startAngle and ending at endAngle going in the given direction by anticlockwise (defaulting to clockwise).
+
{{domxref("CanvasRenderingContext2D.rect()")}}
+
Creates a path for a rectangle at position (x, y) with a size that is determined by width and height.
+
+ +

繪製路徑

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

變形

+ +

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

合成

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

繪製圖形

+ +
+
{{domxref("CanvasRenderingContext2D.drawImage()")}}
+
Draws the specified image. This method is available in multiple formats, providing a great deal of flexibility in its use.
+
+ +

像素控制

+ +

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

圖像平滑

+ +
+
{{domxref("CanvasRenderingContext2D.imageSmoothingEnabled")}} {{experimental_inline}}
+
Image smoothing mode; if disabled, images will not be smoothed if scaled.
+
+ +

canvas 狀態

+ +

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

點擊區域

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

非標準 API

+ + + +

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 引擎專屬

+ +
+
{{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 引擎專屬

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

規範

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "scripting.html#2dcontext:canvasrenderingcontext2d", "CanvasRenderingContext2D")}}{{Spec2('HTML WHATWG')}} 
+ +

瀏覽器相容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("1")}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.8")}}{{CompatIE("9")}}{{CompatOpera("9")}}{{CompatSafari("2")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

相容性註記

+ + + +

參見

+ + + +
+ + +
 
+ +
 
+
+ +
+ + +
 
+ +
 
+
diff --git a/files/zh-tw/web/api/channel_messaging_api/index.html b/files/zh-tw/web/api/channel_messaging_api/index.html new file mode 100644 index 0000000000..1cf9d98692 --- /dev/null +++ b/files/zh-tw/web/api/channel_messaging_api/index.html @@ -0,0 +1,158 @@ +--- +title: Channel Messaging API +slug: Web/API/Channel_Messaging_API +translation_of: Web/API/Channel_Messaging_API +--- +

Channel Messaging API 讓同屬一份文件不同瀏覽環境的兩份程式腳本 (如兩個 IFrame、或主頁面和 IFrame、文件和 {{domxref("SharedWorker")}}、或兩個 worker),也能夠經由雙向 channel (通道) 兩端的 port (連接阜) 直接傳遞訊息互相溝通。

+ +

{{AvailableInWorkers}}

+ +

Channel 訊息概念與使用情境

+ +

{{domxref("MessageChannel.MessageChannel", "MessageChannel()")}} 建構子產生 channel, 一但生成了,便可以存取 channel 兩端的 port: {{domxref("MessageChannel.port1")}} 和 {{domxref("MessageChannel.port2")}},這兩個屬性會回傳 domxref("MessagePort")}} objects.)。建立 channel 的 app 使用 port1,另一端用 port2,利用 {{domxref("window.postMessage")}} 方法帶入參數,向 port2 傳送訊息以及移轉物件 (這裡也就是只 port)。

+ +

一但可移轉物件被移轉後,前任擁有者便失去所有權,例如當 port 移轉出去後,原本持有該 port 的環境便不能再使用之。目前可移轉物件只有 {{domxref("ArrayBuffer")}} 以及 {{domxref("MessagePort")}}。

+ +

另一端的瀏覽環境則藉由 {{domxref("MessagePort.onmessage")}} 監聽訊息、從訊息事件物件的 data 屬性擷取訊息資料,然後再呼叫 {{domxref("MessagePort.postMessage")}} 回傳訊息。

+ +

如果想關閉訊息 channel,則呼叫 {{domxref("MessagePort.close")}}。

+ +

更多 API 使用細節請見 Using channel messaging

+ +

Channel 訊息介面

+ +
+
{{domxref("MessageChannel")}}
+
生成一個新的 message channel。
+
{{domxref("MessagePort")}}
+
控制 port,用來傳送和監聽訊息。
+
{{domxref("PortCollection")}}
+
MessagePorts 陣列,實驗性質方案;用來同時廣播到多個訊息 port。
+
+ +

範例

+ + + +

標準規範

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#toc-comms')}}{{Spec2('HTML WHATWG')}}Channel messaging defined in section 9.5. No difference to the the HTML5 Web Messaging spec.
{{SpecName('HTML5 Web Messaging', '#channel-messaging')}}{{Spec2('HTML5 Web Messaging')}}W3C version of the spec.
+ +

瀏覽器相容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support4{{CompatGeckoDesktop(41)}}10.010.65
PortCollection{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
Available in workers{{CompatVersionUnknown}}{{CompatGeckoDesktop(41)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome MobileFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support4.44{{CompatGeckoMobile(41)}}{{CompatNo}}10.011.55.1
PortCollection{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
Available in workers{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile(41)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

延伸閱讀

+ + diff --git a/files/zh-tw/web/api/characterdata/index.html b/files/zh-tw/web/api/characterdata/index.html new file mode 100644 index 0000000000..5e39a14822 --- /dev/null +++ b/files/zh-tw/web/api/characterdata/index.html @@ -0,0 +1,156 @@ +--- +title: CharacterData +slug: Web/API/CharacterData +translation_of: Web/API/CharacterData +--- +

{{APIRef("DOM")}}

+ +

CharacterData 介面表示了含有字元的 {{domxref("Node")}} 物件。CharacterData 為抽象介面,代表不會有型別為 CharacterData 的物件。物件是由其子介面,如 {{domxref("Text")}}、{{domxref("Comment")}} 或 {{domxref("ProcessingInstruction")}} 等非抽象介面來實作。

+ +

{{InheritanceDiagram}}

+ +

屬性

+ +

Inherits properties from its parent, {{domxref("Node")}}, and implements the {{domxref("ChildNode")}} and {{domxref("NonDocumentTypeChildNode")}} interface.

+ +
+
{{domxref("CharacterData.data")}}
+
Is a {{domxref("DOMString")}} representing the textual data contained in this object.
+
{{domxref("CharacterData.length")}} {{readonlyInline}}
+
Returns an unsigned long representing the size of the string contained in 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.
+
+ +

方法

+ +

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

規範

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

瀏覽器相容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1.0{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.0")}}6{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Implements {{domxref("ChildNode")}} interface.{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("25.0")}} [1]{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Implements {{domxref("ChildNode")}} interface.{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("25.0")}} [1]{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
+
+ +

[1] Two properties, nextElementSibling and previousElementSibling, have been moved to the {{domxref("NonDocumentTypeChildNode")}} interface, also implemented by CharacterData.

+ +

參見

+ + diff --git a/files/zh-tw/web/api/childnode/index.html b/files/zh-tw/web/api/childnode/index.html new file mode 100644 index 0000000000..1d7d3f753b --- /dev/null +++ b/files/zh-tw/web/api/childnode/index.html @@ -0,0 +1,182 @@ +--- +title: ChildNode +slug: Web/API/ChildNode +translation_of: Web/API/ChildNode +--- +
{{APIRef("DOM")}}
+ +

childNodes 介面定義了可以擁有父節點之 {{domxref("Node")}} 物件的方法。

+ +

childNodes 是一個原始的介面,且不能以此建立物件實體。{{domxref("Element")}}、{{domxref("DocumentType")}} 及 {{domxref("CharacterData")}} 物件皆實作了 childNodes

+ +

屬性

+ +

沒有繼承或自有的屬性。

+ +

方法

+ +

沒有繼承的方法。

+ +
+
{{domxref("childNodes.remove()")}} {{experimental_inline}}
+
Removes this childNodes from the children list of its parent.
+
{{domxref("childNodes.before()")}} {{experimental_inline}}
+
Inserts a set of {{domxref("Node")}} or {{domxref("DOMString")}} objects in the children list of this childNodes's parent, just before this childNodes. {{domxref("DOMString")}} objects are inserted as equivalent {{domxref("Text")}} nodes.
+
{{domxref("childNodes.after()")}} {{experimental_inline}}
+
Inserts a set of {{domxref("Node")}} or {{domxref("DOMString")}} objects in the children list of this childNodes's parent, just after this childNodes. {{domxref("DOMString")}} objects are inserted as equivalent {{domxref("Text")}} nodes.
+
{{domxref("childNodes.replaceWith()")}} {{experimental_inline}}
+
Replaces this childNodes 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.
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#interface-childnode', 'childNodes')}}{{Spec2('DOM WHATWG')}}Split the ElementTraversal interface in {{domxref("ParentNode")}} and childNodes. 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

+ +

瀏覽器相容性

+ +

{{ CompatibilityTable }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support (on {{domxref("Element")}}){{CompatChrome(1.0)}}{{CompatVersionUnknown}}{{CompatGeckoDesktop(23)}}9.010.04.0
Support on {{domxref("DocumentType")}} and {{domxref("CharacterData")}} {{experimental_inline}}{{CompatChrome(23.0)}}{{CompatNo}}{{CompatGeckoDesktop(23)}}{{CompatNo}}16.0{{CompatNo}}
remove(){{experimental_inline}}{{CompatChrome(29.0)}}{{CompatVersionUnknown}}{{CompatGeckoDesktop(23)}}{{CompatNo}}16.0{{CompatNo}}
before(), after(), and replaceWith() {{experimental_inline}}{{CompatChrome(54.0)}}{{CompatNo}}{{CompatGeckoDesktop(49)}}{{CompatNo}}{{CompatOpera(39)}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support (on {{domxref("Element")}}){{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile(23)}}{{CompatVersionUnknown}}10.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Support on {{domxref("DocumentType")}} and {{domxref("CharacterData")}} {{experimental_inline}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatGeckoMobile(23)}}{{CompatNo}}16.0{{CompatNo}}{{CompatVersionUnknown}}
remove(){{experimental_inline}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile(23)}}{{CompatNo}}16.0{{CompatNo}}{{CompatVersionUnknown}}
before(), after(), and replaceWith() {{experimental_inline}}{{CompatNo}}{{CompatChrome(54.0)}}{{CompatNo}}{{CompatGeckoMobile(49)}}{{CompatNo}}{{CompatOperaMobile(39)}}{{CompatNo}}{{CompatChrome(54.0)}}
+
+ +

參見

+ + diff --git a/files/zh-tw/web/api/clients/index.html b/files/zh-tw/web/api/clients/index.html new file mode 100644 index 0000000000..000e36a804 --- /dev/null +++ b/files/zh-tw/web/api/clients/index.html @@ -0,0 +1,113 @@ +--- +title: Clients +slug: Web/API/Clients +translation_of: Web/API/Clients +--- +

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

+ +

The Clients interface of the Service Workers API represents a container for a list of {{domxref("Client")}} objects.

+ +

Methods

+ +
+
{{domxref("Clients.get()")}}
+
Gets a service worker client matching a given id and returns it in a {{jsxref("Promise")}}.
+
{{domxref("Clients.matchAll()")}}
+
Gets a list of service worker clients and returns them in a {{jsxref("Promise")}}. Include the options parameter to return all service worker clients whose origin is the same as the associated service worker's origin. If options are not included, the method returns only the service worker clients controlled by the service worker. 
+
{{domxref("Clients.openWindow()")}}
+
Opens a service worker {{domxref("Client")}} in a new browser window.
+
{{domxref("Clients.claim()")}}
+
Allows an active Service Worker to set itself as the active worker for a client page when the worker and the page are in the same scope. 
+
+ +

Examples

+ +
clients.matchAll(options).then(function(clients) {
+  for(i = 0 ; i < clients.length ; i++) {
+    if(clients[i] === 'index.html') {
+      clients.openWindow(clients[i]);
+      // or do something else involving the matching client
+    }
+  }
+});
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Service Workers', '#clients', 'Clients')}}{{Spec2('Service Workers')}}Initial definition
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(40.0)}}{{ CompatGeckoDesktop("44.0") }}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}{{ CompatGeckoMobile("44.0") }}{{ CompatVersionUnknown }}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}
+
+ +

See also

+ + diff --git a/files/zh-tw/web/api/clipboardevent/index.html b/files/zh-tw/web/api/clipboardevent/index.html new file mode 100644 index 0000000000..7353cf4978 --- /dev/null +++ b/files/zh-tw/web/api/clipboardevent/index.html @@ -0,0 +1,119 @@ +--- +title: ClipboardEvent +slug: Web/API/ClipboardEvent +translation_of: Web/API/ClipboardEvent +--- +

{{APIRef("Clipboard API")}} {{SeeCompatTable}}

+ +

ClipboardEvent 介面表示了與修改剪貼簿相關的事件,包括 {{event("cut")}}、{{event("copy")}} 及 {{event("paste")}} 事件。

+ +

屬性

+ +

Also inherits properties from its parent {{domxref("Event")}}.

+ +
+
{{domxref("ClipboardEvent.clipboardData")}} {{readonlyInline}}
+
Is a {{domxref("DataTransfer")}} object containing the data affected by the user-initiated {{event("cut")}}, {{event("copy")}}, or {{event("paste")}} operation, along with its MIME type.
+
+ +

建構式

+ +
+
{{domxref("ClipboardEvent.ClipboardEvent", "ClipboardEvent()")}}
+
Creates a ClipboardEvent event with the given parameters.
+
+ +

方法

+ +

No specific methods; inherits methods from its parent {{domxref("Event")}}.

+ +

規範

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('Clipboard API', '#clipboard-event-interfaces', 'ClipboardEvent') }}{{ Spec2('Clipboard API') }}Initial definition.
+ +

瀏覽器相容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}4.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}
clipboardData{{CompatVersionUnknown}}{{CompatGeckoDesktop("22.0")}}5.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}4.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}
clipboardData{{CompatVersionUnknown}}{{CompatGeckoMobile("22.0")}}5.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

參見

+ + diff --git a/files/zh-tw/web/api/console/assert/index.html b/files/zh-tw/web/api/console/assert/index.html new file mode 100644 index 0000000000..415b4cfa9a --- /dev/null +++ b/files/zh-tw/web/api/console/assert/index.html @@ -0,0 +1,118 @@ +--- +title: Console.assert() +slug: Web/API/console/assert +tags: + - API + - DOM + - Debugging + - 函式 + - 控制台 + - 網頁控制台 + - 網頁開發 +translation_of: Web/API/console/assert +--- +
{{APIRef("Console API")}}
+ +

如果斷言(assertion)為非(false),主控台會顯示錯誤訊息;如果斷言為是(true),則不發生任何事。

+ +

{{AvailableInWorkers}}

+ +
+

注意在 Node.js 內 console.assert() 方法的實做,與瀏覽器並不相同。

+ +

瀏覽器內呼叫 falsy 的 console.assert() 斷言出現 message,但不會中斷程式碼的執行。然而在 Node.js 裡面,falsy 斷言會拋出 AssertionError 錯誤。

+
+ +

語法

+ +
console.assert(assertion, obj1 [, obj2, ..., objN]);
+console.assert(assertion, msg [, subst1, ..., substN]); // c-like message formatting
+
+ +

參數

+ +
+
assertion
+
布林表達式。如果斷言為非,訊息會出現在主控台上。
+
obj1 ... objN
+
要印出來的 JavaScript 物件名單。 The string representations of each of these objects are appended together in the order listed and output.
+
msg
+
包含零個以上的 JavaScript 替代(substitution)字串。
+
subst1 ... substN
+
JavaScript objects with which to replace substitution strings within msg. This parameter gives you additional control over the format of the output.
+
+ +

請參見 {{domxref("console")}} 的 Outputting text to the console 以獲取詳細資訊。

+ +

範例

+ +

以下程式碼示範一個 JavaScript 物件的斷言使用:

+ +
const errorMsg = 'the # is not even';
+for (let number = 2; number <= 5; number += 1) {
+    console.log('the # is ' + number);
+    console.assert(number % 2 === 0, {number: number, errorMsg: errorMsg});
+    // or, using ES2015 object property shorthand:
+    // console.assert(number % 2 === 0, {number, errorMsg});
+}
+// output:
+// the # is 2
+// the # is 3
+// Assertion failed: {number: 3, errorMsg: "the # is not even"}
+// the # is 4
+// the # is 5
+// Assertion failed: {number: 5, errorMsg: "the # is not even"}
+
+ +

請注意,雖然包含替換字符串的字符串在 Node 中用作 console.log 的參數,但很多(如果不是大多數)瀏覽器...

+ +
console.log('the word is %s', 'foo');
+// output: the word is foo
+
+ +

...在所有瀏覽器中,使用此類字符串目前無法作為console.assert的參數使用:

+ +
console.assert(false, 'the word is %s', 'foo');
+// correct output in Node (e.g. v8.10.0) and some browsers
+//     (e.g. Firefox v60.0.2):
+// Assertion failed: the word is foo
+// incorrect output in some browsers
+//     (e.g. Chrome v67.0.3396.87):
+// Assertion failed: the word is %s foo
+
+ +

有關詳細信息,請參閱 {{domxref("console")}} 文檔中的將文本輸出到控制台

+ +

規範

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Console API", "#assert", "console.assert()")}}{{Spec2("Console API")}}初始定義
+ +

瀏覽器相容性

+ + + +

{{Compat("api.Console.assert")}}

+ +

參見

+ + diff --git a/files/zh-tw/web/api/console/index.html b/files/zh-tw/web/api/console/index.html new file mode 100644 index 0000000000..36320a69a8 --- /dev/null +++ b/files/zh-tw/web/api/console/index.html @@ -0,0 +1,289 @@ +--- +title: Console +slug: Web/API/Console +tags: + - API + - Debugging + - Interface + - NeedsCompatTable + - NeedsTranslation + - Reference + - TopicStub + - console + - web console +translation_of: Web/API/Console +--- +
{{APIRef("Console API")}}
+ +

The Console object provides access to the browser's debugging console (e.g. the Web Console in Firefox). The specifics of how it works varies from browser to browser, but there is a de facto set of features that are typically provided.

+ +

The Console object can be accessed from any global object. {{domxref("Window")}} on browsing scopes and {{domxref("WorkerGlobalScope")}} as specific variants in workers via the property console. It's exposed as {{domxref("Window.console")}}, and can be referenced as simply console. For example:

+ +
console.log("Failed to open the specified link")
+ +

This page documents the {{anch("Methods")}} available on the Console object and gives a few {{anch("Usage")}} examples.

+ +

{{AvailableInWorkers}}

+ +

Methods

+ +
+
{{domxref("Console.assert()")}}
+
Log a message and stack trace to console if the first argument is false.
+
{{domxref("Console.clear()")}}
+
Clear the console.
+
{{domxref("Console.count()")}}
+
Log the number of times this line has been called with the given label.
+
{{domxref("Console.debug()")}}
+
An alias for log(). +
Note: Starting with Chromium 58 this method only appears in Chromium browser consoles when level "Verbose" is selected.
+
+
{{domxref("Console.dir()")}} {{Non-standard_inline}}
+
Displays an interactive listing of the properties of a specified JavaScript object. This listing lets you use disclosure triangles to examine the contents of child objects.
+
{{domxref("Console.dirxml()")}} {{Non-standard_inline}}
+
+

Displays an XML/HTML Element representation of the specified object if possible or the JavaScript Object view if it is not possible.

+
+
{{domxref("Console.error()")}}
+
Outputs an error message. You may use string substitution and additional arguments with this method.
+
{{domxref("Console.exception()")}} {{Non-standard_inline}} {{deprecated_inline}}
+
An alias for error().
+
{{domxref("Console.group()")}}
+
Creates a new inline group, indenting all following output by another level. To move back out a level, call groupEnd().
+
{{domxref("Console.groupCollapsed()")}}
+
Creates a new inline group, indenting all following output by another level. However, unlike group() this starts with the inline group collapsed requiring the use of a disclosure button to expand it. To move back out a level, call groupEnd().
+
{{domxref("Console.groupEnd()")}}
+
Exits the current inline group.
+
{{domxref("Console.info()")}}
+
Informative logging of information. You may use string substitution and additional arguments with this method.
+
{{domxref("Console.log()")}}
+
For general output of logging information. You may use string substitution and additional arguments with this method.
+
{{domxref("Console.profile()")}} {{Non-standard_inline}}
+
Starts the browser's built-in profiler (for example, the Firefox performance tool). You can specify an optional name for the profile.
+
{{domxref("Console.profileEnd()")}} {{Non-standard_inline}}
+
Stops the profiler. You can see the resulting profile in the browser's performance tool (for example, the Firefox performance tool).
+
{{domxref("Console.table()")}}
+
Displays tabular data as a table.
+
{{domxref("Console.time()")}}
+
Starts a timer with a name specified as an input parameter. Up to 10,000 simultaneous timers can run on a given page.
+
{{domxref("Console.timeEnd()")}}
+
Stops the specified timer and logs the elapsed time in seconds since it started.
+
{{domxref("Console.timeStamp()")}} {{Non-standard_inline}}
+
Adds a marker to the browser's Timeline or Waterfall tool.
+
{{domxref("Console.trace()")}}
+
Outputs a stack trace.
+
{{domxref("Console.warn()")}}
+
Outputs a warning message. You may use string substitution and additional arguments with this method.
+
+ +

Usage

+ +

Outputting text to the console

+ +

The most frequently-used feature of the console is logging of text and other data. There are four categories of output you can generate, using the {{domxref("console.log()")}}, {{domxref("console.info()")}}, {{domxref("console.warn()")}}, and {{domxref("console.error()")}} methods respectively. Each of these results in output styled differently in the log, and you can use the filtering controls provided by your browser to only view the kinds of output that interest you.

+ +

There are two ways to use each of the output methods; you can simply pass in a list of objects whose string representations get concatenated into one string, then output to the console, or you can pass in a string containing zero or more substitution strings followed by a list of objects to replace them.

+ +

Outputting a single object

+ +

The simplest way to use the logging methods is to output a single object:

+ +
var someObject = { str: "Some text", id: 5 };
+console.log(someObject);
+
+ +

The output looks something like this:

+ +
[09:27:13.475] ({str:"Some text", id:5})
+ +

Outputting multiple objects

+ +

You can also output multiple objects by simply listing them when calling the logging method, like this:

+ +
var car = "Dodge Charger";
+var someObject = { str: "Some text", id: 5 };
+console.info("My first car was a", car, ". The object is:", someObject);
+ +

This output will look like this:

+ +
[09:28:22.711] My first car was a Dodge Charger . The object is: ({str:"Some text", id:5})
+
+ +

Using string substitutions

+ +

Gecko 9.0 {{geckoRelease("9.0")}} introduced support for string substitutions. When passing a string to one of the console object's methods that accepts a string, you may use these substitution strings:

+ + + + + + + + + + + + + + + + + + + + + + + + +
Substitution stringDescription
%o or %OOutputs a JavaScript object. Clicking the object name opens more information about it in the inspector.
%d or %iOutputs an integer. Number formatting is supported, for example  console.log("Foo %.2d", 1.1) will output the number as two significant figures with a leading 0: Foo 01
%sOutputs a string.
%fOutputs a floating-point value. Formatting is supported, for example  console.log("Foo %.2f", 1.1) will output the number to 2 decimal places: Foo 1.10
+ +
+

Note: Precision formatting doesn't work in Chrome

+
+ +

Each of these pulls the next argument after the format string off the parameter list. For example:

+ +
for (var i=0; i<5; i++) {
+  console.log("Hello, %s. You've called me %d times.", "Bob", i+1);
+}
+
+ +

The output looks like this:

+ +
[13:14:13.481] Hello, Bob. You've called me 1 times.
+[13:14:13.483] Hello, Bob. You've called me 2 times.
+[13:14:13.485] Hello, Bob. You've called me 3 times.
+[13:14:13.487] Hello, Bob. You've called me 4 times.
+[13:14:13.488] Hello, Bob. You've called me 5 times.
+
+ +

Styling console output

+ +

You can use the %c directive to apply a CSS style to console output:

+ +
console.log("This is %cMy stylish message", "color: yellow; font-style: italic; background-color: blue;padding: 2px");
+ +
The text before the directive will not be affected, but the text after the directive will be styled using the CSS declarations in the parameter.
+ +
 
+ +
+ +
 
+ +
+

Note: Quite a few CSS properties are supported by this styling; you should experiment and see which ones prove useful.

+
+ +
 
+ +
{{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 the only parameter. To stop the timer, and to get the elapsed time in milliseconds, 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:

+ +
function foo() {
+  function bar() {
+    console.trace();
+  }
+  bar();
+}
+
+foo();
+
+ +

The output in the console looks something like this:

+ +

+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Console API')}}{{Spec2('Console API')}}Initial definition.
+ +

Browser compatibility

+ + + +

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

+ +

Notes

+ + + +

See also

+ + + +

Other implementations

+ + diff --git a/files/zh-tw/web/api/css_object_model/determining_the_dimensions_of_elements/index.html b/files/zh-tw/web/api/css_object_model/determining_the_dimensions_of_elements/index.html new file mode 100644 index 0000000000..589300d041 --- /dev/null +++ b/files/zh-tw/web/api/css_object_model/determining_the_dimensions_of_elements/index.html @@ -0,0 +1,33 @@ +--- +title: Determining the dimensions of elements +slug: Web/API/CSS_Object_Model/Determining_the_dimensions_of_elements +translation_of: Web/API/CSS_Object_Model/Determining_the_dimensions_of_elements +--- +

{{APIRef("CSSOM View")}}

+ +

There are several properties you can look at in order to determine the width and height of elements, and it can be tricky to determine which is the right one for your needs. This article is designed to help you make that decision.  Note that all these properties are read-only.  If you want to set the width and height of an element, use  width and height; or, the overriding min-width and max-width, and min-height and max-height properties.

+ +

How much room does it use up?

+ +

If you need to know the total amount of space an element occupies, including the width of the visible content, scrollbars (if any), padding, and border, you want to use the offsetWidth and offsetHeight properties. Most of the time these are the same as width and height of getBoundingClientRect(), when there aren't any transforms applied to the element. In case of transforms, the offsetWidth and offsetHeight returns the element's layout width and height, while getBoundingClientRect() returns the rendering width and height. As an example, if the element has width: 100px; and transform: scale(0.5); the getBoundingClientRect() will return 50 as the width, while offsetWidth will return 100.

+ +

Image:Dimensions-offset.png

+ +

What's the size of the displayed content?

+ +

If you need to know how much space the actual displayed content takes up, including padding but not including the border, margins, or scrollbars, you want to use the clientWidth and clientHeight properties:

+ +

Image:Dimensions-client.png

+ +

How big is the content?

+ +

If you need to know the actual size of the content, regardless of how much of it is currently visible, you need to use the scrollWidth and scrollHeight properties. These return the width and height of the entire content of an element, even if only part of it is presently visible due to the use of scroll bars.

+ +

For example, if a 600x400 pixel element is being displayed inside a 300x300 pixel scrollbox, scrollWidth will return 600 while scrollHeight will return 400.

+ +

參見

+ + diff --git a/files/zh-tw/web/api/css_object_model/index.html b/files/zh-tw/web/api/css_object_model/index.html new file mode 100644 index 0000000000..e924a96301 --- /dev/null +++ b/files/zh-tw/web/api/css_object_model/index.html @@ -0,0 +1,131 @@ +--- +title: CSS Object Model +slug: Web/API/CSS_Object_Model +tags: + - API + - CSSOM + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/API/CSS_Object_Model +--- +

{{DefaultAPISidebar('CSSOM')}}

+ +

The CSS Object Model is a set of APIs allowing to manipulate CSS from JavaScript. It is the pendant of DOM and HTML APIs, but for CSS. It allows to read and modify CSS style dynamically.

+ +

Reference

+ +
+ +
+ +

Several other interfaces are also extended by the CSSOM-related specifications: {{domxref("Document")}}, {{domxref("Window")}}, {{domxref("Element")}}, {{domxref("HTMLElement")}}, {{domxref("HTMLImageElement")}}, {{domxref("Range")}}, {{domxref("MouseEvent")}}, and {{domxref("SVGElement")}}.

+ +

Tutorials

+ + + +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{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")}} 
+ +

Browser compatibility notes

+ +

All these features have been added little by little over the years to the different browsers: it was a quite complex process that can't be summarized in a simple table. Please refer to the specific interfaces for its availability.

diff --git a/files/zh-tw/web/api/css_object_model/managing_screen_orientation/index.html b/files/zh-tw/web/api/css_object_model/managing_screen_orientation/index.html new file mode 100644 index 0000000000..806ac2d047 --- /dev/null +++ b/files/zh-tw/web/api/css_object_model/managing_screen_orientation/index.html @@ -0,0 +1,172 @@ +--- +title: 控制畫面方向 +slug: Web/API/CSS_Object_Model/Managing_screen_orientation +translation_of: Web/API/CSS_Object_Model/Managing_screen_orientation +--- +

{{SeeCompatTable}}{{APIRef}}

+ +

摘要

+ +

畫面方向(Screen Orientation)與裝置方向(Device Orientation)略有不同。有時甚至裝置本身不具備方向偵測功能,但裝置的螢幕仍搭載方向功能。如果裝置可測知本身的方向又能控制畫面方向,就能隨時配合 Web Apps 而達到最佳效果。

+ +

現有 2 種方法可處理畫面的方向,但均需搭配 CSS 與 JavaScript。第一種方法就是方向的 Media Query。根據瀏覽器視窗為橫放(寬度大於高度)或直放(高度大於寬度)狀態,而透過 CSS 調整網頁內容的配置。

+ +

第二種方法就是 JavaScript Screen Orientation API,可取得畫面目前的方向並進一步鎖定。

+ +

根據方向而調整配置

+ +

方向改變最常見的情形之一,就是根據裝置的方向而修正內容的配置方式。舉例來說,你可能想將按鈕列拉到與裝置螢幕等長。而透過 Media Query 即可輕鬆達到此效果。

+ +

來看看下列 HTML 程式碼範例:

+ +
<ul id="toolbar">
+  <li>A</li>
+  <li>B</li>
+  <li>C</li>
+</ul>
+
+<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis lacinia nisi nec sem viverra vitae fringilla nulla ultricies. In ac est dolor, quis tincidunt leo. Cras commodo quam non tortor consectetur eget rutrum dolor ultricies. Ut interdum tristique dapibus. Nullam quis malesuada est.</p>
+
+ +

CSS 將根據方向的 Media Query,處理畫面方向的特殊樣式:

+ +
/* First let's define some common styles */
+
+html, body {
+  width : 100%;
+  height: 100%;
+}
+
+body {
+  border: 1px solid black;
+
+  -moz-box-sizing: border-box;
+  box-sizing: border-box;
+}
+
+p {
+  font   : 1em sans-serif;
+  margin : 0;
+  padding: .5em;
+}
+
+ul {
+  list-style: none;
+
+  font   : 1em monospace;
+  margin : 0;
+  padding: .5em;
+
+  -moz-box-sizing: border-box;
+  box-sizing: border-box;
+
+  background: black;
+}
+
+li {
+  display: inline-block;
+  margin : 0;
+  padding: 0.5em;
+  background: white;
+}
+
+ +

在設定某些通用的樣式之後,即可針對方向定義特殊條件:

+ +
/* For portrait, we want the tool bar on top */
+
+@media screen and (orientation: portrait) {
+  #toolbar {
+    width: 100%;
+  }
+}
+
+/* For landscape, we want the tool bar stick on the left */
+
+@media screen and (orientation: landscape) {
+  #toolbar {
+    position: fixed;
+    width: 2.65em;
+    height: 100%;
+  }
+
+  p {
+    margin-left: 2em;
+  }
+
+  li + li {
+    margin-top: .5em;
+  }
+}
+
+ +

結果如下所示(若無法顯示,可至本文右上角切換回英文原文觀看):

+ + + + + + + + + + + + + + +
PortraitLandscape
{{ EmbedLiveSample('Adjusting_layout_based_on_the_orientation', 180, 350) }}{{ EmbedLiveSample('Adjusting_layout_based_on_the_orientation', 350, 180) }}
+ +
+

注意:方向 Media Query 其實是以瀏覽器視窗 (或 iframe) 的方向為準,而非裝置本身的方向。

+
+ +

鎖定畫面方向

+ +
+

警告:此 API 仍屬實驗性質,目前仍具備 moz 前綴而僅能用於 Firefox OSFirefox for Android,而 Windows 8.1 以上版本的 Internet Explorer 則使用 ms 前綴。

+
+ +

某些裝置(主要為行動裝置)可根據本身方向而動態改變畫面的方向,讓使用者隨時閱讀畫面上的資訊。這種動作對文字類的內容影響不大,但某些內容就無法順利套用此功能。舉例來說,若遊戲需要裝置方向的相關資訊,就可能因為方向變化而發生混亂情形。

+ +

而 Screen Orientation API 即可用以避免或處理這類變化。

+ +

監聽方向變化

+ +

只要裝置改變了畫面方向與本身方向,就會觸發 {{event("orientationchange")}} 事件,再由 {{domxref("Screen.orientation")}} 屬性讀取之。

+ +
screen.addEventListener("orientationchange", function () {
+  console.log("The orientation of the screen is: " + screen.orientation);
+});
+
+ +

避免方向改變

+ +

任何 Web Apps 均可鎖定畫面以符合本身需求。{{domxref("Screen.lockOrientation()")}} 函式可鎖定畫面方向;{{domxref("Screen.unlockOrientation()")}} 函式可解鎖畫面方向。

+ +

{{domxref("Screen.lockOrientation()")}} 將接受一組字串或系列字串,以定義畫面鎖定的方向。有效字串為:「portrait-primary」、「portrait-secondary」、「landscape-primary」、「landscape-secondary」、「portrait」、「landscape」。另可參閱 {{domxref("Screen.lockOrientation")}} 進一步了解這些有效值。

+ +
screen.lockOrientation('landscape');
+ +
+

注意:畫面鎖定功能將依 Web Apps 而有所不同。如果 App A 鎖定為 landscape;App B 鎖定為 portrait,則此兩款 Apps 均將維持自己的方向。所以不論如何切換 A 與 B,均不會觸發 {{event("orientationchange")}} 事件。

+ +

但若必須改變方向以滿足畫面鎖定的需求,則鎖定方向時就會觸發 {{event("orientationchange")}} 事件。

+
+ +

Firefox OS and Android: Orientation lock using the manifest

+ +

For a Firefox OS and Firefox Android (soon to work on Firefox desktop too) specific way to lock orientation, you can set the orientation field in app's your manifest file, for example:

+ +
"orientation": "portrait"
+ +

參見

+ + diff --git a/files/zh-tw/web/api/css_object_model/using_dynamic_styling_information/index.html b/files/zh-tw/web/api/css_object_model/using_dynamic_styling_information/index.html new file mode 100644 index 0000000000..fa020403aa --- /dev/null +++ b/files/zh-tw/web/api/css_object_model/using_dynamic_styling_information/index.html @@ -0,0 +1,132 @@ +--- +title: 使用動態樣式資訊 +slug: Web/API/CSS_Object_Model/Using_dynamic_styling_information +translation_of: Web/API/CSS_Object_Model/Using_dynamic_styling_information +--- +

The CSS Object Model (CSSOM), part of the DOM, exposes specific interfaces allowing manipulation of a wide amount of information regarding CSS. Initially defined in the DOM Level 2 Style recommendation, these interfaces forms now a specification, CSS Object Model (CSSOM) which aims at superseding it.

+ +

In many cases, and where possible, it really is best practice to dynamically manipulate classes via the {{ domxref("element.className", "className") }} property since the ultimate appearance of all of the styling hooks can be controlled in a single stylesheet. One's JavaScript code also becomes cleaner since instead of being dedicated to styling details, it can focus on the overall semantics of each section it is creating or manipulating, leaving the precise style details to the stylesheet. However, there are cases where actually obtaining or manipulating the rules can be useful (whether for whole stylesheets or individual elements), and that is described in further detail below. Note also that, as with individual element's DOM styles, when speaking of manipulating the stylesheets, this is not actually manipulating the physical document(s), but merely the internal representation of the document.

+ +

The basic style object exposes the {{domxref("Stylesheet")}} and the {{domxref("CSSStylesheet")}} interfaces. Those interfaces contain members like insertRule, selectorText, and parentStyleSheet for accessing and manipulating the individual style rules that make up a CSS stylesheet.

+ +

To get to the style objects from the document, you can use the {{domxref("document.styleSheets")}} property and access the individual objects by index (e.g., document.styleSheets[0] is the first stylesheet defined for the document, etc.).

+ +

透過 CSSOM 修改樣式表規則

+ +
<html>
+<head>
+<title>Modifying a stylesheet rule with CSSOM</title>
+<style type="text/css">
+body {
+ background-color: red;
+}
+</style>
+<script type="text/javascript">
+var stylesheet = document.styleSheets[1];
+stylesheet.cssRules[0].style.backgroundColor="blue";
+</script>
+</head>
+<body>
+The stylesheet declaration for the body's background color is modified via JavaScript.
+</body>
+</html>
+ +

{{ EmbedLiveSample('Modify_a_stylesheet_rule') }}

+ +

The list of properties available in the DOM from the style property is given on the DOM CSS Properties List page.

+ +

To modify styles to a document using CSS syntax, one can insert rules or insert {{HTMLElement("style")}} tags whose innerHTML property is set to the desired CSS.

+ +

修改元素的樣式

+ +

The element {{domxref("HTMLElement.style", "style")}} property (see also the section "DOM Style Object" below) can also be used to get and set the styles on an element. However, this property only returns style attributes that have been set in-line (e.g, <td style="background-color: lightblue"> returns the string "background-color:lightblue", or directly for that element using element.style.propertyName, even though there may be other styles on the element from a stylesheet).

+ +

Also, when you set this property on an element, you override and erase any styles that have been set elsewhere for that element's particular property you are setting. Setting the border property, for example, will override settings made elsewhere for that element's border property in the head section, or external style sheets. However, this will not affect any other property declarations for that element's styles, such as padding or margin or font, for example.

+ +

To change a particular element's style, you can adapt the following example for the element(s) you want to style.

+ +
<html>
+<head>
+<title>simple style example</title>
+
+<script type="text/javascript">
+
+function alterStyle(elem) {
+  elem.style.background = 'green';
+}
+
+function resetStyle(elemId) {
+  elem = document.getElementById(elemId);
+  elem.style.background = 'white';
+}
+</script>
+
+<style type="text/css">
+#p1 {
+  border: solid blue 2px;
+}
+</style>
+</head>
+
+<body>
+
+<!-- passes a reference to the element's object as parameter 'this'. -->
+<p id="p1" onclick="alterStyle(this);">
+ Click here to change background color.
+</p>
+
+<!-- passes the 'p1' id of another element's style to modify. -->
+<button onclick="resetStyle('p1');">Reset background color</button>
+
+</body>
+</html>
+
+ +

{{ EmbedLiveSample('Modify_an_element_style') }}

+ +

The {{domxref("window.getComputedStyle", "getComputedStyle()")}} method on the document.defaultView object returns all styles that have actually been computed for an element. See Example 6: getComputedStyle in the examples chapter for more information on how to use this method.

+ +

DOM Style Object

+ +

The style object represents an individual style statement. Unlike the individual rules available from the document.styleSheets collection, the style object is accessed from the document or from the elements to which that style is applied. It represents the in-line styles on a particular element.

+ +

More important than the two properties noted here is the use of the style object to set individual style properties on an element:

+ +
+
<!DOCTYPE html>
+<html>
+ <head>
+  <title>style Property Example</title>
+  <link rel="StyleSheet" href="example.css" type="text/css">
+  <script type="text/javascript">
+    function stilo() {
+      document.getElementById('d').style.color = 'orange';
+    }
+    function resetStyle() {
+      document.getElementById('d').style.color = 'black';
+    }
+  </script>
+ </head>
+
+ <body>
+  <div id="d" class="thunder">Thunder</div>
+  <button onclick="stilo()">Click here to change text color</button>
+  <button onclick="resetStyle()">Reset text color</button>
+ </body>
+</html>
+
+
+ +

{{ EmbedLiveSample('DOM_Style_Object_code_sample') }}

+ +

The media and type of the style may or may not be given.

+ +

使用 setAttribute 方法

+ +

Note that you can also change style of an element by getting a reference to it and then use its setAttribute method to specify the CSS property and its value.

+ +
var el = document.getElementById('some-element');
+el.setAttribute('style', 'background-color:darkblue;');
+
+ +

Be aware, however, that setAttribute removes all other style properties that may already have been defined in the element's style object. If the some-element element above had an in–line style attribute of say style="font-size: 18px", that value would be removed by the use of setAttribute.

diff --git a/files/zh-tw/web/api/cssstyledeclaration/index.html b/files/zh-tw/web/api/cssstyledeclaration/index.html new file mode 100644 index 0000000000..8893e225d6 --- /dev/null +++ b/files/zh-tw/web/api/cssstyledeclaration/index.html @@ -0,0 +1,90 @@ +--- +title: CSSStyleDeclaration +slug: Web/API/CSSStyleDeclaration +translation_of: Web/API/CSSStyleDeclaration +--- +

{{ APIRef("CSSOM") }}

+ +

概要

+ +

CSSStyleDeclaration 表示了一個 CSS 屬性名值對(property-value pairs)的集合。它被用於幾個 API 當中:

+ + + +

屬性

+ +
+
{{domxref("CSSStyleDeclaration.cssText")}}
+
Textual representation of the declaration block. Setting this attribute changes the style.
+
{{domxref("CSSStyleDeclaration.length")}} {{readonlyInline}}
+
The number of properties. See the {{domxref("CSSStyleDeclaration.item", 'item()')}} method below.
+
{{domxref("CSSStyleDeclaration.parentRule")}} {{readonlyInline}}
+
The containing {{domxref("CSSRule")}}.
+
+ +

方法

+ +
+
{{domxref("CSSStyleDeclaration.getPropertyPriority()")}}
+
Returns the optional priority, "important".
+
{{domxref("CSSStyleDeclaration.getPropertyValue()")}}
+
Returns the property value given a property name.
+
{{domxref("CSSStyleDeclaration.item()")}}
+
Returns a property name.
+
{{domxref("CSSStyleDeclaration.removeProperty()")}}
+
Removes a property from the CSS declaration block.
+
{{domxref("CSSStyleDeclaration.setProperty()")}}
+
Modifies an existing CSS property or creates a new CSS property in the declaration block/.
+
{{domxref("CSSStyleDeclaration.getPropertyCSSValue()")}} {{obsolete_inline}}
+
Only supported via getComputedStyle in Firefox. Returns the property value as a {{ domxref("CSSPrimitiveValue") }} or null for shorthand properties.
+
+ +

範例

+ +
var styleObj = document.styleSheets[0].cssRules[0].style;
+console.log(styleObj.cssText);
+
+for (var i = styleObj.length; i--;) {
+  var nameString = styleObj[i];
+  styleObj.removeProperty(nameString);
+}
+
+console.log(styleObj.cssText);
+ +

備註

+ +

The declaration block is that part of the style rule that appears within the braces and that actually provides the style definitions (for the selector, the part that comes before the braces).

+ +

參見

+ + + +

規範

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSSOM', '#the-cssstyledeclaration-interface', 'CSSStyleDeclaration')}}{{Spec2('CSSOM')}} 
{{SpecName('DOM2 Style', 'css.html#CSS-CSSStyleDeclaration', 'CSSPrimitiveValue')}}{{Spec2('DOM2 Style')}}Initial definition
diff --git a/files/zh-tw/web/api/cssstylesheet/index.html b/files/zh-tw/web/api/cssstylesheet/index.html new file mode 100644 index 0000000000..01abf1a942 --- /dev/null +++ b/files/zh-tw/web/api/cssstylesheet/index.html @@ -0,0 +1,187 @@ +--- +title: CSSStyleSheet +slug: Web/API/CSSStyleSheet +tags: + - API + - CSSOM + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/API/CSSStyleSheet +--- +
{{APIRef("CSSOM")}}
+ +

The CSSStyleSheet interface represents a single CSS style sheet. It inherits properties and methods from its parent, {{domxref("StyleSheet")}}.

+ +

A style sheet consists of {{domxref("CSSRule", "rules", "", 1)}}, such as {{domxref("CSSStyleRule", "style rules", "", 1)}} ("h1,h2 { font-size: 16pt }"), various at-rules (@import, @media, ...), etc. This interface lets you inspect and modify the list of rules in the stylesheet.

+ +

See the {{anch("Notes")}} section for the various ways a CSSStyleSheet object can be obtained.

+ +

Properties

+ +

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

+ +
+
{{domxref("CSSStyleSheet.cssRules")}}
+
Returns a live {{domxref("CSSRuleList")}}, listing the {{domxref("CSSRule")}} objects in the style sheet.
+ This is normally used to access individual rules like this:
+    styleSheet.cssRules[i] // where i = 0..cssRules.length-1
+ To add or remove items in cssRules, use the CSSStyleSheet's deleteRule() and insertRule() methods, described below.
+
{{domxref("CSSStyleSheet.ownerRule")}}
+
If this style sheet is imported into the document using an {{cssxref("@import")}} rule, the ownerRule property will return that {{domxref("CSSImportRule")}}, otherwise it returns null.
+
+ +

Methods

+ +

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

+ +
+
{{domxref("CSSStyleSheet.deleteRule()")}}
+
Deletes a rule at the specified position from the style sheet.
+
{{domxref("CSSStyleSheet.insertRule()")}}
+
Inserts a new rule at the specified position in the style sheet, given the textual representation of the rule.
+
+ +

Notes

+ +

In some browsers, if a stylesheet is loaded from a different domain, calling cssRules results in SecurityError.

+ +

A stylesheet is associated with at most one {{domxref("Document")}}, which it applies to (unless {{domxref("StyleSheet.disabled", "disabled", "", 1)}}). A list of CSSStyleSheet objects for a given document can be obtained using the {{domxref("document.styleSheets")}} property. A specific style sheet can also be accessed from its owner object (Node or CSSImportRule), if any.

+ +

A CSSStyleSheet object is created and inserted into the document's styleSheets list automatically by the browser, when a style sheet is loaded for a document. As the {{domxref("document.styleSheets")}} list cannot be modified directly, there's no useful way to create a new CSSStyleSheet object manually (although Constructable Stylesheet Objects might get added to the Web APIs at some point). To create a new stylesheet, insert a {{HTMLElement("style")}} or {{HTMLElement("link")}} element into the document.

+ +

A (possibly incomplete) list of ways a style sheet can be associated with a document follows:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Reason for the style sheet to be associated with the documentAppears in document.
+ styleSheets
list
Getting the owner element/rule given the style sheet objectThe interface for the owner objectGetting the CSSStyleSheet object from the owner
{{HTMLElement("style")}} and {{HTMLElement("link")}} elements in the documentYes{{domxref("StyleSheet.ownerNode", ".ownerNode")}}{{domxref("HTMLLinkElement")}},
+ {{domxref("HTMLStyleElement")}},
+ or {{domxref("SVGStyleElement")}}
{{domxref("LinkStyle.sheet", ".sheet")}}
CSS {{cssxref("@import")}} rule in other style sheets applied to the documentYes{{domxref("CSSStyleSheet.ownerRule", ".ownerRule")}}{{domxref("CSSImportRule")}}{{domxref("CSSImportRule.styleSheet", ".styleSheet")}}
<?xml-stylesheet ?> processing instruction in the (non-HTML) documentYes{{domxref("StyleSheet.ownerNode", ".ownerNode")}}{{domxref("ProcessingInstruction")}}{{domxref("LinkStyle.sheet", ".sheet")}}
HTTP Link HeaderYesN/AN/AN/A
User agent (default) style sheetsNoN/AN/AN/A
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("CSSOM", "#cssstylesheet", 'CSSStyleSheet')}}{{Spec2("CSSOM")}} 
{{SpecName("DOM2 Style", "css.html#CSS-CSSStyleSheet", "CSSStyleSheet")}}{{Spec2("DOM2 Style")}}Initial definition
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}9.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

See also

+ + diff --git a/files/zh-tw/web/api/cssstylesheet/insertrule/index.html b/files/zh-tw/web/api/cssstylesheet/insertrule/index.html new file mode 100644 index 0000000000..3cd8ba5a87 --- /dev/null +++ b/files/zh-tw/web/api/cssstylesheet/insertrule/index.html @@ -0,0 +1,219 @@ +--- +title: CSSStyleSheet.insertRule() +slug: Web/API/CSSStyleSheet/insertRule +translation_of: Web/API/CSSStyleSheet/insertRule +--- +
{{APIRef("CSSOM")}} 
+ +

CSSStyleSheet.insertRule() 方法新增一個新的 CSS 規則,到當前的樣式表,他伴隨著一些限制.  

+ +

更明確的說,雖然 insertRule() 只是一個 {{domxref("CSSStyleSheet")}} 的方法, 他實際上插入這份規則到 {{domxref("CSSStyleSheet")}}.cssRules, 在 {{domxref("CSSRuleList")}} 之中。

+ +

這份規則,必須包含的內容,取決於它的類型: 對於規則集 (rule-sets),規則同時指定了選擇器和样式聲明。 對於規則 (at-rules),規則同時指定 at 標識符( at-identifier )和規則內容。

+ +

Syntax

+ +

+
+stylesheet.insertRule(rule[, index])
+ +

Parameters

+ +
+
rule
+
一個  {{domxref("DOMString")}} 包含要被插入的規則,這份規則同時指定了選擇器( selector )和样式聲明,或 at 標識符 (at-identifier ) 和規則內容。
+
index {{optional_inline}}
+
+

無符號整數,代表在 {{domxref("CSSStyleSheet")}}.cssRules 中插入的位置,其中 index-0 是第一個規則,而 index-max 就是最後一個規則,並且與 CSSStyleSheet 的長度相同。cssRules 在舊的實現中是必需的。查詢「瀏覽器兼容」取得詳細信息。 默認值為 0。

+
+
+ +

Return value

+ +

The index within the style sheet's rule-list of the newly inserted rule.

+ +

Restrictions  限制

+ +

CSS 樣式表規則列表,有一些直覺的、和不是那麼直覺的限制 ,影響著規則的插入方式和位置。
+ 違反這些可能會導致 DOM 異常 ({{domxref("DOMException")}}) 引發錯誤。

+ + + +

Examples

+ +

Example 1

+ +
// push a new rule onto the top of my stylesheet
+myStyle.insertRule("#blanc { color: white }", 0);
+
+ +

Example 2

+ +
/**
+ * Add a stylesheet rule to the document (may be better practice, however,
+ * to dynamically change classes, so style information can be kept in
+ * genuine stylesheets (and avoid adding extra elements to the DOM))
+ * Note that an array is needed for declarations and rules since ECMAScript does
+ * not afford a predictable object iteration order and since CSS is
+ * order-dependent (i.e., it is cascading); those without need of
+ * cascading rules could build a more accessor-friendly object-based API.
+ * @param {Array} rules Accepts an array of JSON-encoded declarations
+ * @example
+addStylesheetRules([
+  ['h2', // Also accepts a second argument as an array of arrays instead
+    ['color', 'red'],
+    ['background-color', 'green', true] // 'true' for !important rules
+  ],
+  ['.myClass',
+    ['background-color', 'yellow']
+  ]
+]);
+ */
+function addStylesheetRules (rules) {
+  var styleEl = document.createElement('style'),
+      styleSheet;
+
+  // Append style element to head
+  document.head.appendChild(styleEl);
+
+  // Grab style sheet
+  styleSheet = styleEl.sheet;
+
+  for (var i = 0, rl = rules.length; i < rl; i++) {
+    var j = 1, rule = rules[i], selector = rules[i][0], propStr = '';
+    // If the second argument of a rule is an array of arrays, correct our variables.
+    if (Object.prototype.toString.call(rule[1][0]) === '[object Array]') {
+      rule = rule[1];
+      j = 0;
+    }
+
+    for (var pl = rule.length; j < pl; j++) {
+      var prop = rule[j];
+      propStr += prop[0] + ':' + prop[1] + (prop[2] ? ' !important' : '') + ';\n';
+    }
+
+    // Insert CSS Rule
+    styleSheet.insertRule(selector + '{' + propStr + '}', styleSheet.cssRules.length);
+  }
+}
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSSOM', '#dom-cssstylesheet-insertrule', 'CSSStyleSheet.insertRule')}}{{Spec2('CSSOM')}}No change from {{SpecName('DOM2 Style')}}.
{{SpecName('DOM2 Style', 'css.html#CSS-CSSStyleSheet-insertRule', 'CSSStyleSheet.insertRule')}}{{Spec2('DOM2 Style')}}Initial definition
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}9{{CompatVersionUnknown}}{{CompatVersionUnknown}}
index is optional{{CompatChrome(60)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOpera(47)}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
index is optional{{CompatChrome(60)}}{{CompatChrome(60)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOperaMobile(47)}}{{CompatUnknown}}
+
+ +

Legacy browser support

+ + + +

See also

+ + diff --git a/files/zh-tw/web/api/customevent/customevent/index.html b/files/zh-tw/web/api/customevent/customevent/index.html new file mode 100644 index 0000000000..0accf247e5 --- /dev/null +++ b/files/zh-tw/web/api/customevent/customevent/index.html @@ -0,0 +1,90 @@ +--- +title: CustomEvent() +slug: Web/API/CustomEvent/CustomEvent +translation_of: Web/API/CustomEvent/CustomEvent +--- +

{{APIRef("DOM")}}

+ +

CustomEvent() constructor 可用來建立 {{domxref("CustomEvent")}}.

+ +

語法

+ +
 event = new CustomEvent(typeArg, customEventInit);
+ +

參數

+ +
+
typeArg
+
一個 {{domxref("DOMString")}} 用來表示事件名稱。
+
customEventInit{{optional_inline}}
+
Is a CustomEventInit dictionary, having the following fields: +
    +
  • "detail", optional and defaulting to null, of type any, that is a event-dependant value associated with the event.
  • +
+ +
+

The CustomEventInit dictionary also accepts fields from the {{domxref("Event.Event", "EventInit")}} dictionary.

+
+
+
+ +

範例

+ +
// add an appropriate event listener
+obj.addEventListener("cat", function(e) { process(e.detail) });
+
+// create and dispatch the event
+var event = new CustomEvent("cat", {
+  detail: {
+    hazcheeseburger: true
+  }
+});
+obj.dispatchEvent(event);
+ +

規格

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG','#interface-customevent','CustomEvent()')}}{{Spec2('DOM WHATWG')}}Initial definition.
+ +

瀏覽器支援度

+ + + +

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

+ +

添加額外參數

+ +

在 Internet Explorer 9 或更高的版本,你可以用以下的方法給 CustomEvent() constructor 添加額外參數

+ +
(function () {
+  function CustomEvent ( event, params ) {
+    params = params || { bubbles: false, cancelable: false, detail: undefined };
+    var evt = document.createEvent( 'CustomEvent' );
+    evt.initCustomEvent( event, params.bubbles, params.cancelable, params.detail );
+    return evt;
+   }
+
+  CustomEvent.prototype = window.Event.prototype;
+
+  window.CustomEvent = CustomEvent;
+})();
+ +

延伸閱讀

+ + diff --git a/files/zh-tw/web/api/customevent/index.html b/files/zh-tw/web/api/customevent/index.html new file mode 100644 index 0000000000..e35df7df2e --- /dev/null +++ b/files/zh-tw/web/api/customevent/index.html @@ -0,0 +1,88 @@ +--- +title: CustomEvent +slug: Web/API/CustomEvent +tags: + - 待翻譯 +translation_of: Web/API/CustomEvent +--- +

{{APIRef("DOM")}}

+ +

CustomEvent interface 是應用程式為了任意目的所初始化的事件。

+ +

建構式

+ +
+
{{domxref("CustomEvent.CustomEvent", "CustomEvent()")}}
+
建立一個 CustomEvent。
+
+ +

屬性

+ +
+
{{domxref("CustomEvent.detail")}} {{readonlyinline}}
+
初始化事件時傳送的任意資料。
+
+ +

此介面繼承了其父介面 {{domxref("Event")}} 的屬性:

+ +

{{Page("/zh-TW/docs/Web/API/Event", "屬性")}}

+ +

方法

+ +
+
{{domxref("CustomEvent.initCustomEvent()")}} {{deprecated_inline}}
+
+

初始化一 CustomEvent object。若該事件已經被觸發,則不會進行任何動作。

+
+
+ +

此介面繼承了其父介面 {{domxref("Event")}} 的方法:

+ +

{{Page("/zh-TW/docs/Web/API/Event", "方法")}}

+ +

規格

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG','#interface-customevent','CustomEvent')}}{{Spec2('DOM WHATWG')}}原始定義
+ +

瀏覽器兼容性

+ + + +

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

+ +

Firing from privileged code to non-privileged code

+ +

當要從 privileged code (像是插件)到非 privileged code (例如網頁)執行 CustomEvent ,你必須要考慮這之間的安全性。Firefox 和其他 Gecko 應用會對此有所限制。雖然這可以自動防止安全漏洞發生,但也可能導致您的程式碼沒辦法正常執行。

+ +

When creating a CustomEvent object, you must create the object from the same window as you're going to fire against. The detail attribute of your CustomEvent will be subject to the same restrictions. String and Array values will be readable by the content without restrictions, but custom Objects will not. If using a custom Object, you will need to define the attributes of that object that are readable from the content script using Components.utils.cloneInto().

+ +
// doc is a reference to the content document
+function dispatchCustomEvent(doc) {
+  var eventDetail = Components.utils.cloneInto({foo: 'bar'}, doc.defaultView);
+  var myEvent = doc.defaultView.CustomEvent("mytype", eventDetail);
+  doc.dispatchEvent(myEvent);
+}
+ +

Note that exposing a function will allow the content script to run it with chrome privileges, which can open a security vulnerability.

+ +

參見

+ + diff --git a/files/zh-tw/web/api/datatransfer/index.html b/files/zh-tw/web/api/datatransfer/index.html new file mode 100644 index 0000000000..d202c3b876 --- /dev/null +++ b/files/zh-tw/web/api/datatransfer/index.html @@ -0,0 +1,204 @@ +--- +title: DataTransfer +slug: Web/API/DataTransfer +translation_of: Web/API/DataTransfer +--- +
{{APIRef("HTML Drag and Drop API")}}
+ +

DataTransfer 物件被用來保存使用者於拖放操作過程中的資料,其中可能包含了一至多項資料以及多種資料類型。要瞭解拖放操作的更多細節,請參考拖放操作一文。

+ +

DataTransfer 只能是每一種 {{domxref("DragEvent")}} 型別物件的共同屬性-{{domxref("DragEvent.dataTransfer","dataTransfer")}},不能夠被單獨建立。

+ +

屬性

+ +

Standard properties

+ +
+
{{domxref("DataTransfer.dropEffect")}}
+
Gets the type of drag-and-drop operation currently selected or sets the operation to a new type. The value must be none copy link or move.
+
{{domxref("DataTransfer.effectAllowed")}}
+
Provides all of the types of operations that are possible. Must be one of none, copy, copyLink, copyMove, link, linkMove, move, all or uninitialized.
+
{{domxref("DataTransfer.files")}}
+
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.
+
{{domxref("DataTransfer.items")}} {{readonlyInline}}
+
Gives a {{domxref("DataTransferItemList")}} object which is a list of all of the drag data.
+
{{domxref("DataTransfer.types")}} {{readonlyInline}}
+
An array of {{domxref("DOMString","strings")}} giving the formats that were set in the {{event("dragstart")}} event.
+
+ +

Gecko properties

+ +

{{SeeCompatTable}}

+ +
Note: All of the properties in this section are Gecko-specific.
+ +
+
{{domxref("DataTransfer.mozCursor")}}
+
Gives the drag cursor's state. This is primarily used to control the cursor during tab drags.
+
{{domxref("DataTransfer.mozItemCount")}} {{readonlyInline}}
+
Gives the number of items in the drag operation.
+
{{domxref("DataTransfer.mozSourceNode")}} {{readonlyInline}}
+
The {{ domxref("Node") }} over which the mouse cursor was located when the button was pressed to initiate the drag operation. This value is null for external drags or if the caller can't access the node.
+
{{domxref("DataTransfer.mozUserCancelled")}} {{readonlyInline}}
+
This property applies only to the dragend event, and is true if the user canceled the drag operation by pressing escape. It will be false in all other cases, including if the drag failed for any other reason, for instance due to a drop over an invalid location.
+
+ +

方法

+ +

Standard methods

+ +
+
{{domxref("DataTransfer.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.
+
{{domxref("DataTransfer.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.
+
{{domxref("DataTransfer.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.
+
{{domxref("DataTransfer.setDragImage()")}}
+
Set the image to be used for dragging if a custom one is desired.
+
+ +

Gecko methods

+ +

{{SeeCompatTable}}

+ +
Note: All of the methods in this section are Gecko-specific.
+ +
+
{{domxref("DataTransfer.addElement()")}}
+
Sets the drag source to the given element.
+
{{domxref("DataTransfer.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.
+
{{domxref("DataTransfer.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.
+
{{domxref("DataTransfer.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.
+
{{domxref("DataTransfer.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.
+
+ +

範例

+ +

Every method and property listed in this document has its own reference page and each reference page either directly includes an example of the interface or has a link to an example.

+ +

規範

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'interaction.html#datatransfer','DataTransfer')}}{{Spec2('HTML WHATWG')}}mozCursor, mozItemCount, mozSourceNode, mozUserCancelled, addElement(), mozClearDataAt(), mozGetDataAt(), mozSetDataAt() and mozTypesAt are Gecko specific.
{{SpecName('HTML5.1', 'editing.html#the-datatransfer-interface','DataTransfer')}}{{Spec2('HTML5.1')}}Not included in W3C HTML5 {{Spec2('HTML5 W3C')}}
+ +

瀏覽器相容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support4{{CompatVersionUnknown}}3.5 [2]
+ {{CompatGeckoDesktop(52)}}[3]
10 [1] [2]123.1 [2]
{{domxref("DataTransfer.items", "items")}} property4{{CompatVersionUnknown}}50{{CompatNo}}12{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewChrome for AndroidEdgeFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+ {{CompatGeckoMobile(52)}}[3]
{{CompatNo}}{{CompatIE("10")}}[1][2]{{CompatNo}}{{CompatNo}}
{{domxref("DataTransfer.items", "items")}} property{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatGeckoMobile(50)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] Partial support refers to not supporting {{domxref("DataTransfer.setDragImage()")}} [CanIUse.com].

+ +

[2] Does not support {{domxref("DataTransfer.items")}} property.

+ +

[3] As of Firefox 52, the {{domxref("DataTransfer.types")}} property returns a frozen array of {{domxref("DOMString")}}s as per spec, rather than a {{domxref("DOMStringList")}}.

+ +

參見

+ + diff --git a/files/zh-tw/web/api/detecting_device_orientation/index.html b/files/zh-tw/web/api/detecting_device_orientation/index.html new file mode 100644 index 0000000000..d81307ba57 --- /dev/null +++ b/files/zh-tw/web/api/detecting_device_orientation/index.html @@ -0,0 +1,278 @@ +--- +title: 偵測裝置方向 +slug: Web/API/Detecting_device_orientation +translation_of: Web/API/Detecting_device_orientation +--- +
{{SeeCompatTable}}
+ +

目前支援 Web 的裝置,已有越來越多可偵測本身的方向(Orientation);也就是說,這些裝置可根據重力牽引的相對關係而改變其畫面方向,同時回報該筆資料。特別是如行動電話的手持式裝置,同樣會判斷這種資訊而自動旋轉其畫面。如此除了能保持正向畫面之外,裝置橫放時亦能以寬螢幕呈現網頁內容。

+ +

現有 2 組 JavaScript 事件可處理方向資訊。第一個是 {{domxref("DeviceOrientationEvent")}} 事件。只要加速規偵測到裝置方向的變化,隨即送出此事件。在接收並處理這些方向事件所回報的資料之後,即可針對使用者移動裝置所造成的方向與高度變化,確實做出回應。

+ +

第二個為 {{domxref("DeviceMotionEvent")}} 事件。只要加速過程產生變化,隨即送出該事件。此事件用以監聽加速過程的變化,因此不同於 {{domxref("DeviceOrientationEvent")}} 的方向變化。如筆記型電腦中的感測器,一般均能夠偵測 {{domxref("DeviceMotionEvent")}} 而保護移動中的儲存裝置。{{domxref("DeviceOrientationEvent")}} 則較常用於行動裝置。

+ +

處理方向事件

+ +

若要開始接收方向變換的情形,只要監聽 {{event("deviceorientation")}} 事件即可:

+ +
+

Note: gyronorm.js is a polyfill for normalizing the accelerometer and gyroscope data on mobile devices. This is useful for overcoming some of the differences in device support for device orientation.

+
+ +
window.addEventListener("deviceorientation", handleOrientation, true);
+
+ +

在註冊了事件監聽器(Event listener。本範例使用 handleOrientation() 函式)之後,將以更新過的方向資料而定期呼叫你的監聽器函式。

+ +

方向事件共有 4 組值:

+ + + +

事件處理器(Event handler)函式則如下列:

+ +
function handleOrientation(event) {
+  var absolute = event.absolute;
+  var alpha    = event.alpha;
+  var beta     = event.beta;
+  var gamma    = event.gamma;
+
+  // Do stuff with the new orientation data
+}
+
+ +

方向值說明

+ +

所回報的各個軸線值,均是以標準座標而呈現對應各軸線的旋轉量 (Amount of rotation)。可參閱下方所提供的方向與動向資料說明文章以獲得詳細資訊。

+ + + +

方向範例

+ +

只要瀏覽器支援 {{event("deviceorientation")}} 事件,且該執行裝置可偵測自己的方向,均可使用此範例。

+ +

先想像花園裡有 1 顆球:

+ +
<div class="garden">
+  <div class="ball"></div>
+</div>
+
+<pre class="output"></pre>
+
+ +

這座花園為 200 像素寬(對,一座小花園),球就位在正中央:

+ +
.garden {
+  position: relative;
+  width : 200px;
+  height: 200px;
+  border: 5px solid #CCC;
+  border-radius: 10px;
+}
+
+.ball {
+  position: absolute;
+  top   : 90px;
+  left  : 90px;
+  width : 20px;
+  height: 20px;
+  background: green;
+  border-radius: 100%;
+}
+
+ +

現在只要移動裝置,球也會跟著移動:

+ +
var ball   = document.querySelector('.ball');
+var garden = document.querySelector('.garden');
+var output = document.querySelector('.output');
+
+var maxX = garden.clientWidth  - ball.clientWidth;
+var maxY = garden.clientHeight - ball.clientHeight;
+
+function handleOrientation(event) {
+  var x = event.beta;  // In degree in the range [-180,180]
+  var y = event.gamma; // In degree in the range [-90,90]
+
+  output.innerHTML  = "beta : " + x + "\n";
+  output.innerHTML += "gamma: " + y + "\n";
+
+  // Because we don't want to have the device upside down
+  // We constrain the x value to the range [-90,90]
+  if (x >  90) { x =  90};
+  if (x < -90) { x = -90};
+
+  // To make computation easier we shift the range of
+  // x and y to [0,180]
+  x += 90;
+  y += 90;
+
+  // 10 is half the size of the ball
+  // It center the positioning point to the center of the ball
+  ball.style.top  = (maxX*x/180 - 10) + "px";
+  ball.style.left = (maxY*y/180 - 10) + "px";
+}
+
+window.addEventListener('deviceorientation', handleOrientation);
+
+ +

這裡有即時結果 (若無法顯示,可至本文右上角切換回英文原文觀看):

+ +
{{EmbedLiveSample('Orientation_example', '230', '260')}}
+ +
+

警告:Chrome 與 Firefox 處理角度的方式不同,所以某些軸線可能方向顛倒。

+
+ +

處理動向事件

+ +

動向事件與方向事件的處理方式完全相同,但動向事件擁有自己的名稱:{{event("devicemotion")}}

+ +
window.addEventListener("devicemotion", handleMotion, true);
+ +

真正改變的是由 {{domxref("DeviceMotionEvent")}} 物件所提供的資訊;且該物件又作為 HandleMotion 函式的參數。

+ +

動向事件共有 4 組屬性:

+ + + +

動向值說明

+ +

{{domxref("DeviceMotionEvent")}} 物件將提供「裝置位置與方向的變化速度」的相關資訊,並根據 3 組軸線 (可參閱方向與動向資料說明的細節) 提供變化情形。

+ +

針對 {{domxref("DeviceMotionEvent.acceleration","acceleration")}} 與 {{domxref("DeviceMotionEvent.accelerationIncludingGravity","accelerationIncludingGravity")}},這些軸線將對應:

+ + + +

針對稍有差異的 {{domxref("DeviceMotionEvent.rotationRate","rotationRate")}},則資訊將對應:

+ + + +

最後,{{domxref("DeviceMotionEvent.interval","interval")}} 代表以毫秒(Millisecond)為單位的時間間隔,是裝置取得資料的頻率。

+ +

規範

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Device Orientation')}}{{Spec2('Device Orientation')}}Initial specification.
+ +

瀏覽器相容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
{{domxref("DeviceOrientationEvent")}}7.0{{CompatVersionUnknown}}3.6[1]
+ 6
{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
{{domxref("DeviceMotionEvent")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}6{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
{{domxref("DeviceOrientationEvent")}}3.0{{CompatVersionUnknown}}3.6[1]
+ 6
{{CompatNo}}{{CompatNo}}4.2
{{domxref("DeviceMotionEvent")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}6{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Firefox 3.6 to 5 supported mozOrientation versus the standard {{domxref("DeviceOrientationEvent")}} event.

+ +

參見

+ + diff --git a/files/zh-tw/web/api/devicemotionevent/index.html b/files/zh-tw/web/api/devicemotionevent/index.html new file mode 100644 index 0000000000..f21723a1e3 --- /dev/null +++ b/files/zh-tw/web/api/devicemotionevent/index.html @@ -0,0 +1,116 @@ +--- +title: DeviceMotionEvent +slug: Web/API/DeviceMotionEvent +translation_of: Web/API/DeviceMotionEvent +--- +

{{apiref("Device Orientation Events")}}{{SeeCompatTable}}

+ +

概要

+ +

DeviceMotionEvent 提供了網頁開發者關於裝置位置及旋轉方向改變時的速度資訊。

+ +
+

Warning: Currently, Firefox and Chrome does not handle the coordinates the same way. Take care about this while using them.

+
+ +

屬性

+ +
+
{{domxref("DeviceMotionEvent.acceleration")}} {{readonlyinline}}
+
An object giving the acceleration of the device on the three axis X, Y and Z. Acceleration is expressed in m/s2.
+
{{domxref("DeviceMotionEvent.accelerationIncludingGravity")}} {{readonlyinline}}
+
An object giving the acceleration of the device on the three axis X, Y and Z with the effect of gravity. Acceleration is expressed in m/s2.
+
{{domxref("DeviceMotionEvent.rotationRate")}} {{readonlyinline}}
+
An object giving the rate of change of the device's orientation on the three orientation axis alpha, beta and gamma. Rotation rate is express in degrees per seconds.
+
{{domxref("DeviceMotionEvent.interval")}} {{readonlyinline}}
+
A number representing the interval of time, in milliseconds, at which data is obtained from the device.
+
+ +

範例

+ +
window.addEventListener('devicemotion', function(event) {
+  console.log(event.acceleration.x + ' m/s2');
+});
+ +

規範

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Device Orientation')}}{{Spec2('Device Orientation')}}Initial specification.
+ +

瀏覽器相容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{ CompatVersionUnknown() }}{{CompatVersionUnknown}}{{CompatGeckoDesktop("6")}}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{ CompatVersionUnknown() }}{{CompatVersionUnknown}}{{CompatGeckoMobile("6")}}{{ CompatNo() }}{{ CompatNo() }}4.2
+
+ +

參見

+ + diff --git a/files/zh-tw/web/api/deviceorientationevent/index.html b/files/zh-tw/web/api/deviceorientationevent/index.html new file mode 100644 index 0000000000..38bc8f5261 --- /dev/null +++ b/files/zh-tw/web/api/deviceorientationevent/index.html @@ -0,0 +1,122 @@ +--- +title: DeviceOrientationEvent +slug: Web/API/DeviceOrientationEvent +translation_of: Web/API/DeviceOrientationEvent +--- +

{{apiref("Device Orientation Events")}}{{SeeCompatTable}}

+ +

DeviceOrientationEvent 提供了網頁開發者關於目前瀏覽頁面之裝置的物理旋轉方向資訊。

+ +
+

Warning: Currently, Firefox and Chrome do not handle the coordinates the same way. Take care about this while using them.

+
+ +

屬性

+ +
+
{{domxref("DeviceOrientationEvent.absolute")}} {{readonlyinline}}
+
A boolean that indicates whether or not the device is providing orientation data absolutely.
+
{{domxref("DeviceOrientationEvent.alpha")}} {{readonlyinline}}
+
A number representing the motion of the device around the z axis, express in degrees with values ranging from 0 to 360
+
{{domxref("DeviceOrientationEvent.beta")}} {{readonlyinline}}
+
A number representing the motion of the device around the x axis, express in degrees with values ranging from -180 to 180. This represents a front to back motion of the device.
+
{{domxref("DeviceOrientationEvent.gamma")}} {{readonlyinline}}
+
A number representing the motion of the device around the y axis, express in degrees with values ranging from -90 to 90. This represents a left to right motion of the device.
+
+ +

範例

+ +
window.addEventListener('deviceorientation', function(event) {
+  console.log(event.alpha + ' : ' + event.beta + ' : ' + event.gamma);
+});
+ +

規範

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Device Orientation')}}{{Spec2('Device Orientation')}}Initial specification.
+ +

瀏覽器相容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support7.0 [1]{{CompatVersionUnknown}}6 [2]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support3.0{{CompatVersionUnknown}} [1]{{CompatVersionUnknown}}6 [2]{{CompatNo}}{{CompatNo}}4.2{{CompatVersionUnknown}} [1]
+
+ +

[1] Before version 50, Chrome provided absolute values instead of relative values for this event. Developers still needing absolute values may use the {{domxref("ondeviceorientationabsolute")}} event.

+ +

[2] Firefox 3.6, 4, and 5 supported mozOrientation instead of the standard DeviceOrientationEvent interface

+ +

參見

+ + diff --git a/files/zh-tw/web/api/document.createtreewalker/index.html b/files/zh-tw/web/api/document.createtreewalker/index.html new file mode 100644 index 0000000000..9e74411a14 --- /dev/null +++ b/files/zh-tw/web/api/document.createtreewalker/index.html @@ -0,0 +1,224 @@ +--- +title: Document.createTreeWalker() +slug: Web/API/document.createTreeWalker +translation_of: Web/API/Document/createTreeWalker +--- +
+ {{ApiRef("Document")}}
+

Document.createTreeWalker() 方法,能建立一個 {{domxref("TreeWalker")}} 物件並傳回.

+

語法

+
treeWalker = document.createTreeWalker(root, whatToShow, filter, entityReferenceExpansion);
+
+

參數

+
+
+ root
+
+ 是這個 {{domxref("TreeWalker")}} 遍歷的根節點(root {{domxref("Node")}}). Typically this will be an element owned by the document.
+
+ whatToShow {{optional_inline}}
+
+ Is an optional unsigned long representing a bitmask created by combining the constant properties of NodeFilter. 它是一種方便的方法,用來過濾某些類型的節點。 It defaults to 0xFFFFFFFF representing the SHOW_ALL constant.
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constant數值說明
NodeFilter.SHOW_ALL-1 (that is the max value of unsigned long)顯示所有節點.
NodeFilter.SHOW_ATTRIBUTE {{deprecated_inline}}2Shows attribute {{ domxref("Attr") }} nodes. This is meaningful only when creating a {{ domxref("TreeWalker") }} with an {{ domxref("Attr") }} node as its root; in this case, it means that the attribute node will appear in the first position of the iteration or traversal. Since attributes are never children of other nodes, they do not appear when traversing over the document tree.
NodeFilter.SHOW_CDATA_SECTION {{deprecated_inline}}8Shows {{ domxref("CDATASection") }} nodes.
NodeFilter.SHOW_COMMENT128Shows {{ domxref("Comment") }} nodes.
NodeFilter.SHOW_DOCUMENT256Shows {{ domxref("Document") }} nodes.
NodeFilter.SHOW_DOCUMENT_FRAGMENT1024Shows {{ domxref("DocumentFragment") }} nodes.
NodeFilter.SHOW_DOCUMENT_TYPE512Shows {{ domxref("DocumentType") }} nodes.
NodeFilter.SHOW_ELEMENT1Shows {{ domxref("Element") }} nodes.
NodeFilter.SHOW_ENTITY {{deprecated_inline}}32Shows {{ domxref("Entity") }} nodes. This is meaningful only when creating a {{ domxref("TreeWalker") }} with an {{ domxref("Entity") }} node as its root; in this case, it means that the {{ domxref("Entity") }} node will appear in the first position of the traversal. Since entities are not part of the document tree, they do not appear when traversing over the document tree.
NodeFilter.SHOW_ENTITY_REFERENCE {{deprecated_inline}}16Shows {{ domxref("EntityReference") }} nodes.
NodeFilter.SHOW_NOTATION {{deprecated_inline}}2048Shows {{ domxref("Notation") }} nodes. This is meaningful only when creating a {{ domxref("TreeWalker") }} with a {{ domxref("Notation") }} node as its root; in this case, it means that the {{ domxref("Notation") }} node will appear in the first position of the traversal. Since entities are not part of the document tree, they do not appear when traversing over the document tree.
NodeFilter.SHOW_PROCESSING_INSTRUCTION64Shows {{ domxref("ProcessingInstruction") }} nodes.
NodeFilter.SHOW_TEXT4顯示文字節點({{ domxref("Text") }} nodes).
+
+
+ filter {{optional_inline}}
+
+ 是一個可選的 {{domxref("NodeFilter")}}, 這是一個物件有著 acceptNode 方法, 這方法被 {{domxref("TreeWalker")}} 呼叫來決定是否接受通過 whatToShow 檢查的節點.
+
+ entityReferenceExpansion {{optional_inline}} {{obsolete_inline}}
+
+ Is a {{domxref("Boolean")}} flag indicating if when discarding an {{domxref("EntityReference")}} its whole sub-tree must be discarded at the same time.
+
+

Example

+

The following example goes through all nodes in the body, reduces the set of nodes to elements, simply passes through as acceptable each node (it could reduce the set in the acceptNode() method instead), and then makes use of tree walker iterator that is created to advance through the nodes (now all elements) and push them into an array.

+
var treeWalker = document.createTreeWalker(
+  document.body,
+  NodeFilter.SHOW_ELEMENT,
+  { acceptNode: function(node) { return NodeFilter.FILTER_ACCEPT; } },
+  false
+);
+
+var nodeList = [];
+
+while(treeWalker.nextNode()) nodeList.push(treeWalker.currentNode);
+
+

Specifications

+ + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-document-createtreewalker', 'Document.createTreeWalker')}}{{Spec2('DOM WHATWG')}}Removed the expandEntityReferences parameter.
+ Made the whatToShow and filter parameters optionals.
{{SpecName('DOM2 Traversal_Range', 'traversal.html#NodeIteratorFactory-createTreeWalker', 'Document.createTreeWalker')}}{{Spec2('DOM2 Traversal_Range')}}Initial definition.
+

Browser compatibility

+

{{CompatibilityTable}}

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1.0{{CompatGeckoDesktop("1.8.1")}}9.09.03.0
whatToShow and filter optional1.0{{CompatGeckoDesktop("12")}}{{CompatNo}}{{CompatVersionUnknown}}3.0
expandEntityReferences {{obsolete_inline}}1.0{{CompatGeckoDesktop("1.8.1")}}
+ Removed in {{CompatGeckoDesktop("12")}}
9.09.03.0
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatGeckoMobile("1.8.1")}}{{CompatVersionUnknown}}9.03.0
whatToShow and filter optional{{CompatVersionUnknown}}{{CompatGeckoDesktop("12")}}{{CompatNo}}{{CompatVersionUnknown}}3.0
expandEntityReferences {{obsolete_inline}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.8.1")}}
+ Removed in {{CompatGeckoDesktop("12")}}
{{CompatVersionUnknown}}9.03.0
+
+

See also

+ diff --git a/files/zh-tw/web/api/document/body/index.html b/files/zh-tw/web/api/document/body/index.html new file mode 100644 index 0000000000..a33d2a7901 --- /dev/null +++ b/files/zh-tw/web/api/document/body/index.html @@ -0,0 +1,128 @@ +--- +title: Document.body +slug: Web/API/Document/body +translation_of: Web/API/Document/body +--- +
{{APIRef("DOM")}}
+ +

回傳目前文件的 {{HTMLElement("body")}} 或 {{HTMLElement("frameset")}} 節點,如元素不存在則回傳 null

+ +

語法

+ +
var objRef = document.body;
+document.body = objRef;
+ +

範例

+ +
// in 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"
+
+ +

備註

+ +

document.body is the element that contains the content for the document. In documents with <body> contents, returns the <body> element, and in frameset documents, this returns the outermost <frameset> element.

+ +

Though body is settable, setting a new body on a document will effectively remove all the current children of the existing <body> element.

+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG','dom.html#dom-document-body','Document.body')}}{{Spec2('HTML WHATWG')}} 
{{SpecName('HTML5.1','dom.html#dom-document-body','Document.body')}}{{Spec2('HTML5.1')}} 
{{SpecName('HTML5 W3C','dom.html#dom-document-body','Document.body')}}{{Spec2('HTML5 W3C')}} 
{{SpecName('DOM2 HTML','html.html#ID-56360201','Document.body')}}{{Spec2('DOM2 HTML')}} 
{{SpecName('DOM1','level-one-html.html#attribute-body','Document.body')}}{{Spec2('DOM1')}}Initial definition.
+ +

瀏覽器相容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1{{CompatVersionUnknown}}269.6 (possibly earlier)4 (possibly earlier)
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}5 (probably earlier)
+
+ +

參見

+ + diff --git a/files/zh-tw/web/api/document/createdocumentfragment/index.html b/files/zh-tw/web/api/document/createdocumentfragment/index.html new file mode 100644 index 0000000000..efdd4c31e6 --- /dev/null +++ b/files/zh-tw/web/api/document/createdocumentfragment/index.html @@ -0,0 +1,136 @@ +--- +title: Document.createDocumentFragment() +slug: Web/API/Document/createDocumentFragment +tags: + - API + - DOM + - 參考 + - 文本片段 + - 方法 +translation_of: Web/API/Document/createDocumentFragment +--- +
{{ApiRef("DOM")}}
+ +

建立新的 {{domxref("DocumentFragment")}}.

+ +

語法

+ +
var fragment = document.createDocumentFragment();
+
+ +

fragment 是 {{domxref("DocumentFragment")}} 的一個參考物件。

+ +

描述

+ +

DocumentFragments 是 DOM 節點(Nodes)。他們不會成為 DOM主幹的一部份。最常見的作法是先建立文本片段 (document fragment),然後將元素 (element) 加入文本片段中,最後再將文本片段加入 DOM 樹中。在 DOM 樹中,文本片段將會被他所有的子元素取代。

+ +

正因為文本片段是存在記憶體中,並且不是 DOM 主幹的一部分,增加子元素並不會導致網頁重刷 (reflow)(重新計算元素的位置和幾何)。因此採用文本片段通常會有比較好的效能表現 (better performance)。

+ +

舉例

+ +

這個例子中用清單來呈現主流瀏覽器。

+ +

HTML

+ +
<ul id="ul">
+</ul>
+ +

JavaScript

+ +
var element  = document.getElementById('ul'); // assuming ul exists
+var fragment = document.createDocumentFragment();
+var browsers = ['Firefox', 'Chrome', 'Opera',
+    'Safari', 'Internet Explorer'];
+
+browsers.forEach(function(browser) {
+    var li = document.createElement('li');
+    li.textContent = browser;
+    fragment.appendChild(li);
+});
+
+element.appendChild(fragment);
+
+ +

結果

+ +

jsfiddle 上看範例結果。

+ +

規格

+ + + + + + + + + + + + + + + + +
規格狀態註解
{{SpecName('DOM WHATWG', '#dom-document-createdocumentfragment', 'Document.createDocumentFragment()')}}{{Spec2('DOM WHATWG')}}Initial definition in the DOM 1 specification.
+ +

瀏覽器相容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
特色Firefox (Gecko)ChromeEdgeInternet ExplorerOperaSafari
基礎支援{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
特色Firefox Mobile (Gecko)AndroidEdgeIE MobileOpera MobileSafari Mobile
基礎支援{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

更多參考

+ + diff --git a/files/zh-tw/web/api/document/createelement/index.html b/files/zh-tw/web/api/document/createelement/index.html new file mode 100644 index 0000000000..2d847004cc --- /dev/null +++ b/files/zh-tw/web/api/document/createelement/index.html @@ -0,0 +1,179 @@ +--- +title: Document.createElement() +slug: Web/API/Document/createElement +translation_of: Web/API/Document/createElement +--- +
{{APIRef("DOM")}}
+ +

HTML 文件中,Document.createElement() 方法可以依指定的標籤名稱(tagName)建立 HTML 元素,或是在未定義標籤名稱下建立一個 {{domxref("HTMLUnknownElement")}}。在 XUL 文件中,Document.createElement() 將會建立指定的 XUL 元素。而在其它文件,則會建立一個 namespace URI 為 null 的元素。

+ +

若要明確指定元素的 namespace URI,請使用 document.createElementNS()

+ +

語法

+ +
var element = document.createElement(tagName[, options]);
+
+ +

參數

+ +
+
tagName
+
一個指定類型給所創建的元素的字串。{{domxref("Node.nodeName", "nodeName")}} 創建的元素由 tagName 的值初始,不要使用吻合名稱(例如 "html:a")。當該方法在 HTML 文件中被調用時,createElement() 會先將 tagName 轉化為小寫後再創建元素。在 Firefox、Opera 和 Chrome,createElement(null) 與 createElement("null") 作用相同。
+
options{{optional_inline}}
+
選擇性 ElementCreationOptions 物件包含一個屬性 is,它的值是先前使用customElements.define() 所定義的自定義元素的標籤名稱。為了與以前的 自定義元素規範 相容,一些瀏覽器將允許你在此傳遞一個字串而非物件,其字串的值就是自定義元件的標籤名稱。了解更多訊息以及如何使用此參數,可以參閱 擴展原生 HTML 元素 。
+
新元素將被賦予一個 is 屬性,其值就是自定義元素的標籤名稱。自定義元素算是實驗中的功能,因此目前只作用於部分瀏覽器中。
+
+ +

回傳值

+ +

一個新的 Element.

+ +

範例

+ +

這邊創建一個新的 <div> ,並將它插入到 ID div1 之前。

+ +

HTML

+ +
<!DOCTYPE html>
+<html>
+<head>
+  <title>||Working with elements||</title>
+</head>
+<body>
+  <div id="div1">The text above has been created dynamically.</div>
+</body>
+</html>
+
+ +

JavaScript

+ +
document.body.onload = addElement;
+
+function addElement () {
+  // create a new div element
+  // and give it some content
+  var newDiv = document.createElement("div");
+  var newContent = document.createTextNode("Hi there and greetings!");
+  newDiv.appendChild(newContent); //add the text node to the newly created div.
+
+  // add the newly created element and its content into the DOM
+  var currentDiv = document.getElementById("div1");
+  document.body.insertBefore(newDiv, currentDiv);
+}
+ +

{{EmbedLiveSample("Example", 500, 50)}}

+ +

規範

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', "#dom-document-createelement", "Document.createElement")}}{{Spec2('DOM WHATWG')}}
+ +

瀏覽器相容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}[1][2]{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
options argument{{CompatVersionUnknown}}[3]{{CompatUnknown}}{{CompatGeckoDesktop(50)}}[4][5]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
options argument{{CompatVersionUnknown}}{{CompatVersionUnknown}}[3]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}[3]
+
+ +

[1] Starting with Gecko 22.0 {{geckoRelease("22.0")}} createElement() no longer uses the {{domxref("HTMLSpanElement")}} interface when the argument is "bgsounds", "multicol", or "image".  Instead, HTMLUnknownElement is used for "bgsound" and "multicol" and {{domxref("HTMLElement")}} HTMLElement is used for "image".

+ +

[2] The Gecko implementation of createElement doesn't conform to the DOM spec for XUL and XHTML documents: localName and namespaceURI are not set to null on the created element. See {{ Bug(280692) }} for details.

+ +

[3] In previous versions of the specification, this argument was just a string whose value was the custom element's tag name. For example: document.createElement("button", "custom-button") rather than document.createElement("button", {id: "custom-button"}). For the sake of backwards compatibility, Chrome accepts both forms.

+ +

[4] See [3] above: like Chrome, Firefox accepts a string instead of an object here, but only from version 51 onwards. In version 50,  options must be an object.

+ +

[5] To experiment with custom elements in Firefox, you must set the dom.webcomponents.enabled and dom.webcomponents.customelements.enabled preferences to true.

+ +

參見

+ + diff --git a/files/zh-tw/web/api/document/createrange/index.html b/files/zh-tw/web/api/document/createrange/index.html new file mode 100644 index 0000000000..93703c54bb --- /dev/null +++ b/files/zh-tw/web/api/document/createrange/index.html @@ -0,0 +1,33 @@ +--- +title: Document.createRange() +slug: Web/API/Document/createRange +translation_of: Web/API/Document/createRange +--- +
{{APIRef("DOM")}}
+ +

回傳一 {{domxref("Range")}} 物件。

+ +

語法

+ +
range = document.createRange();
+
+ +

創造 range 為 {{domxref("Range")}} 物件.

+ +

示例

+ +
var range = document.createRange();
+
+range.setStart(startNode, startOffset);
+range.setEnd(endNode, endOffset);
+
+ +

註意

+ +

當  Range 被創建之後,必須先設定其範圍初始點及結束點, 才能使用大部分 {{domxref("Range")}} 所提供的方法。

+ +

規範

+ + diff --git a/files/zh-tw/web/api/document/createtextnode/index.html b/files/zh-tw/web/api/document/createtextnode/index.html new file mode 100644 index 0000000000..80d3d562b9 --- /dev/null +++ b/files/zh-tw/web/api/document/createtextnode/index.html @@ -0,0 +1,120 @@ +--- +title: Document.createTextNode() +slug: Web/API/Document/createTextNode +translation_of: Web/API/Document/createTextNode +--- +
{{APIRef("DOM")}}
+ +

創建一個新的文字節點.

+ +

Syntax

+ +
var text = document.createTextNode(data);
+
+ + + +

Example

+ +
<!DOCTYPE html>
+<html lang="en">
+<head>
+<title>createTextNode example</title>
+<script>
+function addTextNode(text) {
+  var newtext = document.createTextNode(text),
+      p1 = document.getElementById("p1");
+
+  p1.appendChild(newtext);
+}
+</script>
+</head>
+
+<body>
+  <button onclick="addTextNode('YES! ');">YES!</button>
+  <button onclick="addTextNode('NO! ');">NO!</button>
+  <button onclick="addTextNode('WE CAN! ');">WE CAN!</button>
+
+  <hr />
+
+  <p id="p1">First line of paragraph.</p>
+</body>
+</html>
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("DOM3 Core", "core.html#ID-1975348127", "Document.createTextNode()")}}{{Spec2("DOM3 Core")}}No change
{{SpecName("DOM2 Core", "core.html#ID-1975348127", "Document.createTextNode()")}}{{Spec2("DOM2 Core")}}Initial definition
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
diff --git a/files/zh-tw/web/api/document/defaultview/index.html b/files/zh-tw/web/api/document/defaultview/index.html new file mode 100644 index 0000000000..58905ebdeb --- /dev/null +++ b/files/zh-tw/web/api/document/defaultview/index.html @@ -0,0 +1,94 @@ +--- +title: Document.defaultView +slug: Web/API/Document/defaultView +translation_of: Web/API/Document/defaultView +--- +
{{ApiRef}}
+ +

在瀏覽器中,document.defaultView 屬性會指向一個目前 {{Glossary("Browsing_context", "document")}} 所屬的 {{domxref("Window", "window")}} 物件,若無則為 null

+ +

語法

+ +
var win = document.defaultView;
+ +

此為唯讀屬性。

+ +

規範

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#dom-document-defaultview', 'Document.defaultView')}}{{Spec2('HTML WHATWG')}}No change
{{SpecName('HTML5 W3C', 'browsers.html#dom-document-defaultview', 'Document.defaultView')}}{{Spec2('HTML5 W3C')}}Initial definition
+ +

瀏覽器相容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureFirefox (Gecko)ChromeEdgeInternet ExplorerEdgeOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatIE("9.0")}}0.10{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureFirefox Mobile (Gecko)AndroidEdgeIE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
diff --git a/files/zh-tw/web/api/document/designmode/index.html b/files/zh-tw/web/api/document/designmode/index.html new file mode 100644 index 0000000000..9f04db7952 --- /dev/null +++ b/files/zh-tw/web/api/document/designmode/index.html @@ -0,0 +1,114 @@ +--- +title: Document.designMode +slug: Web/API/Document/designMode +tags: + - API + - Document + - HTML DOM + - NeedsBrowserCompatibility + - Property +translation_of: Web/API/Document/designMode +--- +
{{ ApiRef() }}
+ +
 
+ +

概要

+ +

document.designMode 控制整個文件是否能夠編輯。可用的數值是 "on""off"。根據規範,這個屬性預設值為 "off"。Firefox 遵從這個標準。較早以前的 Chrome 和 IE 預設值是 "inherit"。從 Chrome 43 起,預設值是 「off」;不再支援「inherit」。在 IE6-10 中,數值為大寫英文字母。

+ +

語法

+ +
var mode = document.designMode;
+document.designMode = "on";
+document.designMode = "off";
+ +

範例

+ +

讓 {{HTMLElement("iframe")}} 的文件可以給使用者編輯:

+ +
iframeNode.contentDocument.designMode = "on";
+
+ +

規範

+ + + + + + + + + + + + + + +
規範狀態註解
{{SpecName('HTML WHATWG', '#making-entire-documents-editable:-the-designmode-idl-attribute', 'designMode')}}{{Spec2('HTML WHATWG')}}Initial definition.
+ +

瀏覽器相容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
功能ChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
基本支援{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
功能AndroidAndroid WebviewEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
基本支援{{CompatNo}}{{ CompatVersionUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

參考

+ + diff --git a/files/zh-tw/web/api/document/documentelement/index.html b/files/zh-tw/web/api/document/documentelement/index.html new file mode 100644 index 0000000000..aa3f5db82d --- /dev/null +++ b/files/zh-tw/web/api/document/documentelement/index.html @@ -0,0 +1,60 @@ +--- +title: Document.documentElement +slug: Web/API/Document/documentElement +translation_of: Web/API/Document/documentElement +--- +

{{ ApiRef("DOM") }}

+ +

Document.documentElement 會回傳目前文件({{domxref("document")}})中的根元素({{domxref("Element")}}),如:HTML 文件中的 <html> 元素。

+ +

語法

+ +
var element = document.documentElement;
+
+ +

範例

+ +
var rootElement = document.documentElement;
+var firstTier = rootElement.childNodes;
+
+// firstTier is the NodeList of the direct children of the root element
+for (var i = 0; i < firstTier.length; i++) {
+   // do something with each direct kid of the root element
+   // as firstTier[i]
+}
+ +

備註

+ +

對於所有非空的 HTML 文件, document.documentElement 將會是一個 {{HTMLElement("html")}}  元素 ; 對於所有非空的 XML 文件,document.documentElement 則會是文件的根元素。

+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
規範狀態 備註
{{SpecName('DOM2 Core','core.html#ID-87CD092','Document.documentElement')}}{{Spec2('DOM2 Core')}} 
{{SpecName('DOM3 Core','core.html#ID-87CD092','Document.documentElement')}}{{Spec2('DOM3 Core')}} 
{{SpecName('DOM4','#dom-document-documentelement','Document.documentElement')}}{{Spec2('DOM4')}} 
{{SpecName('DOM WHATWG','#dom-document-documentelement','Document.documentElement')}}{{Spec2('DOM WHATWG')}} 
diff --git a/files/zh-tw/web/api/document/execcommand/index.html b/files/zh-tw/web/api/document/execcommand/index.html new file mode 100644 index 0000000000..c06cd0d89c --- /dev/null +++ b/files/zh-tw/web/api/document/execcommand/index.html @@ -0,0 +1,172 @@ +--- +title: Document.execCommand() +slug: Web/API/Document/execCommand +translation_of: Web/API/Document/execCommand +--- +
{{ApiRef("DOM")}}{{Obsolete_header}}
+ +

當 HTML 文件(document)被切換到 designMode 時,它的 document 物件就會對外暴露 execCommand 方法作為操控目前可編輯區域的指令,譬如 form inputscontentEditable 元素。

+ +

多數的指令會作用在文件的選取 (粗體、斜體等),而其他則像是插入新的元素(新增一個連結)或是影響一整列的文字(縮排)。當使用 contentEditable 時, execCommand() 會作用在目前活躍的可編輯元素上。

+ +

語法

+ +
document.execCommand(aCommandName, aShowDefaultUI, aValueArgument)
+
+ +

回傳值

+ +

如果該指令不被支援或停用將回傳一個 false 的 {{jsxref('Boolean')}} 值。

+ +
+

備註:只有在使用者互動的部分回傳 true 。請不要嘗試在呼叫指令前使用回傳值來確認瀏覽器是否支援。

+
+ +

參數

+ +
+
aCommandName
+
一個 {{domxref("DOMString")}} 作為指定要執行的指令。所有可用的指令列表請見 {{anch("Commands")}} 。
+
aShowDefaultUI
+
一個 {{jsxref("Boolean")}} 作為指示是否顯示預設的使用者介面。 Mozilla 並未實作這項功能。
+
aValueArgument
+
針對需要提供輸入引數的指令,藉由 {{domxref("DOMString")}} 提供相關的資訊。譬如, insertImage 需要提供圖片的 URL 。若沒有引數的需求則可指定為 null
+
+ +

指令

+ +
+
backColor
+
變更文件的背景色彩。在 styleWithCss 模式中,它作用於涵蓋區域的背景色彩。這個指令需要提供一個 {{cssxref("<color>")}} 值字串作為引數值。請留意, Internet Explorer 使用這個指令作為設定文字的背景色彩。
+
bold
+
切換選取區域插入點的粗體與否。 Internet Explorer 使用 {{HTMLElement("strong")}} 標籤而不是 {{HTMLElement("b")}}.
+
ClearAuthenticationCache
+
清除所有快取中的驗證憑證。
+
contentReadOnly
+
使內容文件成為唯讀或可編輯。此指令需要提供布林值 true/false 作為引數值。(Internet Explorer 不支援)。
+
copy
+
複製目前選取的區域到剪貼簿。各個瀏覽器對於這個指令的行為可能有所差異且不斷變更。如果你有使用這個指令的情境,請先查閱相容性表格來決定如何使用。
+
createLink
+
對選取的區域建立超連結,僅限於有選取內容。需要提供一個 URI 字串值作為超連結的 href 。 URI 必須最少包含一個字元且可以是空白字元(Internet Explorer 會建立一個 null 值的連結)。
+
cut
+
移除目前選取的區域並複製到剪貼簿。各個瀏覽器對於這個指令的行為可能有所差異且不斷變更。使用細節請查閱相容性表格
+
decreaseFontSize
+
在選取區域或插入點的前後加入一個 {{HTMLElement("small")}} 標籤( Internet Explorer 不支援)
+
defaultParagraphSeparator
+
變更可編輯文字區域於新增段落時的段落分隔器。更多細節請查閱 產生 markup 的區別
+
delete
+
刪除目前選取的區域。
+
enableAbsolutePositionEditor
+
啟用或停用用於移動絕對定位元素的抓取器。這個指令在 Firefox 63 Beta/Dev 版本中預設停用({{bug(1449564)}})。
+
enableInlineTableEditing
+
啟用或停用表格的列 / 欄的插入及刪除。此指令在 Firefox 63 Beta/Dev 版本中預設停用 ({{bug(1449564)}})。
+
enableObjectResizing
+
啟用或停用圖片、表格、絕對定位元素、其他可重設大小物件的重設大小處理。此指令在 Firefox 63 Beta/Dev 版本中預設停用 ({{bug(1449564)}})。
+
fontName
+
變更選取區域或插入點的字型名稱。此指令需要字型名稱字串(如「Arial」)作為引數值。
+
fontSize
+
變更選取區域或插入點的字型大小。此指令需要 1-7 的整數作為引數值。
+
foreColor
+
變更選取區域或插入點的字型色彩。此指令需要十六進位的色彩字串作為引數值。
+
formatBlock
+
在目前選取區域的前後加入一個 HTML 區塊層級元素,若選取區域已經存在區塊元素則取代之。(在 Firefox 中, {{HTMLElement("blockquote")}} 是個例外——它會包裹住任何所包含的區塊元素)。 此指令需要一個標籤名稱字串作為引數值。幾乎所有區塊層級元素都可以使用(Internet Explorer and Edge 僅支援標題標籤 H1H6ADDRESSPRE 且必須由角括號包裹起來,譬如 "<H1>" )。
+
forwardDelete
+
刪除游標位置後的字元,等同於在 Windows 按下 Delete 鍵盤按鍵。
+
heading
+
在選取區域或插入點前後加入一個標題元素。此指令需要標籤名稱字串作為引數值(例:"H1", "H6" )(Internet Explorer 及 Safari 不支援)。
+
hiliteColor
+
變更選取區域或插入點的背景色彩。此指令需要一個色彩字串作為引數值。 useCSS 必須為 true 才能有作用(Internet Explorer 不支援)。
+
increaseFontSize
+
在選取區域或插入點前後加入一個 {{HTMLElement("big")}} 標題(Internet Explorer 不支援)。
+
indent
+
縮排選取區域或插入點所包含的列。在 Firefox ,如果選取的範圍跨越多列且不同的縮排層級,只有選取中最淺層縮排列的才會被縮排。
+
insertBrOnReturn
+
控制 Enter 按鍵按下時在目前區塊元素中插入 {{HTMLElement("br")}} 元素或分割成為兩個元素(Internet Explorer 不支援)。
+
insertHorizontalRule
+
在插入點插入一個 {{HTMLElement("hr")}} 元素或以它取代選取的內容。
+
insertHTML
+
在插入點插入一個 HTML 字串(會刪除選取內容)需要一個有效的 HTML 字串作為引數值(Internet Explorer 不支援)。
+
insertImage
+
在插入點插入一個圖片(會刪除選取內容)。需要一個 URL 字串作為圖片的 src 引數值。這個需求跟 createLink 的字串是一樣的。
+
insertOrderedList
+
在選取區域或插入點建立一個有序的清單
+
insertUnorderedList
+
在選取區域或插入點建立一個無序的清單
+
insertParagraph
+
在選取區域或目前列的前後插入段落(Internet Explorer 會在插入點插入段落並刪除選取的內容)。
+
insertText
+
在插入點處插入給予的純文字(選取內容將被刪除)。
+
italic
+
切換選取區域或插入點的斜體開關(Internet Explorer 使用 {{HTMLElement("em")}} 元素而不是 {{HTMLElement("i")}} )。
+
justifyCenter
+
置中對齊選取區域或插入點的內容。
+
justifyFull
+
左右對齊選取區域或插入點的內容。
+
justifyLeft
+
靠左對齊選取區域或插入點的內容。
+
justifyRight
+
靠右對齊選取區域或插入點的內容。
+
outdent
+
凸排選取區域或插入點所包含的列。
+
paste
+
在目前的插入點貼上剪貼簿的內容(取代目前選取的項目)。網頁內容無法使用。詳閱 [1]。
+
redo
+
復原上一個取消的指令。
+
removeFormat
+
移除目前選取區域所有的格式。
+
selectAll
+
選取可編輯區域的所有內容。
+
strikeThrough
+
切換選取區域或插入點的刪除線開關。
+
subscript
+
切換選取區域或插入點的 subscript 開關。
+
superscript
+
切換選取區域或插入點的 superscript 開關。
+
underline
+
切換選取區域或插入點的底線開關。
+
undo
+
取消上一個執行的指令。
+
unlink
+
從選取的超連結刪除錨點元素
+
useCSS {{Deprecated_inline}}
+
針對產生的 markup 使用 HTML 標籤或 CSS。此指令需要一個布林值 true/false 作為引數值。
+
注意:這個引述在邏輯上是反向的(舉例:使用 false 會使用 CSS ,反之使用 true 則使用 HTML 且 Internet Explorer 不支援。這個指令已經被棄用並由 styleWithCSS 取而代之。
+
styleWithCSS
+
取代 useCSS 的指令。 true 會在 markup 修改 / 產生 style 屬性, false 會產生展示用的元素。
+
+ +

範例

+ +

一個在 CodePen 上展示如果使用的範例。

+ +

規格

+ + + + + + + + + + + + + + +
規格狀態備註
execCommand
+ +

瀏覽器相容性

+ + + +

{{Compat("api.Document.execCommand")}}

+ +

相關資訊

+ + diff --git a/files/zh-tw/web/api/document/forms/index.html b/files/zh-tw/web/api/document/forms/index.html new file mode 100644 index 0000000000..769d80871c --- /dev/null +++ b/files/zh-tw/web/api/document/forms/index.html @@ -0,0 +1,75 @@ +--- +title: Document.forms +slug: Web/API/Document/forms +translation_of: Web/API/Document/forms +--- +
{{APIRef("DOM")}}
+ +

forms 屬性會回傳一個包含目前頁面中所有 {{HTMLElement("form")}} 元素的集合物件(型別為 {{domxref("HTMLCollection")}})。

+ +

語法

+ +
collection = document.forms;
+ +

範例:取得表單資訊

+ +
<!DOCTYPE html>
+<html lang="en">
+
+<head>
+<title>document.forms example</title>
+</head>
+
+<body>
+
+<form id="robby">
+  <input type="button" onclick="alert(document.forms[0].id);" value="robby's form" />
+</form>
+
+<form id="dave">
+  <input type="button" onclick="alert(document.forms[1].id);" value="dave's form" />
+</form>
+
+<form id="paul">
+  <input type="button" onclick="alert(document.forms[2].id);" value="paul's form" />
+</form>
+
+</body>
+</html>
+
+ +

範例 2:取得表單內的元素

+ +
var selectForm = document.forms[index];
+var selectFormElement = document.forms[index].elements[index];
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#dom-document-forms', 'Document.forms')}}{{ Spec2('HTML WHATWG') }} 
{{SpecName('DOM2 HTML', 'html.html#ID-1689064', 'Document.forms')}}{{ Spec2('DOM2 Events') }}Initial definition.
+ +

參見

+ + diff --git a/files/zh-tw/web/api/document/getelementsbyclassname/index.html b/files/zh-tw/web/api/document/getelementsbyclassname/index.html new file mode 100644 index 0000000000..b66647c82d --- /dev/null +++ b/files/zh-tw/web/api/document/getelementsbyclassname/index.html @@ -0,0 +1,127 @@ +--- +title: Document.getElementsByClassName() +slug: Web/API/Document/getElementsByClassName +tags: + - 待翻譯 +translation_of: Web/API/Document/getElementsByClassName +--- +

{{APIRef("DOM")}}

+ +

針對所有給定的 class 子元素,回傳類似陣列的物件。當呼叫 document 物件時,它會搜尋整個文件,包括根節點在內。你也可以在所有元素呼叫 {{domxref("Element.getElementsByClassName", "getElementsByClassName()")}},那它就只會回傳含有給定 class 的特定根元素的後代元素。

+ +

表達式

+ +
var elements = document.getElementsByClassName(names); // or:
+var elements = rootElement.getElementsByClassName(names);
+ + + +

範例

+ +

取得所有 class 為 “test” 的元素:

+ +
document.getElementsByClassName('test');
+ +

取得所有 class 為 “test” 和 “red” 的元素:

+ +
document.getElementsByClassName('red test');
+ +

取得所有在 id 為 '“main” 的元素裡 class 為 “test” 的元素:

+ +
document.getElementById('main').getElementsByClassName('test');
+ +

我們也可以藉由傳遞 {{ domxref("HTMLCollection") }} 為 this 來使用 Array.prototype 的方法。下面的例子將會找到所有 class 為 “test” 的 div 元素:

+ +
var testElements = document.getElementsByClassName('test');
+var testDivs = Array.prototype.filter.call(testElements, function(testElement){
+    return testElement.nodeName === 'DIV';
+});
+ +

取得 class 是 test 的元素

+ +

這是最常用的操作方法:

+ +
<!doctype html>
+<html>
+<head>
+    <meta charset="UTF-8">
+    <title>Document</title>
+</head>
+<body>
+    <div id="parent-id">
+        <p>hello word1</p>
+        <p class="test">hello word2</p>
+        <p>hello word3</p>
+        <p>hello word4</p>
+    </div>
+    <script>
+        var parentDOM = document.getElementById("parent-id");
+
+        var test=parentDOM.getElementsByClassName("test");//test is not target element
+        console.log(test);//HTMLCollection[1]
+
+        var testTarget=parentDOM.getElementsByClassName("test")[0];//year , this element is target
+        console.log(testTarget);//<p class="test">hello word2</p>
+    </script>
+</body>
+</html>
+ +

瀏覽器相容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatVersionUnknown() }}3.09.0{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

規範

+ + diff --git a/files/zh-tw/web/api/document/head/index.html b/files/zh-tw/web/api/document/head/index.html new file mode 100644 index 0000000000..7ecde675ea --- /dev/null +++ b/files/zh-tw/web/api/document/head/index.html @@ -0,0 +1,114 @@ +--- +title: Document.head +slug: Web/API/Document/head +translation_of: Web/API/Document/head +--- +

{{APIRef("DOM")}}

+ +

回傳當前文件的 {{HTMLElement("head")}} 元素。如果該文件有超過一個 <head> 元素,那只會回傳第一個 <head> 元素。

+ +

語法

+ +
var objRef = document.head;
+
+ +

範例

+ +
// in HTML: <head id="my-document-head">
+var aHead = document.head;
+
+alert(aHead.id); // "my-document-head";
+
+alert( document.head === document.querySelector("head") ); // true
+
+ +

備註

+ +

document.head 是「唯讀」。若是想要將 document.head 改成別的值會失敗,這時有些瀏覽器不會告知任何錯誤訊息;有些,例如在 ECMAScript Strict 模式下 的 Gecko 瀏覽器,會給出 TypeError 異常。

+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG','dom.html#dom-document-head','Document.head')}}{{Spec2('HTML WHATWG')}}Initial definition.
{{SpecName('HTML5.1','dom.html#dom-document-head','Document.head')}}{{Spec2('HTML5.1')}} 
{{SpecName('HTML5 W3C','dom.html#dom-document-head','Document.head')}}{{Spec2('HTML5 W3C')}} 
+ +

瀏覽器相容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support4.0{{CompatVersionUnknown}}{{CompatGeckoDesktop("2")}}9.011.05.0
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("2")}}9.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

參見

+ + diff --git a/files/zh-tw/web/api/document/index.html b/files/zh-tw/web/api/document/index.html new file mode 100644 index 0000000000..ca1c9830b7 --- /dev/null +++ b/files/zh-tw/web/api/document/index.html @@ -0,0 +1,446 @@ +--- +title: Document +slug: Web/API/Document +tags: + - API + - DOM + - Gecko + - MakeBrowserAgnostic + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/API/Document +--- +
{{APIRef}}
+ +
+ +

Document 介面代表所有在瀏覽器中載入的網頁,也是作為網頁內容 DOM 樹(包含如 {{HTMLElement("body")}}、{{HTMLElement("table")}} 與其它的{{domxref("Element", "元素")}})的進入點。Document 提供了網頁文件所需的通用函式,例如取得頁面 URL 或是建立網頁文件中新的元素節點等。

+ +

{{inheritanceDiagram}}

+ +

Document 介面描述了各種類型文件的共同屬性與方法。根據文件的類型(如 HTMLXML、SVG 等),也會擁有各自的 API:HTML 文件(content type 為 text/html)實作了 {{domxref("HTMLDocument")}} 介面,而 XML 及 SVG 文件實作了 {{domxref("XMLDocument")}} 介面。

+ +

請注意 window.document 物件為 HTMLDocument 所建構。

+ +

屬性

+ +

這個介面繼承了  {{domxref("Node")}} 以及 {{domxref("EventTarget")}} 介面。

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

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

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

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

+ +

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

+ +

HTML 文件擴充

+ +

window.document 物件的部分屬性繼承自 HTML 文件的 {{domxref("HTMLDocument")}} 介面,或是來自 Document 從 HTML5 之後擴充的屬性。

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

事件處理器

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

此介面繼承了 {{domxref("GlobalEventHandlers")}} 的事件處理器:

+ +

{{Page("/zh-TW/docs/Web/API/GlobalEventHandlers", "屬性")}}

+ +

方法

+ +

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

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

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

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

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

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

HTML 文件擴充

+ +

Document 物件的部分方法繼承自 HTML 文件的 {{domxref("HTMLDocument")}} 介面,或是來自 Document 從 HTML5 之後擴充的方法:

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

規範

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

瀏覽器相容性備註

+ +

Firefox notes

+ +

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

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

Mozilla also define some non-standard methods:

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

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/zh-tw/web/api/document/keyup_event/index.html b/files/zh-tw/web/api/document/keyup_event/index.html new file mode 100644 index 0000000000..3568b30c18 --- /dev/null +++ b/files/zh-tw/web/api/document/keyup_event/index.html @@ -0,0 +1,149 @@ +--- +title: keyup +slug: Web/API/Document/keyup_event +translation_of: Web/API/Document/keyup_event +--- +

當鍵盤上的手指離開按鍵時,keyup事件會被觸發。

+ +

基本資料

+ +
+
詳述
+
DOM L3
+
介面
+
KeyboardEvent
+
Bubbles
+
Yes
+
Cancelable
+
Yes
+
Target
+
網頁文件, 網頁元素
+
Default Action
+
None
+
+ +

屬性

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
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.
+ + + + diff --git a/files/zh-tw/web/api/document/queryselector/index.html b/files/zh-tw/web/api/document/queryselector/index.html new file mode 100644 index 0000000000..a79edb1c1f --- /dev/null +++ b/files/zh-tw/web/api/document/queryselector/index.html @@ -0,0 +1,102 @@ +--- +title: document.querySelector +slug: Web/API/Document/querySelector +tags: + - DOM + - Fixit + - Gecko DOM Reference + - Gecko DOM 參考 + - Selectors + - 選擇器 +translation_of: Web/API/Document/querySelector +--- +
+ {{ApiRef()}}
+

摘要

+

回傳 document 第一個符合特定選擇器群組的元素(採用深度優先,前序追蹤 document 節點)。

+

語法

+
element = document.querySelector(selectors);
+

其中

+ +

範例

+

這個範例會回傳 document 選到的第一個 "myclass" class:

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

注意事項

+

若找不到相應元素就會回傳 null,否則回傳第一個符合的元素。

+

若選擇器符合某 ID,且該 ID 在 document 中誤用數次,就會回傳第一個符合的元素。

+

當特定選擇器群組無效,會擲回 SYNTAX_ERR 例外狀況。

+

querySelector() 是由 Selectors API 引入的選擇器。

+

傳入 querySelector 的字串參數必須遵循 CSS 語法。若要選取未遵循 CSS 語法的 ID 或選擇器(例如不當使用冒號或空格),必須強制加上兩個反斜線來跳脫錯誤的字元:

+
<div id="foo\bar"></div>
+<div id="foo:bar"></div>
+
+<script>
+document.querySelector('#foo\bar')    // 甚麼都沒選到
+document.querySelector('#foo\\\\bar') // 選到第一個 div
+document.querySelector('#foo:bar')     // 甚麼都沒選到
+document.querySelector('#foo\\:bar')   // 選到第二個 div
+</script>
+
+

瀏覽器相容性

+

{{CompatibilityTable()}}

+
+ + + + + + + + + + + + + + + + + + + +
功能特色ChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
基本支援13.5 (1.9.1)
+ {{bug(416317)}}
8103.2 (525.3)
+ {{Webkitbug("16587")}}
+
+
+ + + + + + + + + + + + + + + + + + + +
功能特色AndroidFirefox 行動版 (Gecko)IE 行動版Opera 行動版Safari 行動版
基本支援2.1910.03.2
+
+

規格文件

+ +

詳見

+ diff --git a/files/zh-tw/web/api/document/readystate/index.html b/files/zh-tw/web/api/document/readystate/index.html new file mode 100644 index 0000000000..13cf835aa7 --- /dev/null +++ b/files/zh-tw/web/api/document/readystate/index.html @@ -0,0 +1,108 @@ +--- +title: Document.readyState +slug: Web/API/Document/readyState +tags: + - API + - HTML DOM + - Reference +translation_of: Web/API/Document/readyState +--- +
{{APIRef("DOM")}} {{ gecko_minversion_header("1.9.2") }}
+ +

總覽

+ +

{{ domxref("document") }} 的 Document.readyState 屬性描述文件的讀取狀態。

+ +

數值

+ +

文件的 readyState 數值如下:

+ +
+
loading
+
{{ domxref("document") }} 正在讀取中。
+
interactive
+
文件已經完成讀取和解析,但是其他的子資源,如「圖片樣式層次表」,仍然在讀取。這個狀態表示 {{event("DOMContentLoaded")}} 事件已經被觸發。
+
complete
+
文件及子資源都完成讀取。這個狀態表示 {{event("load")}} 事件即將被觸發。
+
+ +

當這個屬性的數值改變時, {{event("readystatechange")}} 事件在 {{ domxref("document") }} 上觸發。

+ +

表達式

+ +
var string = document.readyState;
+
+ +

範例

+ +

不同的狀態

+ +
switch (document.readyState) {
+  case "loading":
+    // 文件讀取中。
+    break;
+  case "interactive":
+    // 文件已經完成讀取。可以使用 DOM 元素。
+    var span = document.createElement("span");
+    span.textContent = "A <span> element.";
+    document.body.appendChild(span);
+    break;
+  case "complete":
+    // 頁面已經完成讀取。
+    console.log("The first CSS rule is: " + document.styleSheets[0].cssRules[0].cssText);
+    break;
+}
+
+ +

readystatechange 替代 DOMContentLoaded

+ +
// alternative to DOMContentLoaded event
+document.onreadystatechange = function () {
+  if (document.readyState == "interactive") {
+    initApplication();
+  }
+}
+ +

readystatechange 替代 load

+ +
// alternative to load event
+document.onreadystatechange = function () {
+  if (document.readyState == "complete") {
+    initApplication();
+  }
+}
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + +
規範狀態
{{SpecName("HTML WHATWG", "#current-document-readiness", "Document readiness")}}{{Spec2('HTML WHATWG')}} 
{{SpecName("HTML5.1", "#current-document-readiness", "Document readiness")}}{{Spec2('HTML5.1')}} 
{{SpecName("HTML5 W3C", "#current-document-readiness", "Document readiness")}}{{Spec2('HTML5 W3C')}}Initial specification.
+ +

參見

+ + diff --git a/files/zh-tw/web/api/document/registerelement/index.html b/files/zh-tw/web/api/document/registerelement/index.html new file mode 100644 index 0000000000..66c3330dca --- /dev/null +++ b/files/zh-tw/web/api/document/registerelement/index.html @@ -0,0 +1,113 @@ +--- +title: Document.registerElement() +slug: Web/API/Document/registerElement +tags: + - API + - DOM + - JavaScript + - 自訂標籤 +translation_of: Web/API/Document/registerElement +--- +

{{APIRef("DOM")}}{{Deprecated_header}}

+ +
+

Warning: document.registerElement()                       已經被棄用,建議使用               customElements.define().

+
+ +

{{draft}}

+ +

 document.registerElement()                 可以在瀏覽器中註冊一個新的自訂標籤(元素)and returns a constructor for the new element.

+ +
+

Note: This is an experimental technology. The browser you use it in must support Web Components. See Enabling Web Components in Firefox.

+
+ +

語法

+ +
var constructor = document.registerElement(tag-name, options);
+ +

參數

+ +
+
標籤名稱
+
自訂的標籤名稱需有一個 橫線  ( - ), 例如my-tag.
+
options {{optional_inline}}
+
+

An object with properties prototype to base the custom element on, and extends, an existing tag to extend. Both of these are optional.

+
+
+ +

例子

+ +

這是一個非常簡單的例子:

+ +
var Mytag = document.registerElement('my-tag');
+
+ +

現在新的標籤已經在瀏覽器中註冊了. The Mytag variable holds a constructor that you can use to create a my-tag element in the document as follows:

+ +
document.body.appendChild(new Mytag());
+ +

This inserts an empty my-tag element that will be visible if you use the browser's developer tools. It will not be visible if you use the browser's view source capability. And it won't be visible in the browser unless you add some content to the tag. Here is one way to add content to the new tag:

+ +
var mytag = document.getElementsByTagName("my-tag")[0];
+mytag.textContent = "I am a my-tag element.";
+
+ +

瀏覽器支援性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support3531[1]{{CompatNo}}25{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support4.4.431[1]{{CompatNo}}25{{CompatNo}}
+
+ +

[1] This API is implemented behind a preference.

+ +

也看一下

+ + diff --git a/files/zh-tw/web/api/document/scroll_event/index.html b/files/zh-tw/web/api/document/scroll_event/index.html new file mode 100644 index 0000000000..26dbb7640c --- /dev/null +++ b/files/zh-tw/web/api/document/scroll_event/index.html @@ -0,0 +1,103 @@ +--- +title: scroll +slug: Web/API/Document/scroll_event +translation_of: Web/API/Document/scroll_event +--- +

當文件的可視區或元素被滾動(scroll),scroll事件會被觸發

+ +

一般資訊

+ +
+
規範
+
DOM L3, CSSOM View
+
介面
+
UIEvent
+
Bubbles
+
Not on elements, but bubbles to the default view when fired on the document
+
Cancelable
+
No
+
Target
+
defaultView, Document, Element
+
Default Action
+
None
+
+ +

屬性

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

Example

+ +

因為 scroll 事件是高頻觸發,這樣的事件處理程式不該進行運算成本高的程式,像是DOM的修改。所以,建議使用 requestAnimationFrame, setTimeoutcustomEvent 如下所示

+ +

Scroll optimization with window.requestAnimationFrame

+ +
// Reference: http://www.html5rocks.com/en/tutorials/speed/animations/
+
+var last_known_scroll_position = 0;
+var ticking = false;
+
+function doSomething(scroll_pos) {
+  // do something with the scroll position
+}
+
+window.addEventListener('scroll', function(e) {
+  last_known_scroll_position = window.scrollY;
+  if (!ticking) {
+    window.requestAnimationFrame(function() {
+      doSomething(last_known_scroll_position);
+      ticking = false;
+    });
+  }
+  ticking = true;
+});
+ +

 

+ +

關於resize事件的更多類似例子。

+ +

瀏覽器相容性

+ +

iOS UIWebView

+ +

在iOS UIWebViews中,滾動捲軸時 scroll 事件不會觸發;它們要等到滾動完成時才被觸發。請參閱Bootstrap issue #16202。 Safari 和 WKWebViews 不受此bug的影響。

diff --git a/files/zh-tw/web/api/document/width/index.html b/files/zh-tw/web/api/document/width/index.html new file mode 100644 index 0000000000..39eef5c184 --- /dev/null +++ b/files/zh-tw/web/api/document/width/index.html @@ -0,0 +1,45 @@ +--- +title: Document.width +slug: Web/API/Document/width +translation_of: Web/API/Document/width +--- +
{{APIRef("DOM")}} {{Obsolete_header}}
+ +
+

注意: 從 {{Gecko("6.0")}} 開始, document.width 將不再被支援。取而代之的是 document.body.clientWidth 。請參照: {{domxref("element.clientWidth")}}.

+
+ +

傳回目前文件中,{{HTMLElement("body")}} 元素的寬度有多少像素。

+ +

Internet Explorer 不支援!

+ +

語法

+ +
pixels = document.width;
+
+ +

範例

+ +
function init() {
+    alert("文件的寬度是 " + document.width + " 像素。");
+}
+
+ +

其他替代

+ +
document.body.clientWidth              /* <body> 的寬度 */
+document.documentElement.clientWidth   /* <html> 的寬度 */
+window.innerWidth                      /* 視窗的寬度 */
+
+ +

規範於

+ +

HTML5

+ +

同時參考

+ + diff --git a/files/zh-tw/web/api/document_object_model/examples/index.html b/files/zh-tw/web/api/document_object_model/examples/index.html new file mode 100644 index 0000000000..66a1756da6 --- /dev/null +++ b/files/zh-tw/web/api/document_object_model/examples/index.html @@ -0,0 +1,373 @@ +--- +title: 使用 web 和 XML 開發來使用 DOM +slug: Web/API/Document_Object_Model/Examples +translation_of: Web/API/Document_Object_Model/Examples +--- +

本章介紹了使用 DOM 進行 Web 以及 XML 開發的一些長範例。只要可能,在例子就會使用通用的 JavaScript Web API 、技巧以及模式來操作文檔對象(the document object)。

+ +

範例一:高度和寬度

+ +

下面的例子展示了在不同尺寸的圖片時使用其高(height)和寬(width)屬性的情況:

+ +
<!DOCTYPE html>
+<html lang="en">
+<head>
+<title>width/height example</title>
+<script>
+function init() {
+  var arrImages = new Array(3);
+
+  arrImages[0] = document.getElementById("image1");
+  arrImages[1] = document.getElementById("image2");
+  arrImages[2] = document.getElementById("image3");
+
+  var objOutput = document.getElementById("output");
+  var strHtml = "<ul>";
+
+  for (var i = 0; i < arrImages.length; i++) {
+    strHtml += "<li>image" + (i+1) +
+            ": height=" + arrImages[i].height +
+            ", width=" + arrImages[i].width +
+            ", style.height=" + arrImages[i].style.height +
+            ", style.width=" + arrImages[i].style.width +
+            "<\/li>";
+  }
+
+  strHtml += "<\/ul>";
+
+  objOutput.innerHTML = strHtml;
+}
+</script>
+</head>
+<body onload="init();">
+
+<p>Image 1: no height, width, or style
+  <img id="image1" src="http://www.mozilla.org/images/mozilla-banner.gif">
+</p>
+
+<p>Image 2: height="50", width="500", but no style
+  <img id="image2"
+       src="http://www.mozilla.org/images/mozilla-banner.gif"
+       height="50" width="500">
+</p>
+
+<p>Image 3: no height, width, but style="height: 50px; width: 500px;"
+  <img id="image3"
+       src="http://www.mozilla.org/images/mozilla-banner.gif"
+       style="height: 50px; width: 500px;">
+</p>
+
+<div id="output"> </div>
+</body>
+</html>
+
+ +

範例二:圖片屬性

+ +
<!DOCTYPE html>
+<html lang="en">
+<head>
+<title>Modifying an image border</title>
+
+<script>
+function setBorderWidth(width) {
+  document.getElementById("img1").style.borderWidth = width + "px";
+}
+</script>
+</head>
+
+<body>
+<p>
+  <img id="img1"
+       src="image1.gif"
+       style="border: 5px solid green;"
+       width="100" height="100" alt="border test">
+</p>
+
+<form name="FormName">
+  <input type="button" value="Make border 20px-wide" onclick="setBorderWidth(20);" />
+  <input type="button" value="Make border 5px-wide"  onclick="setBorderWidth(5);" />
+</form>
+
+</body>
+</html>
+
+ +

範例三:改變樣式(style)

+ +

在下面這個簡單的例子中,透過取得的 DOM 元素中的 style 物件和 style 物件中的屬性,我們可以取得 HTML 段落中的一些基本樣式屬性。在本例中,你可以直接操控各別的樣式屬性。在下一個的例子裡(見例4),你可以使用 stylesheets 和它的規則來改變整個文檔的樣式。

+ +
<!DOCTYPE html>
+<html lang="en">
+<head>
+<title>Changing color and font-size example</title>
+
+<script>
+function changeText() {
+  var p = document.getElementById("pid");
+
+  p.style.color = "blue"
+  p.style.fontSize = "18pt"
+}
+</script>
+</head>
+<body>
+
+<p id="pid" onclick="window.location.href = 'http://www.cnn.com/';">linker</p>
+
+<form>
+  <p><input value="rec" type="button" onclick="changeText();" /></p>
+</form>
+
+</body>
+</html>
+
+ +

範例四:使用樣式表(stylesheets)

+ +

在文檔物件的 styleSheets 屬性會回傳一系列載入文檔中的樣式表(stylesheets)。你可以透過 styleSheets、style 和 CSSRule 物件來獲取樣式表和每條樣式規則。在下面的例子中,把所有的樣式規則中的選擇器文本(字符串)打印到控制台中。

+ +
var ss = document.styleSheets;
+
+for(var i = 0; i < ss.length; i++) {
+  for(var j = 0; j < ss[i].cssRules.length; j++) {
+    dump( ss[i].cssRules[j].selectorText + "\n" );
+  }
+}
+ +

下面是一個只定義了三條樣式規則的單一樣式表的文檔:

+ +
body { background-color: darkblue; }
+p { font-face: Arial; font-size: 10pt; margin-left: .125in; }
+#lumpy { display: none; }
+
+ +

該腳本會輸出如下的結果:

+ +
BODY
+P
+#LUMPY
+
+ +

範例五:事件傳遞

+ +

本例以一種簡單的方法闡述了事件是如何觸發以及在 DOM 中是如何處理的。當這個 HTML 文檔 BODY 載入的時候,在表格的首行註冊了一個事件監聽器。事件監聽器透過執行函數 stopEvent 來處理事件,從而改變在該表格底部的值。

+ +

然而,stopEvent 同時也會另外執行一個事件物件的方法{{domxref("event.stopPropagation")}},這會使得該事件(點擊)無法在 DOM 中有進一步的冒泡行為。請注意,表格本身有一個 {{domxref("element.onclick","onclick")}} 事件,使得這個表格被點擊時的時候原本應該要會跳出一個訊息。但因為 stopEvent 方法已經阻止了冒泡,所以在表格中的數據更新後,該事件階段有效地結束,表格的點擊事件沒有被觸發,而是顯示一個警告框(event propagation halted)——證實了事件被有效結束而沒有進一步冒泡。

+ +
<!DOCTYPE html>
+<html lang="en">
+<head>
+<title>Event Propagation</title>
+
+<style>
+#t-daddy { border: 1px solid red }
+#c1 { background-color: pink; }
+</style>
+
+<script>
+function stopEvent(ev) {
+  c2 = document.getElementById("c2");
+  c2.innerHTML = "hello";
+
+  // this ought to keep t-daddy from getting the click.
+  ev.stopPropagation();
+  alert("event propagation halted.");
+}
+
+function load() {
+  elem = document.getElementById("tbl1");
+  elem.addEventListener("click", stopEvent, false);
+}
+</script>
+</head>
+
+<body onload="load();">
+
+<table id="t-daddy" onclick="alert('hi');">
+  <tr id="tbl1">
+    <td id="c1">one</td>
+  </tr>
+  <tr>
+    <td id="c2">two</td>
+  </tr>
+</table>
+
+</body>
+</html>
+
+ +

Example 6: getComputedStyle

+ +

這個例子演示了如何用 {{domxref("window.getComputedStyle")}} 方法來獲取一個尚未被透過樣式元素或 JavaScript 設定的元素樣式(例如,elt.style.backgroundColor="RGB(173,216,230)")。列舉在 {{domxref("element.style", "elt.style")}} 後面的類型的樣式可以用更直接{{domxref("element.style", "elt.style")}} 屬性獲取。

+ +

getComputedStyle() 返回了一個 ComputedCSSStyleDeclaration 物件,其獨立的樣式屬性可以用該物件的 getPropertyValue() 方法引用,如同下面的例子一樣:

+ +
<!DOCTYPE html>
+<html lang="en">
+<head>
+
+<title>getComputedStyle example</title>
+
+<script>
+function cStyles() {
+  var RefDiv = document.getElementById("d1");
+  var txtHeight = document.getElementById("t1");
+  var h_style = document.defaultView.getComputedStyle(RefDiv, null).getPropertyValue("height");
+
+  txtHeight.value = h_style;
+
+  var txtWidth = document.getElementById("t2");
+  var w_style = document.defaultView.getComputedStyle(RefDiv, null).getPropertyValue("width");
+
+  txtWidth.value = w_style;
+
+  var txtBackgroundColor = document.getElementById("t3");
+  var b_style = document.defaultView.getComputedStyle(RefDiv, null).getPropertyValue("background-color");
+
+  txtBackgroundColor.value = b_style;
+}
+</script>
+
+<style>
+#d1 {
+  margin-left: 10px;
+  background-color: rgb(173, 216, 230);
+  height: 20px;
+  max-width: 20px;
+}
+</style>
+
+</head>
+
+<body>
+
+<div id="d1">&nbsp;</div>
+
+<form action="">
+  <p>
+    <button type="button" onclick="cStyles();">getComputedStyle</button>
+    height<input id="t1" type="text" value="1" />
+    max-width<input id="t2" type="text" value="2" />
+    bg-color<input id="t3" type="text" value="3" />
+  </p>
+</form>
+
+</body>
+</html>
+
+ +

範例七:顯示事件物件的屬性

+ +

這個例子使用 DOM 方法來顯示所有 {{domxref("window.onload")}} {{domxref("event")}} 物件的屬性及其在 table 中的值。這個方法也展示一個有用的技術,使用 for...in 迴圈來來遍歷一個物件的屬性,以得到它們的值。

+ +

不同瀏覽器之間事件物件的屬性有很大不同,WHATWG DOM Standard 規範了事件的標準屬性,然而,許多瀏覽器都大大擴展了這些。

+ +

將下面的代碼放到一個空白的文本文件,並將其用各種瀏覽器開啟,你一定會對各種瀏覽器之間的不一致(事件屬性的名稱及其數量)感到驚訝。你可能還喜歡在這個頁面加入一些元素,並呼叫不同的事件處理函數(event handlers)。

+ +
<!DOCTYPE html>
+<html lang="en">
+<head>
+<meta charset="utf-8"/>
+<title>Show Event properties</title>
+
+<style>
+table { border-collapse: collapse; }
+thead { font-weight: bold; }
+td { padding: 2px 10px 2px 10px; }
+
+.odd { background-color: #efdfef; }
+.even { background-color: #ffffff; }
+</style>
+
+<script>
+
+function showEventProperties(e) {
+  function addCell(row, text) {
+    var cell = row.insertCell(-1);
+    cell.appendChild(document.createTextNode(text));
+  }
+
+  var e = e || window.event;
+  document.getElementById('eventType').innerHTML = e.type;
+
+  var table = document.createElement('table');
+  var thead = table.createTHead();
+  var row = thead.insertRow(-1);
+  var lableList = ['#', 'Property', 'Value'];
+  var len = lableList.length;
+
+  for (var i=0; i<len; i++) {
+    addCell(row, lableList[i]);
+  }
+
+  var tbody = document.createElement('tbody');
+  table.appendChild(tbody);
+
+  for (var p in e) {
+    row = tbody.insertRow(-1);
+    row.className = (row.rowIndex % 2)? 'odd':'even';
+    addCell(row, row.rowIndex);
+    addCell(row, p);
+    addCell(row, e[p]);
+  }
+
+  document.body.appendChild(table);
+}
+
+window.onload = function(event){
+  showEventProperties(event);
+}
+</script>
+</head>
+
+<body>
+<h1>Properties of the DOM <span id="eventType"></span> Event Object</h1>
+</body>
+
+</html>
+
+ +

範例八:使用 DOM Table 介面

+ +

DOM HTMLTableElement 介面提供了一些方便的方法用於創建和操作資料表。兩種常用的方法是{{domxref("HTMLTableElement.insertRow")}}和{{domxref("tableRow.insertCell")}}.。

+ +

增加一行和一些細格到現有的資料表:

+ +
<table id="table0">
+ <tr>
+  <td>Row 0 Cell 0</td>
+  <td>Row 0 Cell 1</td>
+ </tr>
+</table>
+
+<script>
+var table = document.getElementById('table0');
+var row = table.insertRow(-1);
+var cell,
+    text;
+
+for (var i = 0; i < 2; i++) {
+  cell = row.insertCell(-1);
+  text = 'Row ' + row.rowIndex + ' Cell ' + i;
+  cell.appendChild(document.createTextNode(text));
+}
+</script>
+
+ +

提醒

+ + + + + + diff --git a/files/zh-tw/web/api/document_object_model/how_to_create_a_dom_tree/index.html b/files/zh-tw/web/api/document_object_model/how_to_create_a_dom_tree/index.html new file mode 100644 index 0000000000..02a3ac01e2 --- /dev/null +++ b/files/zh-tw/web/api/document_object_model/how_to_create_a_dom_tree/index.html @@ -0,0 +1,145 @@ +--- +title: 如何建立 DOM 樹 +slug: Web/API/Document_Object_Model/How_to_create_a_DOM_tree +translation_of: Web/API/Document_object_model/How_to_create_a_DOM_tree +--- +

{{draft}}

+ +

This page describes how to use the DOM Core API in JavaScript to create and modify DOM objects. It applies to all Gecko-based applications (such as Firefox) both in privileged (extensions) and unprivileged (web pages) code.

+ +

Dynamically creating a DOM tree

+ +

Consider the following XML document:

+ +
<?xml version="1.0"?>
+<people>
+  <person first-name="eric" middle-initial="H" last-name="jung">
+    <address street="321 south st" city="denver" state="co" country="usa"/>
+    <address street="123 main st" city="arlington" state="ma" country="usa"/>
+  </person>
+
+  <person first-name="jed" last-name="brown">
+    <address street="321 north st" city="atlanta" state="ga" country="usa"/>
+    <address street="123 west st" city="seattle" state="wa" country="usa"/>
+    <address street="321 south avenue" city="denver" state="co" country="usa"/>
+  </person>
+</people>
+
+ +

The W3C DOM API, supported by Mozilla, can be used to create an in-memory representation of this document like so:

+ +
var doc = document.implementation.createDocument("", "", null);
+var peopleElem = doc.createElement("people");
+
+var personElem1 = doc.createElement("person");
+personElem1.setAttribute("first-name", "eric");
+personElem1.setAttribute("middle-initial", "h");
+personElem1.setAttribute("last-name", "jung");
+
+var addressElem1 = doc.createElement("address");
+addressElem1.setAttribute("street", "321 south st");
+addressElem1.setAttribute("city", "denver");
+addressElem1.setAttribute("state", "co");
+addressElem1.setAttribute("country", "usa");
+personElem1.appendChild(addressElem1);
+
+var addressElem2 = doc.createElement("address");
+addressElem2.setAttribute("street", "123 main st");
+addressElem2.setAttribute("city", "arlington");
+addressElem2.setAttribute("state", "ma");
+addressElem2.setAttribute("country", "usa");
+personElem1.appendChild(addressElem2);
+
+var personElem2 = doc.createElement("person");
+personElem2.setAttribute("first-name", "jed");
+personElem2.setAttribute("last-name", "brown");
+
+var addressElem3 = doc.createElement("address");
+addressElem3.setAttribute("street", "321 north st");
+addressElem3.setAttribute("city", "atlanta");
+addressElem3.setAttribute("state", "ga");
+addressElem3.setAttribute("country", "usa");
+personElem2.appendChild(addressElem3);
+
+var addressElem4 = doc.createElement("address");
+addressElem4.setAttribute("street", "123 west st");
+addressElem4.setAttribute("city", "seattle");
+addressElem4.setAttribute("state", "wa");
+addressElem4.setAttribute("country", "usa");
+personElem2.appendChild(addressElem4);
+
+var addressElem5 = doc.createElement("address");
+addressElem5.setAttribute("street", "321 south avenue");
+addressElem5.setAttribute("city", "denver");
+addressElem5.setAttribute("state", "co");
+addressElem5.setAttribute("country", "usa");
+personElem2.appendChild(addressElem5);
+
+peopleElem.appendChild(personElem1);
+peopleElem.appendChild(personElem2);
+doc.appendChild(peopleElem);
+
+ +

See also the DOM chapter of the XUL Tutorial.

+ +

You can automate the creation of a DOM tree using a JXON reverse algorithm in association with the following JSON representation:

+ +
{
+  "people": {
+    "person": [{
+      "address": [{
+        "@street": "321 south st",
+        "@city": "denver",
+        "@state": "co",
+        "@country": "usa"
+      }, {
+        "@street": "123 main st",
+        "@city": "arlington",
+        "@state": "ma",
+        "@country": "usa"
+      }],
+      "@first-name": "eric",
+      "@middle-initial": "H",
+      "@last-name": "jung"
+    }, {
+      "address": [{
+        "@street": "321 north st",
+        "@city": "atlanta",
+        "@state": "ga",
+        "@country": "usa"
+      }, {
+        "@street": "123 west st",
+        "@city": "seattle",
+        "@state": "wa",
+        "@country": "usa"
+      }, {
+        "@street": "321 south avenue",
+        "@city": "denver",
+        "@state": "co",
+        "@country": "usa"
+      }],
+      "@first-name": "jed",
+      "@last-name": "brown"
+    }]
+  }
+}
+
+ +

So what?

+ +

DOM trees can be queried using XPath expressions, converted to strings or written to a local or remote files using XMLSerializer (without having to first convert to a string), POSTed to a web server (via XMLHttpRequest), transformed using XSLT, XLink, converted to a JavaScript object through a JXON algorithm, etc.

+ +

You can use DOM trees to model data which isn't well-suited for RDF (or perhaps you just don't like RDF). Another application is that, since XUL is XML, the UI of your application can be dynamically manipulated, downloaded, uploaded, saved, loaded, converted, or transformed quite easily.

+ +

See also

+ + + +

{{ languages( { "fr": "fr/Comment_cr\u00e9er_un_arbre_DOM", "ja": "ja/How_to_create_a_DOM_tree", "zh-cn": "zh-cn/How_to_create_a_DOM_tree" } ) }}

diff --git a/files/zh-tw/web/api/document_object_model/index.html b/files/zh-tw/web/api/document_object_model/index.html new file mode 100644 index 0000000000..a2e07c7fdd --- /dev/null +++ b/files/zh-tw/web/api/document_object_model/index.html @@ -0,0 +1,384 @@ +--- +title: 文件物件模型 (DOM) +slug: Web/API/Document_Object_Model +tags: + - DOM + - DOM Reference + - DOM 參考 + - Intermediate +translation_of: Web/API/Document_Object_Model +--- +

{{DefaultAPISidebar("DOM")}}

+ +

文件物件模型(Document Object Model, DOM是 HTML、XML 和 SVG 文件的程式介面。它提供了一個文件(樹)的結構化表示法,並定義讓程式可以存取並改變文件架構、風格和內容的方法。DOM 提供了文件以擁有屬性與函式的節點與物件組成的結構化表示。節點也可以附加事件處理程序,一旦觸發事件就會執行處理程序。 本質上,它將網頁與腳本或程式語言連結在一起。

+ +

雖然常常使用 JavaScript 來存取 DOM,但它本身並不是 JavaScript 語言的一部分,而且它也可以被其他語言存取(雖然不太常見就是了)。

+ +

這裡有一篇 DOM 的介紹可供查閱。

+ +

DOM 介面

+ +
+ +
+ +

棄用的 DOM 介面

+ +

文件物件模型正被大量的簡化。為了達成這個目的,下這些介面是在 DOM level 3 或更早的規範中就被刪掉了。由於不清楚是否會被再度納入,請姑且當他們已經被遺棄,並避免使用:

+ +
+ +
+ +

HTML 介面

+ +

一份包含 html 的文件會透過 {{domxref("HTMLDocument")}} 介面來描述。注意 HTML 規範也擴展了 {{domxref("Document")}} 介面。

+ +

HTMLDocument 物件也提供了瀏覽器功能的存取:分頁、透過 {{domxref("Window")}} 介面描繪頁面的視窗、與其相關的 {{domxref("window.style", "樣式")}} (通常是 CSS )、與本文關聯的瀏覽器 {{domxref("window.history", "歷史")}}、以及一個文件內的 {{domxref("Selection", "選擇器")}}。

+ +

HTML 元素介面

+ +
+ +
+ +

其他介面

+ +
+ +
+ +

棄用的 HTML 介面

+ +
+ +
+ +

SVG 介面

+ +

SVG 元素介面

+ +
+ +
+ +

SVG 資料型別介面

+ +

這裡是資料型態的 DOM API,在 SVG 特性和性質的定義中被使用。

+ +
+

備註:從 {{Gecko("5.0")}} 開始,下列 SVG 相關的 DOM 介面物件的表示清單,現在可以被索引且可以像陣列般被取用;此外,他們也有 length 屬性來標示其清單中的項目個數:{{domxref("SVGLengthList")}}、{{domxref("SVGNumberList")}}、{{domxref("SVGPathSegList")}},和 {{domxref("SVGPointList")}}。

+
+ +

靜態類型

+ +
+ +
+ +

動畫類型

+ +
+ +
+ +

SMIL 相關介面

+ +
+ +
+ +

其他的 SVG 介面

+ +
+ +
+ +

相關連結

+ + diff --git a/files/zh-tw/web/api/document_object_model/whitespace/index.html b/files/zh-tw/web/api/document_object_model/whitespace/index.html new file mode 100644 index 0000000000..7e584a3dd6 --- /dev/null +++ b/files/zh-tw/web/api/document_object_model/whitespace/index.html @@ -0,0 +1,183 @@ +--- +title: DOM 中的空白字元 +slug: Web/API/Document_Object_Model/Whitespace +tags: + - DOM + - 所有類別 +translation_of: Web/API/Document_Object_Model/Whitespace +--- +

問題說明

+

DOM 裡的空白字元會讓處理節點結構時增加不少麻煩。Mozilla 相關軟體中,原始文件裡所有空白字元都會在 DOM 中出現(不包括標籤內含的空白字元)。這樣的處理方式有其必要,一方面編輯器中可逕行排列文字、二方面 CSS 裡的 white-space: pre 也才能發揮作用。 如此一來就表示:

+ +

換句話說,下面這段程式碼的 DOM 節點結構就如附圖一般,其中「\n」代表換行字元:

+
<!-- My document -->
+<html>
+<head>
+  <title>My Document</title>
+</head>
+<body>
+  <h1>Header</h1>
+  <p>
+    Paragraph
+  </p>
+</body>
+</html>
+
+ +

+ +

這麼一來,要使用 DOM 遊走於節點結構間又不想要無用的空白字元時,會有點困難。

+

助你一臂之力

+

以下的 JavaScript 程式碼定義了許多函式,讓你處理 DOM 中的空白字元時能輕鬆點:

+
/**
+ * 以下所謂的「空白字元」代表:
+ *  "\t" TAB \u0009 (移位字元)
+ *  "\n" LF  \u000A (換行字元)
+ *  "\r" CR  \u000D (歸位字元)
+ *  " "  SPC \u0020 (真正的空白)
+ *
+ * 不包括 JavaScript 的「\s」,因為那代表如不斷行字元等其他字元。
+ */
+
+
+/**
+ * 測知某節點的文字內容是否全為空白。
+ *
+ * @參數   nod  |CharacterData| 類的節點(如  |Text|、|Comment| 或 |CDATASection|)。
+ * @傳回值      若 |nod| 的文字內容全為空白則傳回 true,否則傳回 false。
+ */
+function is_all_ws( nod )
+{
+  // Use ECMA-262 Edition 3 String and RegExp features
+  return !(/[^\t\n\r ]/.test(nod.data));
+}
+
+
+/**
+ * 測知是否該略過某節點。
+ *
+ * @參數   nod  DOM1 |Node| 物件
+ * @傳回值      若 |Text| 節點內僅有空白字元或為 |Comment| 節點時,傳回 true,
+ *              否則傳回 false。
+ */
+
+function is_ignorable( nod )
+{
+  return ( nod.nodeType == 8) || // 註解節點
+         ( (nod.nodeType == 3) && is_all_ws(nod) ); // 僅含空白字元的文字節點
+}
+
+/**
+ * 此為會跳過空白字元節點及註解節點的 |previousSibling| 函式
+ * ( |previousSibling| 是 DOM 節點的特性值,為該節點的前一個節點。)
+ *
+ * @參數   sib  節點。
+ * @傳回值      有兩種可能:
+ *               1) |sib| 的前一個「非空白、非註解」節點(由 |is_ignorable| 測知。)
+ *               2) 若該節點前無任何此類節點,則傳回 null。
+ */
+function node_before( sib )
+{
+  while ((sib = sib.previousSibling)) {
+    if (!is_ignorable(sib)) return sib;
+  }
+  return null;
+}
+
+/**
+ * 此為會跳過空白字元節點及註解節點的 |nextSibling| 函式
+ *
+ * @參數   sib  節點。
+ * @傳回值      有兩種可能:
+ *               1) |sib| 的下一個「非空白、非註解」節點。
+ *               2) 若該節點後無任何此類節點,則傳回 null。
+ */
+function node_after( sib )
+{
+  while ((sib = sib.nextSibling)) {
+    if (!is_ignorable(sib)) return sib;
+  }
+  return null;
+}
+
+/**
+ * 此為會跳過空白字元節點及註解節點的 |lastChild| 函式
+ * ( lastChild| 是 DOM 節點的特性值,為該節點之中最後一個子節點。)
+ *
+ * @參數   par  節點。
+ * @傳回值      有兩種可能:
+ *               1) |par| 中最後一個「非空白、非註解」節點。
+ *               2) 若該節點中無任何此類子節點,則傳回 null。
+ */
+function last_child( par )
+{
+  var res=par.lastChild;
+  while (res) {
+    if (!is_ignorable(res)) return res;
+    res = res.previousSibling;
+  }
+  return null;
+}
+
+/**
+ * 此為會跳過空白字元節點及註解節點的 |firstChild| 函式
+ *
+ * @參數   par  節點。
+ * @傳回值      有兩種可能:
+ *               1) |par| 中第一個「非空白、非註解」節點。
+ *               2) 若該節點中無任何此類子節點,則傳回 null。
+ */
+function first_child( par )
+{
+  var res=par.firstChild;
+  while (res) {
+    if (!is_ignorable(res)) return res;
+    res = res.nextSibling;
+  }
+  return null;
+}
+
+/**
+ * 此為傳回值不包含文字節點資料的首尾所有空白字元、
+ * 並將兩個以上的空白字元縮減為一個的 |data| 函式。
+ *( data 是 DOM 文字節點的特性值,為該文字節點中的資料。)
+ *
+ * @參數   txt 欲傳回其中資料的文字節點
+ * @傳回值     文字節點的內容,其中空白字元已依前述方式處理。
+ */
+function data_of( txt )
+{
+  var data = txt.data;
+  // Use ECMA-262 Edition 3 String and RegExp features
+  data = data.replace(/[\t\n\r ]+/g, " ");
+  if (data.charAt(0) == " ")
+    data = data.substring(1, data.length);
+  if (data.charAt(data.length - 1) == " ")
+    data = data.substring(0, data.length - 1);
+  return data;
+}
+
+

範例

+

以下示範上述函式的應用方法,在節點結構中依序檢查、找出內容為「"This is the third paragraph"」的節點,並修改其 class 屬性及文字內容。

+
var cur = first_child(document.getElementById("test"));
+while (cur)
+{
+  if (data_of(cur.firstChild) == "This is the third paragraph.")
+  {
+      cur.className = "magic";
+      cur.firstChild.data = "This is the magic paragraph.";
+  }
+  cur = node_after(cur);
+}
+
+
+

原文資訊

+ +
diff --git "a/files/zh-tw/web/api/document_object_model/\344\272\213\344\273\266/index.html" "b/files/zh-tw/web/api/document_object_model/\344\272\213\344\273\266/index.html" new file mode 100644 index 0000000000..ff4ecfe572 --- /dev/null +++ "b/files/zh-tw/web/api/document_object_model/\344\272\213\344\273\266/index.html" @@ -0,0 +1,69 @@ +--- +title: 事件與DOM +slug: Web/API/Document_Object_Model/事件 +translation_of: Web/API/Document_Object_Model/Events +--- +

Introduction

+ +

This chapter describes the DOM Event Model. The Event interface itself is described, as well as the interfaces for event registration on nodes in the DOM, and event listeners, and several longer examples that show how the various event interfaces relate to one another.

+ +

There is an excellent diagram that clearly explains the three phases of event flow through the DOM in the DOM Level 3 Events draft.

+ +

Also see Example 5: Event Propagation in the Examples chapter for a more detailed example of how events move through the DOM.

+ +

Registering event listeners

+ +

There are 3 ways to register event handlers for a DOM element.

+ +

EventTarget.addEventListener

+ +
// Assuming myButton is a button element
+myButton.addEventListener('click', function(){alert('Hello world');}, false);
+
+ +

This is the method you should use in modern web pages.

+ +

Note: Internet Explorer 6-8 didn't support this method, offering a similar {{domxref("EventTarget.attachEvent")}} API instead. For cross-browser compatibility use one of the many JavaScript libraries available.

+ +

More details can be found on the {{domxref("EventTarget.addEventListener")}} reference page.

+ +

HTML attribute

+ +
<button onclick="alert('Hello world!')">
+
+ +

The JavaScript code in the attribute is passed the Event object via the event parameter. The return value is treated in a special way, described in the HTML specification.

+ +

This way should be avoided. This makes the markup bigger and less readable. Concerns of content/structure and behavior are not well-separated, making a bug harder to find.

+ +

DOM element properties

+ +
// Assuming myButton is a button element
+myButton.onclick = function(event){alert('Hello world');};
+
+ +

The function can be defined to take an event parameter. The return value is treated in a special way, described in the HTML specification.

+ +

The problem with this method is that only one handler can be set per element and per event.

+ +

Accessing Event interfaces

+ +

Event handlers may be attached to various objects including DOM elements, document, the window object, etc. When an event occurs, an event object is created and passed sequentially to the event listeners.

+ +

The {{domxref("Event")}} interface is accessible from within the handler function, via the event object passed as the first argument. The following simple example shows how an event object is passed to the event handler function, and can be used from within one such function.

+ +
function foo(evt) {
+  // the evt parameter is automatically assigned the event object
+  alert(evt);
+}
+table_el.onclick = foo;
+
+ + + + diff --git a/files/zh-tw/web/api/documentfragment/index.html b/files/zh-tw/web/api/documentfragment/index.html new file mode 100644 index 0000000000..a3926841e0 --- /dev/null +++ b/files/zh-tw/web/api/documentfragment/index.html @@ -0,0 +1,248 @@ +--- +title: DocumentFragment +slug: Web/API/DocumentFragment +translation_of: Web/API/DocumentFragment +--- +

{{ ApiRef("DOM") }}

+ +

DocumentFragment 介面表示了一個沒有父節點的最小化文件物件。DocumentFragment 被當作一種輕量化的 {{domxref("Document")}},用如同標準文件一般的方式保存片段的文件結構(由節點組成)。關鍵的區別在於文件片段不是真實的 DOM 結構,文件片段的變動並不會影響目前的網頁文件,也不會導致回流({{Glossary("reflow")}})或引起任何影響效能的情況發生。

+ +

一般的用法是建立一個 DocumentFragment 物件,在此物件中組織一個 DOM 的子樹。再使用 {{domxref("Node")}} 介面定義的方法,如 {{domxref("Node.appendChild", "appendChild()")}} 或 {{domxref("Node.insertBefore", "insertBefore()")}} 將這個文件片段加入或插入目前頁面的 DOM 當中。執行這個將文件片段中的節點置入 DOM 的動作之後,會留下一個空的 DocumentFragment 物件(只會插入物件中的節點,DocumentFragment 物件本身不會被插入)。由於文件片段中的所有節點是一次性的被插入目前頁面文件當中,故回流及頁面渲染只會被觸發一次,所以可用插入 DocumentFragment 物件的方式取代傳統分別插入多個節點至 DOM(將節點一個一個分次進行插入)的操作方式。

+ +

此介面也適合與 Web components 搭配使用:{{HTMLElement("template")}} 元素在其 {{domxref("HTMLTemplateElement.content")}} 屬性中便包含了一個 DocumentFragment 物件。

+ +

可使用 {{domxref("document.createDocumentFragment()")}} 方法或 DocumentFragment 的建構式來建立一個空的 DocumentFragment 物件。

+ +

屬性

+ +

This interface has no specific properties, but inherits those of its parent, {{domxref("Node")}}, and implements those of the {{domxref("ParentNode")}} interface.

+ +
+
{{ domxref("ParentNode.children") }} {{readonlyInline}}{{experimental_inline}}
+
Returns a live {{domxref("HTMLCollection")}} containing all objects of type {{domxref("Element")}} 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.
+
+ +

建構式

+ +
+
{{ domxref("DocumentFragment.DocumentFragment()", "DocumentFragment()") }} {{experimental_inline}}
+
Returns an empty DocumentFragment object.
+
+ +

方法

+ +

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

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#interface-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
+ +

瀏覽器相容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1.0{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
querySelector() and querySelectorAll()1.0{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.1")}}8.010.03.2 (525.3)
findAll() and find() {{experimental_inline}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
DocumentFragment() constructor {{experimental_inline}}28.0{{CompatVersionUnknown}}{{CompatGeckoDesktop("24.0")}}{{CompatNo}}15.0{{CompatNo}}
ParentNode properties {{experimental_inline}}28.0{{CompatNo}}{{CompatGeckoDesktop("25.0")}}{{CompatNo}}15.0{{CompatNo}}
ParentNode methods {{experimental_inline}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
querySelector() and querySelectorAll()2.1{{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}}8.010.03.2 (525.3)
findAll() and find() {{experimental_inline}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
DocumentFragment() constructor {{experimental_inline}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("24.0")}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
ParentNode properties {{experimental_inline}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatGeckoMobile("25.0")}}{{CompatNo}}5.0{{CompatNo}}
ParentNode methods {{experimental_inline}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

參見

+ + diff --git a/files/zh-tw/web/api/documenttype/index.html b/files/zh-tw/web/api/documenttype/index.html new file mode 100644 index 0000000000..f0d7ae32b4 --- /dev/null +++ b/files/zh-tw/web/api/documenttype/index.html @@ -0,0 +1,200 @@ +--- +title: DocumentType +slug: Web/API/DocumentType +tags: + - API + - DOM + - DocumentType + - Interface +translation_of: Web/API/DocumentType +--- +
{{APIRef("DOM")}}
+ +

DocumentType 介面表示了一個代表文件類型的 {{domxref("Node")}} 節點。

+ +

{{InheritanceDiagram}}

+ +

屬性

+ +

此介面繼承了其父介面 {{domxref("Node")}} 的屬性,以及實作了 {{domxref("ChildNode")}} 介面。

+ +
+
{{domxref("DocumentType.entities")}} {{readonlyInline}} {{obsolete_Inline}}
+
A {{domxref("NamedNodeMap")}} of entities declared in the DTD. Every node in this map implements the {{domxref("Entity")}} interface.
+
{{domxref("DocumentType.internalSubset")}} {{readonlyInline}} {{obsolete_Inline}}
+
A {{domxref("DOMString")}} of the internal subset, or null if there is none. Eg "<!ELEMENT foo (bar)>".
+
{{domxref("DocumentType.name")}} {{readonlyInline}}
+
A {{domxref("DOMString")}}, eg "html" for <!DOCTYPE HTML>.
+
{{domxref("DocumentType.notations")}} {{readonlyInline}} {{obsolete_Inline}}
+
A {{domxref("NamedNodeMap")}} with notations declared in the DTD. Every node in this map implements the {{domxref("Notation")}} interface.
+
{{domxref("DocumentType.publicId")}} {{readonlyInline}}
+
A {{domxref("DOMString")}}, eg "-//W3C//DTD HTML 4.01//EN", empty string for HTML5.
+
{{domxref("DocumentType.systemId")}} {{readonlyInline}}
+
A {{domxref("DOMString")}}, eg "http://www.w3.org/TR/html4/strict.dtd", empty string for HTML5.
+
+ +

方法

+ +

此介面繼承了其父介面 {{domxref("Node")}} 的方法,以及實作了 {{domxref("ChildNode")}} 介面。

+ +
+
{{domxref("ChildNode.remove()")}} {{experimental_inline}}
+
Removes the object from its parent children list.
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#documenttype', 'DocumentType')}}{{Spec2('DOM WHATWG')}}Added implemention of the {{domxref("ChildNode")}} interface.
+ Removed the internalSubset, entities, and notation properties.
{{SpecName('DOM3 Core', 'core.html#ID-412266927', 'DocumentType')}}{{Spec2('DOM3 Core')}}No change from {{SpecName('DOM2 Core')}}.
{{SpecName('DOM2 Core', 'core.html#ID-412266927', 'DocumentType')}}{{Spec2('DOM2 Core')}}Added the publicID, systemID, and internalSubset properties.
{{SpecName('DOM1', 'level-one-core.html#ID-412266927', 'DocumentType')}}{{Spec2('DOM1')}}Initial definition
+ +

瀏覽器相容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1.0{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
entities and notations1.0[1]{{CompatVersionUnknown}}[3]{{CompatGeckoDesktop("1.0")}}
+ {{CompatNo}}{{CompatGeckoDesktop("6.0")}}
{{CompatVersionUnknown}}[3]{{CompatVersionUnknown}}[1]{{CompatVersionUnknown}}
internalSubset{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatNo}} (not anymore in any case){{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Implements {{domxref("ChildNode")}}29.0{{CompatVersionUnknown}}{{CompatGeckoDesktop("25.0")}}[2]{{CompatNo}}16.0{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
entities and notations{{CompatVersionUnknown}}[1]{{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}}
+ {{CompatNo}}{{CompatGeckoMobile("6.0")}}
{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
internalSubset{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Implements {{domxref("ChildNode")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("25.0")}}[2]{{CompatNo}}16.0{{CompatNo}}
+
+ +

[1] The Chromium project plans to drop supports for the internalSubset, entities and notations methods.

+ +

[2] Firefox 25 also added the previousElementSibling and nextElementSibling properties, this was removed in Firefox 28 due to compatibility problems.

+ +

[3] entities and notations properties exist in IE and Edge, but seem to always be null?

+ +

參見

+ + diff --git a/files/zh-tw/web/api/domparser/index.html b/files/zh-tw/web/api/domparser/index.html new file mode 100644 index 0000000000..4ded67f1c3 --- /dev/null +++ b/files/zh-tw/web/api/domparser/index.html @@ -0,0 +1,200 @@ +--- +title: DOMParser +slug: Web/API/DOMParser +tags: + - DOMParser SVG XML +translation_of: Web/API/DOMParser +--- +

{{APIRef("DOM")}}{{SeeCompatTable}}

+ +

DOMParser可以將XML或是HTML格式的字串轉成DOM 文件. DOMParser的規格請參閱DOM解譯與串流化.

+ +

請注意XMLHttpRequest解譯的是URL連結內容裡的XML與HTML文件.

+ +

產生一個 DOMParser

+ +

new DOMParser()" 可產生DOMParser.

+ +

關於如何在Firefox外掛程式中產生DOMParser,請參考nsIDOMParser文件

+ +

解譯 XML

+ +

產生解譯物件後,請呼叫parseFromString方法函式來將XML字串轉換成DOM物件:

+ +
var parser = new DOMParser();
+var doc = parser.parseFromString(stringContainingXMLSource, "application/xml");
+
+ +

錯誤處理

+ +

請注意如果解譯過程出錯,目前的DOMParser不會丟出異常物件(exception),但是會回傳一個錯誤文件(請看程式臭蟲{{Bug(45566)}}):

+ +
<parsererror xmlns="http://www.mozilla.org/newlayout/xml/parsererror.xml">
+(error description)
+<sourcetext>(a snippet of the source XML)</sourcetext>
+</parsererror>
+
+ +

解譯錯誤也會記錄在錯誤終端機中(Error Console), 紀錄裡頭的文件URI (如下) 則為錯誤來源.

+ +

解譯 SVG 或 HTML 文件

+ +

DOMParser也可以用來解譯 SVG 文件 {{geckoRelease("10.0")}} 或是 HTML 文件 {{geckoRelease("12.0")}}. 可以依 MIME 格式,輸出三種不同格式. 如果MIME 格式是 text/xml,輸出的格式為 XMLDocument, 如果 MIME 格式是 image/svg+xml, 輸出格式為 SVGDocument, 如果 MIME 格式是 text/html, 輸出格式則為 HTMLDocument.

+ +
var parser = new DOMParser();
+var doc = parser.parseFromString(stringContainingXMLSource, "application/xml");
+// returns a Document, but not a SVGDocument nor a HTMLDocument
+
+parser = new DOMParser();
+doc = parser.parseFromString(stringContainingXMLSource, "image/svg+xml");
+// returns a SVGDocument, which also is a Document.
+
+parser = new DOMParser();
+doc = parser.parseFromString(stringContainingHTMLSource, "text/html");
+// returns a HTMLDocument, which also is a Document.
+
+ +

其他瀏覽器可用的DOMParser HTML 外掛程式

+ +
/*
+ * DOMParser HTML extension
+ * 2012-09-04
+ *
+ * By Eli Grey, http://eligrey.com
+ * Public domain.
+ * NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
+ */
+
+/*! @source https://gist.github.com/1129031 */
+/*global document, DOMParser*/
+
+(function(DOMParser) {
+	"use strict";
+
+	var
+	  proto = DOMParser.prototype
+	, nativeParse = proto.parseFromString
+	;
+
+	// Firefox/Opera/IE throw errors on unsupported types
+	try {
+		// WebKit returns null on unsupported types
+		if ((new DOMParser()).parseFromString("", "text/html")) {
+			// text/html parsing is natively supported
+			return;
+		}
+	} catch (ex) {}
+
+	proto.parseFromString = function(markup, type) {
+		if (/^\s*text\/html\s*(?:;|$)/i.test(type)) {
+			var
+			  doc = document.implementation.createHTMLDocument("")
+			;
+	      		if (markup.toLowerCase().indexOf('<!doctype') > -1) {
+        			doc.documentElement.innerHTML = markup;
+      			}
+      			else {
+        			doc.body.innerHTML = markup;
+      			}
+			return doc;
+		} else {
+			return nativeParse.apply(this, arguments);
+		}
+	};
+}(DOMParser));
+
+ +

DOMParser from Chrome/JSM/XPCOM/Privileged Scope

+ +

See article here: nsIDOMParser

+ +

瀏覽器相容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
XML support{{CompatChrome(1)}}{{CompatGeckoDesktop(1)}}{{CompatIE(9)}}{{CompatOpera(8)}}{{CompatSafari(3.2)}}
SVG support{{CompatChrome(4)}}{{CompatGeckoDesktop(10.0)}}{{CompatIE(10)}}{{CompatOpera(15)}}{{CompatSafari(3.2)}}
HTML support{{CompatChrome(30)}}{{CompatGeckoDesktop(12.0)}}{{CompatIE(10)}}{{CompatOpera(17)}}{{CompatSafari(7.1)}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
XML support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
SVG support{{CompatUnknown}}{{CompatGeckoMobile(10.0)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
HTML support{{CompatUnknown}}{{CompatGeckoMobile(12.0)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

參考資料

+ + diff --git a/files/zh-tw/web/api/domstring/index.html b/files/zh-tw/web/api/domstring/index.html new file mode 100644 index 0000000000..396773ce7f --- /dev/null +++ b/files/zh-tw/web/api/domstring/index.html @@ -0,0 +1,50 @@ +--- +title: DOMString +slug: Web/API/DOMString +translation_of: Web/API/DOMString +--- +

{{APIRef("DOM")}}

+ +

DOMString 是編碼為 UTF-16 的字串。當 JavaScript 使用這類字串時, DOMString 會映射成一個 {{jsxref("String")}}.

+ +

傳送 null 給接受 DOMString 的 method 或參數時,會將其轉換成 "null"

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebIDL', '#idl-DOMString', 'DOMString')}}{{Spec2('WebIDL')}}修正定義文件用詞。並移除奇特的極端請況。
{{SpecName('DOM3 Core', 'core.html#DOMString', 'DOMString')}}{{Spec2('DOM3 Core')}}No change from {{SpecName('DOM2 Core')}}
{{SpecName('DOM2 Core', 'core.html#ID-C74D1578', 'DOMString')}}{{Spec2('DOM2 Core')}}No change from {{SpecName('DOM1')}}
{{SpecName('DOM1', 'level-one-core.html#ID-C74D1578', 'DOMString')}}{{Spec2('DOM1')}}初次定義 DOMString 。
+ +

延伸閱讀

+ + diff --git a/files/zh-tw/web/api/domtokenlist/index.html b/files/zh-tw/web/api/domtokenlist/index.html new file mode 100644 index 0000000000..998c3b6e48 --- /dev/null +++ b/files/zh-tw/web/api/domtokenlist/index.html @@ -0,0 +1,117 @@ +--- +title: DOMTokenList +slug: Web/API/DOMTokenList +translation_of: Web/API/DOMTokenList +--- +

{{APIRef("DOM")}}{{gecko_minversion_header("1.9.2")}}

+ +

DOMTokenList 介面表示了一個以空格作為分隔的內容集,通常來自 {{domxref("Element.classList")}}、{{domxref("HTMLLinkElement.relList")}}、{{domxref("HTMLAnchorElement.relList")}} 或 {{domxref("HTMLAreaElement.relList")}} 等屬性。本介面與 {{jsxref("Array")}} 同樣是由 0 開始索引,且 DOMTokenList 是區分大小寫的。

+ +

屬性

+ +

This interface doesn't inherit any property.

+ +
+
{{domxref("DOMTokenList.length")}} {{ReadOnlyInline}}
+
Is an integer representing the number of objects stored in the object.
+
+ +

方法

+ +

This interface doesn't inherit any method.

+ +
+
{{domxref("DOMTokenList.item()")}}
+
Returns an item in the list by its index (or undefined if the number is greater than or equal to the length of the list, prior to {{gecko("7.0")}} returned null)
+
{{domxref("DOMTokenList.contains()")}}
+
Returns true if the underlying string contains token, otherwise false
+
{{domxref("DOMTokenList.add()")}}
+
Adds token to the underlying string
+
{{domxref("DOMTokenList.remove()")}}
+
Removes token from the underlying string
+
{{domxref("DOMTokenList.replace()")}}
+
Replaces an existing token with a new token.
+
{{domxref("DOMTokenList.supports()")}}
+
Returns true if a given token is in the associated attribute's supported tokens.
+
{{domxref("DOMTokenList.toggle()")}}
+
Removes token from string and returns false. If token doesn't exist it's added and the function returns true
+
+ +

規範

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("DOM WHATWG", "#interface-domtokenlist", "DOMTokenList")}}{{Spec2("DOM WHATWG")}}Initial definition
+ +

瀏覽器相容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}10{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
+
+ +

參見

+ + diff --git a/files/zh-tw/web/api/dragevent/datatransfer/index.html b/files/zh-tw/web/api/dragevent/datatransfer/index.html new file mode 100644 index 0000000000..f46de41856 --- /dev/null +++ b/files/zh-tw/web/api/dragevent/datatransfer/index.html @@ -0,0 +1,118 @@ +--- +title: DragEvent.dataTransfer +slug: Web/API/DragEvent/dataTransfer +translation_of: Web/API/DragEvent/dataTransfer +--- +
{{APIRef("HTML Drag and Drop API")}}
+ +

DataEvent.dataTransfer 屬性保留了拖曳操作中的資料(指向一個 {{domxref("DataTransfer")}} 物件)。

+ +

此屬性為 {{readonlyInline}}。

+ +

語法

+ +
var data = dragEvent.dataTransfer;
+
+ +

回傳值

+ +
+
data
+
一個保存 {{domxref("DragEvent")}} 當中資料的 {{domxref("DataTransfer")}} 物件。
+
+ +

範例

+ +

This example illustrates accessing the drag and drop data within the {{event("dragend")}} event handler.

+ +
function process_data(d) {
+   // Process the data ...
+}
+
+dragTarget.addEventListener("dragend", function(ev) {
+   // Call the drag and drop data processor
+   if (ev.dataTransfer != null) process_data(ev.dataTransfer);
+ }, false);
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("HTML WHATWG", "interaction.html#dom-dragevent-datatransfer", "DragEvent.dataTransfer")}}{{Spec2("HTML WHATWG")}} 
{{SpecName("HTML5.1", "editing.html#dom-dragevent-datatransfer", "DragEvent.dataTransfer")}}{{Spec2("HTML5.1")}}Initial definition
+ +

瀏覽器相容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support4{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.1")}}10123.1
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewChrome for AndroidEdgeFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatIE("10")}}{{CompatNo}}{{CompatNo}}
+
diff --git a/files/zh-tw/web/api/dragevent/index.html b/files/zh-tw/web/api/dragevent/index.html new file mode 100644 index 0000000000..45f233ab58 --- /dev/null +++ b/files/zh-tw/web/api/dragevent/index.html @@ -0,0 +1,160 @@ +--- +title: DragEvent +slug: Web/API/DragEvent +translation_of: Web/API/DragEvent +--- +
{{APIRef("HTML Drag and Drop API")}}
+ +

DragEvent 介面是一種 {{domxref("Event","DOM event")}},定義了拖放操作時產生的事件物件。使用者藉由把指標裝置 (例如滑鼠) 放到有效區域並拖移到另一個新的位置 ( 如另外一個 DOM 元素 ) 來開始一個拖動的動作。 而應用程式可以自由地決定互動的方式來達到符合該應用程式的使用情境。

+ + + +

This interface inherits properties from {{domxref("MouseEvent")}} and {{domxref("Event")}}.

+ +

屬性

+ +
+
{{domxref('DragEvent.dataTransfer')}} {{readonlyInline}}
+
The data that is transferred during a drag and drop interaction.
+
+ +

建構式

+ +

Although this interface has a constructor, it is not possible to create a useful DataTransfer object from script, since {{domxref("DataTransfer")}} objects have a processing and security model that is coordinated by the browser during drag-and-drops.

+ +
+
{{domxref("DragEvent.DragEvent", "DragEvent()")}}
+
Creates a synthetic and untrusted DragEvent.
+
+ +

事件類型

+ +
+
{{event('drag')}}
+
在『被選擇的物件』被拖曳時觸發。
+
{{event('dragend')}}
+
在『被選擇的物件』結束拖曳時觸發 (就是放開滑鼠鍵、或按下 Esc 鍵時)。
+
{{event('dragenter')}}
+
當『被選擇的物件』被拖曳到『可以當目標的物件』時, 在『進入』該目標物件上方的瞬間觸發。注意, 不是『被選擇的物件』觸發此事件, 而是『可以當目標的物件』。
+
{{event('dragexit')}}
+
This event is fired when an element is no longer the drag operation's immediate selection target.
+
{{event('dragleave')}}
+
當『被選擇的物件』被拖曳到『可以當目標的物件』時, 在『離開』該目標物件上方的瞬間觸發。注意, 不是『被選擇的物件』觸發此事件, 而是『可以當目標的物件』。
+
{{event('dragover')}}
+
當『被選擇的物件』被拖曳到『可以當目標的物件』的上方時觸發 (頻率大約每秒數次)。注意, 不是『被選擇的物件』觸發此事件, 而是『可以當目標的物件』 。
+
{{event('dragstart')}}
+
在『被選擇的物件』開始拖曳時觸發。
+
{{event('drop')}}
+
當『被選擇的物件』被拖曳、放到『目標物件』時觸發。注意, 不是『被選擇的物件』觸發此事件, 而是『目標物件』。
+
+ +

通用事件處理器

+ +
+
{{domxref('GlobalEventHandlers.ondrag')}}
+
A {{domxref('GlobalEventHandlers','global event handler')}} for the {{event('drag')}} event.
+
{{domxref('GlobalEventHandlers.ondragend')}}
+
A {{domxref('GlobalEventHandlers','global event handler')}} for the {{event('dragend')}} event.
+
{{domxref('GlobalEventHandlers.ondragenter')}}
+
A {{domxref('GlobalEventHandlers','global event handler')}} for the {{event('dragenter')}} event.
+
{{domxref('GlobalEventHandlers.ondragexit')}}
+
A {{domxref('GlobalEventHandlers','global event handler')}} for the {{event('dragexit')}} event.
+
{{domxref('GlobalEventHandlers.ondragleave')}}
+
A {{domxref('GlobalEventHandlers','global event handler')}} for the {{event('dragleave')}} event.
+
{{domxref('GlobalEventHandlers.ondragover')}}
+
A {{domxref('GlobalEventHandlers','global event handler')}} for the {{event('dragover')}} event.
+
{{domxref('GlobalEventHandlers.ondragstart')}}
+
A {{domxref('GlobalEventHandlers','global event handler')}} for the {{event('dragstart')}} event.
+
{{domxref('GlobalEventHandlers.ondrop')}}
+
A {{domxref('GlobalEventHandlers','global event handler')}} for the {{event('drop')}} event.
+
+ +

範例

+ +

An Example of each property, constructor, event type and global event handlers is included in their respective reference page.

+ +

規範

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("HTML WHATWG", "interaction.html#the-dragevent-interface", "DragEvent")}}{{Spec2("HTML WHATWG")}}
{{SpecName("HTML5.1", "editing.html#the-dragevent-interface", "DragEvent")}}{{Spec2("HTML5.1")}}Initial definition
+ +

瀏覽器相容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support4{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.1")}}10123.1
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewChrome for AndroidEdgeFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatIE("10")}}{{CompatNo}}{{CompatNo}}
+
+ +

參見

+ +

{{page("/zh-TW/docs/Web/API/DataTransfer", "參見")}}

diff --git a/files/zh-tw/web/api/element/attributes/index.html b/files/zh-tw/web/api/element/attributes/index.html new file mode 100644 index 0000000000..ce24985c8b --- /dev/null +++ b/files/zh-tw/web/api/element/attributes/index.html @@ -0,0 +1,121 @@ +--- +title: Element.attributes +slug: Web/API/Element/attributes +translation_of: Web/API/Element/attributes +--- +

{{ APIRef("DOM") }}

+ +

 

+ +

The Element.attributes property returns a live collection of all attribute nodes registered to the specified node. It is a {{domxref("NamedNodeMap")}}, not an Array, so it has no {{jsxref("Array")}} methods and the {{domxref("Attr")}} nodes' indexes may differ among browsers. To be more specific, attributes is a key/value pair of strings that represents any information regarding that attribute.

+ +

 

+ +

Element.attribute 特性會把特定節點裡所有的屬性變成一個集合,然後回傳出來. 這是一個  NamedNodeMap, 而並非一個陣列. 所以它並沒有陣列的方法和在瀏覽器中  Attr節點裡的索引值也可能不同. 更詳細的來說, attributes 是一個鍵/值的配對, 它包含了所有有關於這個節點屬性的資訊

+ +

 

+ +

Syntax

+ +
var attr = element.attributes;
+
+ +

Example

+ +

Basic examples

+ +
// Get the first <p> element in the document
+var para = document.getElementsByTagName("p")[0];
+var atts = para.attributes;
+ +

Enumerating elements attributes

+ +

Numerical indexing is useful for going through all of an element's attributes.
+ The following example runs through the attribute nodes for the element in the document with id "paragraph", and prints each attribute's value.

+ +
<!DOCTYPE html>
+
+<html>
+
+ <head>
+  <title>Attributes example</title>
+  <script type="text/javascript">
+   function listAttributes() {
+     var paragraph = document.getElementById("paragraph");
+     var result = document.getElementById("result");
+
+     // First, let's verify that the paragraph has some attributes
+     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 = "No attributes to show";
+     }
+   }
+  </script>
+ </head>
+
+<body>
+ <p id="paragraph" style="color: green;">Sample Paragraph</p>
+ <form action="">
+  <p>
+    <input type="button" value="Show first attribute name and value"
+      onclick="listAttributes();">
+    <input id="result" type="text" value="">
+  </p>
+ </form>
+</body>
+</html>
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-element-attributes', 'Element.attributes')}}{{Spec2('DOM WHATWG')}}From {{SpecName('DOM3 Core')}}, moved from {{domxref("Node")}} to {{domxref("Element")}}
{{SpecName('DOM3 Core', 'core.html#ID-84CF096', 'Element.attributes')}}{{Spec2('DOM3 Core')}}No change from {{SpecName('DOM2 Core')}}
{{SpecName('DOM2 Core', 'core.html#ID-84CF096', 'Element.attributes')}}{{Spec2('DOM2 Core')}}No change from {{SpecName('DOM1')}}
{{SpecName('DOM1', 'level-one-core.html#ID-84CF096', 'Element.attributes')}}{{Spec2('DOM1')}}Initial definition.
+ +

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/zh-tw/web/api/element/classlist/index.html b/files/zh-tw/web/api/element/classlist/index.html new file mode 100644 index 0000000000..afa5b7c862 --- /dev/null +++ b/files/zh-tw/web/api/element/classlist/index.html @@ -0,0 +1,403 @@ +--- +title: Element.classList +slug: Web/API/Element/classList +translation_of: Web/API/Element/classList +--- +
{{APIRef("DOM")}}
+ +

Element.classList 唯讀屬性代表了該元素所擁有之類別屬性(Class {{Glossary("Attribute")}})的即時更新集-{{domxref("DOMTokenList")}}。

+ +

使用 classList 屬性是取得元素 Class 的一種便利方式,也可以透過 {{domxref("element.className")}} 來得到以空格分隔之 Class 清單字串。

+ +

語法

+ +
var elementClasses = elementNodeReference.classList;
+
+ +

elementClasses is a {{domxref("DOMTokenList")}} representing the class attribute of elementNodeReference. If the class attribute was not set or is empty elementClasses.length returns 0. element.classList itself is read-only, although you can modify it using the add() and remove() methods.

+ +

方法

+ +
+
add( String [, String] )
+
Add specified class values. If these classes already exist in attribute of the element, then they are ignored.
+
remove( String [,String] )
+
Remove specified class values.
+
item ( Number )
+
Return class value by index in collection.
+
toggle ( String [, force] )
+
When only one argument is present: Toggle class value; i.e., if class exists then remove it and return false, if not, then add it and return true.
+ When a second argument is present: If the second argument is true, add specified class value, and if it is false, remove it.
+
contains( String )
+
Checks if specified class value exists in class attribute of the element.
+
+ +

範例

+ +
// div is an object reference to a <div> element with class="foo bar"
+div.classList.remove("foo");
+div.classList.add("anotherclass");
+
+// if visible is set remove it, otherwise add it
+div.classList.toggle("visible");
+
+//  add/remove visible, depending on test conditional, i less than 10
+div.classList.toggle("visible", i < 10 );
+
+alert(div.classList.contains("foo"));
+
+div.classList.add("foo","bar"); //add multiple classes
+ +
+

Versions of Firefox before 26 do not implement the use of several arguments in the add/remove/toggle methods. See https://bugzilla.mozilla.org/show_bug.cgi?id=814014

+
+ +

JavaScript shim for other implementations

+ +
Note: This shim does not work in Internet Explorer versions less than 8.
+ +
/*
+ * classList.js: Cross-browser full element.classList implementation.
+ * 2014-07-23
+ *
+ * By Eli Grey, http://eligrey.com
+ * Public Domain.
+ * NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
+ */
+
+/*global self, document, DOMException */
+
+/*! @source http://purl.eligrey.com/github/classList.js/blob/master/classList.js*/
+
+if ("document" in self) {
+
+// Full polyfill for browsers with no classList support
+if (!("classList" in document.createElement("_"))) {
+
+(function (view) {
+
+"use strict";
+
+if (!('Element' in view)) return;
+
+var
+    classListProp = "classList"
+  , protoProp = "prototype"
+  , elemCtrProto = view.Element[protoProp]
+  , objCtr = Object
+  , strTrim = String[protoProp].trim || function () {
+    return this.replace(/^\s+|\s+$/g, "");
+  }
+  , arrIndexOf = Array[protoProp].indexOf || function (item) {
+    var
+        i = 0
+      , len = this.length
+    ;
+    for (; i < len; i++) {
+      if (i in this && this[i] === item) {
+        return i;
+      }
+    }
+    return -1;
+  }
+  // Vendors: please allow content code to instantiate DOMExceptions
+  , DOMEx = function (type, message) {
+    this.name = type;
+    this.code = DOMException[type];
+    this.message = message;
+  }
+  , checkTokenAndGetIndex = function (classList, token) {
+    if (token === "") {
+      throw new DOMEx(
+          "SYNTAX_ERR"
+        , "An invalid or illegal string was specified"
+      );
+    }
+    if (/\s/.test(token)) {
+      throw new DOMEx(
+          "INVALID_CHARACTER_ERR"
+        , "String contains an invalid character"
+      );
+    }
+    return arrIndexOf.call(classList, token);
+  }
+  , ClassList = function (elem) {
+    var
+        trimmedClasses = strTrim.call(elem.getAttribute("class") || "")
+      , classes = trimmedClasses ? trimmedClasses.split(/\s+/) : []
+      , i = 0
+      , len = classes.length
+    ;
+    for (; i < len; i++) {
+      this.push(classes[i]);
+    }
+    this._updateClassName = function () {
+      elem.setAttribute("class", this.toString());
+    };
+  }
+  , classListProto = ClassList[protoProp] = []
+  , classListGetter = function () {
+    return new ClassList(this);
+  }
+;
+// Most DOMException implementations don't allow calling DOMException's toString()
+// on non-DOMExceptions. Error's toString() is sufficient here.
+DOMEx[protoProp] = Error[protoProp];
+classListProto.item = function (i) {
+  return this[i] || null;
+};
+classListProto.contains = function (token) {
+  token += "";
+  return checkTokenAndGetIndex(this, token) !== -1;
+};
+classListProto.add = function () {
+  var
+      tokens = arguments
+    , i = 0
+    , l = tokens.length
+    , token
+    , updated = false
+  ;
+  do {
+    token = tokens[i] + "";
+    if (checkTokenAndGetIndex(this, token) === -1) {
+      this.push(token);
+      updated = true;
+    }
+  }
+  while (++i < l);
+
+  if (updated) {
+    this._updateClassName();
+  }
+};
+classListProto.remove = function () {
+  var
+      tokens = arguments
+    , i = 0
+    , l = tokens.length
+    , token
+    , updated = false
+    , index
+  ;
+  do {
+    token = tokens[i] + "";
+    index = checkTokenAndGetIndex(this, token);
+    while (index !== -1) {
+      this.splice(index, 1);
+      updated = true;
+      index = checkTokenAndGetIndex(this, token);
+    }
+  }
+  while (++i < l);
+
+  if (updated) {
+    this._updateClassName();
+  }
+};
+classListProto.toggle = function (token, force) {
+  token += "";
+
+  var
+      result = this.contains(token)
+    , method = result ?
+      force !== true && "remove"
+    :
+      force !== false && "add"
+  ;
+
+  if (method) {
+    this[method](token);
+  }
+
+  if (force === true || force === false) {
+    return force;
+  } else {
+    return !result;
+  }
+};
+classListProto.toString = function () {
+  return this.join(" ");
+};
+
+if (objCtr.defineProperty) {
+  var classListPropDesc = {
+      get: classListGetter
+    , enumerable: true
+    , configurable: true
+  };
+  try {
+    objCtr.defineProperty(elemCtrProto, classListProp, classListPropDesc);
+  } catch (ex) { // IE 8 doesn't support enumerable:true
+    if (ex.number === -0x7FF5EC54) {
+      classListPropDesc.enumerable = false;
+      objCtr.defineProperty(elemCtrProto, classListProp, classListPropDesc);
+    }
+  }
+} else if (objCtr[protoProp].__defineGetter__) {
+  elemCtrProto.__defineGetter__(classListProp, classListGetter);
+}
+
+}(self));
+
+} else {
+// There is full or partial native classList support, so just check if we need
+// to normalize the add/remove and toggle APIs.
+
+(function () {
+  "use strict";
+
+  var testElement = document.createElement("_");
+
+  testElement.classList.add("c1", "c2");
+
+  // Polyfill for IE 10/11 and Firefox <26, where classList.add and
+  // classList.remove exist but support only one argument at a time.
+  if (!testElement.classList.contains("c2")) {
+    var createMethod = function(method) {
+      var original = DOMTokenList.prototype[method];
+
+      DOMTokenList.prototype[method] = function(token) {
+        var i, len = arguments.length;
+
+        for (i = 0; i < len; i++) {
+          token = arguments[i];
+          original.call(this, token);
+        }
+      };
+    };
+    createMethod('add');
+    createMethod('remove');
+  }
+
+  testElement.classList.toggle("c3", false);
+
+  // Polyfill for IE 10 and Firefox <24, where classList.toggle does not
+  // support the second argument.
+  if (testElement.classList.contains("c3")) {
+    var _toggle = DOMTokenList.prototype.toggle;
+
+    DOMTokenList.prototype.toggle = function(token, force) {
+      if (1 in arguments && !this.contains(token) === !force) {
+        return force;
+      } else {
+        return _toggle.call(this, token);
+      }
+    };
+
+  }
+
+  testElement = null;
+}());
+
+}
+
+}
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("HTML WHATWG", "dom.html#dom-classlist", "Element.classList")}}{{Spec2("HTML WHATWG")}}Note within the HTML specification related to the {{htmlattrxref("class")}} attribute.
{{SpecName("DOM WHATWG", "#dom-element-classlist", "Element.classList")}}{{Spec2("DOM WHATWG")}}Initial definition
{{SpecName("DOM4", "#dom-element-classlist", "Element.classList")}}{{Spec2("DOM4")}} 
+ +

瀏覽器相容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support8.0{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.2")}}10[1]11.505.1
toggle method's second argument24{{CompatVersionUnknown}}{{CompatGeckoDesktop("24")}}{{CompatNo}}[2]155.1
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support3.0{{CompatGeckoMobile("1.9.2")}}1011.105.0
toggle method's second argument{{CompatUnknown}}{{CompatGeckoMobile("24")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Not supported for SVG elements.  See a report at Microsoft about that.
+ [2] Internet Explorer never implemented this. See a report at Microsoft about that.

+ +

參見

+ + diff --git a/files/zh-tw/web/api/element/click_event/index.html b/files/zh-tw/web/api/element/click_event/index.html new file mode 100644 index 0000000000..4c7044e4b3 --- /dev/null +++ b/files/zh-tw/web/api/element/click_event/index.html @@ -0,0 +1,205 @@ +--- +title: click +slug: Web/API/Element/click_event +tags: + - 待翻譯 +translation_of: Web/API/Element/click_event +--- +

click 事件通常會在設備的按鈕(通常是滑鼠按鍵)點擊元素時執行。

+ +

基本資料

+ +
+
詳述
+
DOM L3
+
介面
+
{{domxref("MouseEvent")}}
+
Bubbles
+
Yes
+
Cancelable
+
Yes
+
Target
+
網頁元素
+
Default Action
+
Varies
+
+ +

Properties

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
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)A count of consecutive clicks that happened in a short amount of time, incremented by one.
currentTarget {{readonlyInline}}EventTargetThe node that had the event listener attached.
relatedTarget {{readonlyInline}}EventTargetFor 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.
+ +

範例

+ +
<div id="test"></div>
+
+<script>
+  document.getElementById("test").addEventListener("click", function( event ) {
+    // 在 “clicked div”顯示點擊次數
+    event.target.innerHTML = "click count: " + event.detail;
+  }, false);
+</script>
+
+ +

Browser compatibility

+ +

Internet Explorer

+ +

Internet Explorer 8 & 9 suffer from a bug where elements with a computed {{cssxref("background-color")}} of transparent that are overlaid on top of other element(s) won't receive click events. Any click events will be fired at the underlying element(s) instead. See this live example for a demonstration.

+ +

Known workarounds for this 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):

+ + + +

關聯事件

+ + diff --git a/files/zh-tw/web/api/element/clientheight/index.html b/files/zh-tw/web/api/element/clientheight/index.html new file mode 100644 index 0000000000..99ae4faf06 --- /dev/null +++ b/files/zh-tw/web/api/element/clientheight/index.html @@ -0,0 +1,62 @@ +--- +title: Element.clientHeight +slug: Web/API/Element/clientHeight +tags: + - API + - Reference +translation_of: Web/API/Element/clientHeight +--- +

{{ APIRef("DOM") }}

+ +

Element.clientHeight 唯讀屬性會回傳元素內部高度(像素),包含 padding 但並未包含水平滾動條、border、margin。

+ +

clientHeight 可以被計算成 CSS height + CSS padding - 水平滾動條的高度(如果有顯示)

+ +
+

Note: 這個屬性會以四捨五入進位取整數. 如果要使用非整數值, 使用 {{ domxref("element.getBoundingClientRect()") }}.

+
+ +

表達式

+ +
var h = element.clientHeight;
+ +

h 代表元素高度(pixels)的正整數.

+ +

範例

+ +

 

+ +

             Image:Dimensions-client.png

+ + +

規範

+ + + + + + + + + + + + + + + + +
規範狀態
{{SpecName('CSSOM View', '#dom-element-clientheight', 'clientHeight')}}{{Spec2('CSSOM View')}} 
+ +

+ +

clientHeight 是在 the Internet Explorer 物件介紹的屬性.

+ +

參見

+ + diff --git a/files/zh-tw/web/api/element/getattribute/index.html b/files/zh-tw/web/api/element/getattribute/index.html new file mode 100644 index 0000000000..e5b7a1c27e --- /dev/null +++ b/files/zh-tw/web/api/element/getattribute/index.html @@ -0,0 +1,71 @@ +--- +title: Element.getAttribute() +slug: Web/API/Element/getAttribute +translation_of: Web/API/Element/getAttribute +--- +
{{APIRef("DOM")}}
+ +

摘要

+ +

getAttribute() 函式會回傳該網頁元素的屬性。 如果該屬性不存在,其回傳值會是null或 "" (空字串); 詳見 {{Anch("Notes")}} 。

+ +

語法

+ +
var attribute = element.getAttribute(attributeName);
+
+ +

where

+ + + +

Example

+ +
var div1 = document.getElementById("div1");
+var align = div1.getAttribute("align");
+
+alert(align); // shows the value of align for the element with id="div1"
+ +

Notes

+ +

When called on an HTML element in a DOM flagged as an HTML document, getAttribute() lower-cases its argument before proceeding.

+ +

Essentially all web browsers (Firefox, Internet Explorer, recent versions of Opera, Safari, Konqueror, and iCab, as a non-exhaustive list) return null when the specified attribute does not exist on the specified element and this is what the current DOM specification draft specifies. The old DOM 3 Core specification, on the other hand, says that the correct return value in this case is actually the empty string, and some DOM implementations implement this behavior. The implementation of getAttribute in XUL (Gecko) actually follows the DOM 3 Core specification and returns an empty string. Consequently, you should use {{domxref("element.hasAttribute()")}} to check for an attribute's existence prior to calling getAttribute() if it is possible that the requested attribute does not exist on the specified element.

+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support2923{{CompatVersionUnknown}}{{CompatVersionUnknown}}6
+
+ +
{{DOMAttributeMethods}}
+ +

Specification

+ + diff --git a/files/zh-tw/web/api/element/index.html b/files/zh-tw/web/api/element/index.html new file mode 100644 index 0000000000..d363baeead --- /dev/null +++ b/files/zh-tw/web/api/element/index.html @@ -0,0 +1,674 @@ +--- +title: Element +slug: Web/API/Element +tags: + - API + - DOM + - DOM Reference + - Element + - NeedsTranslation + - TopicStub + - Élément(2) +translation_of: Web/API/Element +--- +

{{ APIRef("DOM") }}

+ +

Element 介面表示了一個在 {{domxref("Document")}} 中的物件,其描述了各類型元素的共同屬性與方法,Element 的子介面則定義了不同類型元素的具體行為並增加額外的功能。例如 {{domxref("HTMLElement")}} 為所有 HTML 元素的基礎介面,而 {{domxref("SVGElement")}} 則是定義所有 SVG 元素的介面。

+ +

在 Web 領域之外,如 XUL 語言也能藉由 XULElement 介面來繼承 Element

+ +

{{InheritanceDiagram}}

+ +

屬性

+ +

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

+ +
+
{{ domxref("Element.assignedSlot")}} {{experimental_inline}} {{readOnlyInline}}
+
Returns the {{domxref("HTMLSlotElement")}} interface associated with the element.
+
{{ domxref("Element.attributes") }} {{readOnlyInline}}
+
Returns a {{ domxref("NamedNodeMap") }} object containing the assigned attributes of the corresponding HTML element.
+
{{ domxref("Element.classList") }} {{readOnlyInline}}
+
Returns a {{ domxref("DOMTokenList") }} containing the list of class attributes.
+
{{ domxref("Element.className") }}
+
Is a {{domxref("DOMString")}} representing the class of the element.
+
{{ domxref("Element.clientHeight") }} {{experimental_inline}} {{readOnlyInline}}
+
Returns a {{jsxref("Number")}} representing the inner height of the element.
+
{{ domxref("Element.clientLeft") }} {{experimental_inline}} {{readOnlyInline}}
+
Returns a {{jsxref("Number")}} representing the width of the left border of the element.
+
{{ domxref("Element.clientTop") }} {{experimental_inline}} {{readOnlyInline}}
+
Returns a {{jsxref("Number")}} representing the width of the top border of the element.
+
{{ domxref("Element.clientWidth") }} {{experimental_inline}} {{readOnlyInline}}
+
Returns a {{jsxref("Number")}} representing the inner width of the element.
+
{{domxref("Element.computedName")}} {{readOnlyInline}}
+
Returns a {{domxref("DOMString")}} containing the label exposed to accessibility.
+
{{domxref("Element.computedRole")}} {{readOnlyInline}}
+
Returns a {{domxref("DOMString")}} containing the ARIA role that has been applied to a particular element.
+
{{ domxref("Element.id") }}
+
Is a {{domxref("DOMString")}} representing the id of the element.
+
{{ domxref("Element.innerHTML") }}
+
Is a {{domxref("DOMString")}} representing the markup of the element's content.
+
{{ domxref("Element.localName") }} {{readOnlyInline}}
+
A {{domxref("DOMString")}} representing the local part of the qualified name of the element.
+
{{domxref("Element.namespaceURI")}} {{readonlyInline}}
+
The namespace URI of the element, or null if it is no namespace. +
+

Note: In Firefox 3.5 and earlier, HTML elements are in no namespace. In later versions, HTML elements are in the http://www.w3.org/1999/xhtml namespace in both HTML and XML trees. {{ gecko_minversion_inline("1.9.2") }}

+
+
+
{{ domxref("NonDocumentTypeChildNode.nextElementSibling") }} {{readOnlyInline}}
+
Is a {{ domxref("Element") }}, the element immediately following the given one in the tree, or null if there's no sibling node.
+
{{ domxref("Element.outerHTML") }} {{experimental_inline}}
+
Is a {{domxref("DOMString")}} representing the markup of the element including its content. When used as a setter, replaces the element with nodes parsed from the given string.
+
{{ domxref("Element.prefix") }} {{readOnlyInline}}
+
A {{domxref("DOMString")}} representing the namespace prefix of the element, or null if no prefix is specified.
+
{{ domxref("NonDocumentTypeChildNode.previousElementSibling") }} {{readOnlyInline}}
+
Is a {{ domxref("Element") }}, the element immediately preceding the given one in the tree, or null if there is no sibling element.
+
{{ domxref("Element.scrollHeight") }} {{experimental_inline}} {{readOnlyInline}}
+
Returns a {{jsxref("Number")}} representing the scroll view height of an element.
+
{{ domxref("Element.scrollLeft") }} {{experimental_inline}}
+
Is a {{jsxref("Number")}} representing the left scroll offset of the element.
+
{{ domxref("Element.scrollLeftMax") }} {{non-standard_inline}} {{readOnlyInline}}
+
Returns a {{jsxref("Number")}} representing the maximum left scroll offset possible for the element.
+
{{ domxref("Element.scrollTop") }} {{experimental_inline}}
+
Is a {{jsxref("Number")}} representing the top scroll offset the an element.
+
{{ domxref("Element.scrollTopMax") }} {{non-standard_inline}} {{readOnlyInline}}
+
Returns a {{jsxref("Number")}} representing the maximum top scroll offset possible for the element.
+
{{ domxref("Element.scrollWidth") }} {{experimental_inline}} {{readOnlyInline}}
+
Returns a {{jsxref("Number")}} representing the scroll view width of the element.
+
{{domxref("Element.shadowRoot") }} {{experimental_inline}} {{readOnlyInline}}
+
Returns the youngest shadow root that is hosted by the element.
+
{{domxref("Element.slot")}} {{experimental_inline}}
+
Returns the name of the shadow DOM slot attatched to the element. A slot is a placeholder inside a web component that users can fill with their own markup.
+
{{domxref("Element.tabStop")}} {{non-standard_inline}}
+
Is a {{jsxref("Boolean")}} indicating if the element can receive input focus via the tab key.
+
{{ domxref("Element.tagName") }} {{readOnlyInline}}
+
Returns a {{domxref("String")}} with the name of the tag for the given element.
+
{{ domxref("Element.undoManager")}} {{experimental_inline}} {{readOnlyInline}}
+
Returns the {{domxref("UndoManager")}} associated with the element.
+
{{ domxref("Element.undoScope")}} {{experimental_inline}}
+
Is a {{jsxref("Boolean")}} indicating if the element is an undo scope host, or not.
+
+ +
+

Note: DOM Level 3 defined namespaceURI, localName and prefix on the {{domxref("Node")}} interface. In DOM4 they were moved to Element.

+ +

This change is implemented in Chrome since version 46.0 and Firefox since version 48.0.

+
+ +

事件處理器

+ +
+
{{ domxref("Element.ongotpointercapture") }}
+
Returns the event handler for the {{event("gotpointercapture")}} event type.
+
{{ domxref("Element.onlostpointercapture") }}
+
Returns the event handler for the {{event("lostpointercapture")}} event type.
+
{{ domxref("Element.onwheel") }} {{ non-standard_inline() }}
+
Returns the event handling code for the wheel event.
+
+ +

方法

+ +

Inherits methods from its parents {{domxref("Node")}}, and its own parent, {{domxref("EventTarget")}}, and implements those of {{domxref("ParentNode")}}, {{domxref("ChildNode")}}, {{domxref("NonDocumentTypeChildNode")}}, and {{domxref("Animatable")}}.

+ +
+
{{ domxref("EventTarget.addEventListener()") }}
+
Registers an event handler to a specific event type on the element.
+
{{domxref("Element.attachShadow()")}} {{experimental_inline}}
+
Attatches a shadow DOM tree to the specified element and returns a reference to its {{domxref("ShadowRoot")}}.
+
{{domxref("Element.animate()")}} {{experimental_inline}}
+
A shortcut method to create and run an animation on an element. Returns the created Animation object instance.
+
{{ domxref("Element.closest()")}} {{experimental_inline}}
+
Returns the {{domxref("Element")}}, descendant of this element (or this element itself), that is the closest ancestor of the elements selected by the selectors given in parameter.
+
{{ domxref("Element.createShadowRoot()")}} {{experimental_inline}} {{deprecated_inline()}}
+
Creates a shadow DOM on on the element, turning it into a shadow host. Returns a {{domxref("ShadowRoot")}}.
+
{{ domxref("EventTarget.dispatchEvent()") }}
+
Dispatches an event to this node in the DOM and returns a {{jsxref("Boolean")}} that indicates that at least one handler has not canceled it.
+
{{domxref("Element.find()")}}{{experimental_inline}}
+
...
+
{{domxref("Element.findAll()")}}{{experimental_inline}}
+
...
+
{{domxref("Element.getAnimations()")}} {{experimental_inline}}
+
Returns an array of Animation objects currently active on the element.
+
{{ domxref("Element.getAttribute()") }}
+
Retrieves the value of the named attribute from the current node and returns it as an {{jsxref("Object")}}.
+
{{ domxref("Element.getAttributeNames()") }}
+
 
+
{{ domxref("Element.getAttributeNS()") }}
+
Retrieves the value of the attribute with the specified name and namespace, from the current node and returns it as an {{jsxref("Object")}}.
+
{{ domxref("Element.getAttributeNode()") }} {{obsolete_inline}}
+
Retrieves the node representation of the named attribute from the current node and returns it as an {{ domxref("Attr") }}.
+
{{ domxref("Element.getAttributeNodeNS()") }} {{obsolete_inline}}
+
Retrieves the node representation of the attribute with the specified name and namespace, from the current node and returns it as an {{ domxref("Attr") }}.
+
{{ domxref("Element.getBoundingClientRect()") }}
+
...
+
{{ domxref("Element.getClientRects()") }}
+
Returns a collection of rectangles that indicate the bounding rectangles for each line of text in a client.
+
{{domxref("Element.getDestinationInsertionPoints()")}} {{experimental_inline}}
+
+
{{ domxref("Element.getElementsByClassName()") }}
+
Returns a live {{ domxref("HTMLCollection") }} that contains all descendants of the current element that possess the list of classes given in the parameter.
+
{{ domxref("Element.getElementsByTagName()") }}
+
Returns a live {{ domxref("HTMLCollection") }} containing all descendant elements, of a particular tag name, from the current element.
+
{{ domxref("Element.getElementsByTagNameNS()") }}
+
Returns a live {{ domxref("HTMLCollection") }} containing all descendant elements, of a particular tag name and namespace, from the current element.
+
{{ domxref("Element.hasAttribute()") }}
+
Returns a {{jsxref("Boolean")}} indicating if the element has the specified attribute or not.
+
{{ domxref("Element.hasAttributeNS()") }}
+
Returns a {{jsxref("Boolean")}} indicating if the element has the specified attribute, in the specified namespace, or not.
+
{{ domxref("Element.hasAttributes()") }}
+
Returns a {{jsxref("Boolean")}} indicating if the element has one or more HTML attributes present.
+
{{ domxref("Element.insertAdjacentElement") }} {{experimental_inline}}
+
Inserts a given element node at a given position relative to the element it is invoked upon.
+
{{ domxref("Element.insertAdjacentHTML") }} {{experimental_inline}}
+
Parses the text as HTML or XML and inserts the resulting nodes into the tree in the position given.
+
{{ domxref("Element.insertAdjacentText") }} {{experimental_inline}}
+
Inserts a given text node at a given position relative to the element it is invoked upon.
+
{{ domxref("Element.matches()") }} {{experimental_inline}}
+
Returns a {{jsxref("Boolean")}} indicating whether or not the element would be selected by the specified selector string.
+
{{ domxref("Element.querySelector()") }}
+
Returns the first {{ domxref("Node") }} which matches the specified selector string relative to the element.
+
{{ domxref("Element.querySelectorAll") }}
+
Returns a {{ domxref("NodeList") }} of nodes which match the specified selector string relative to the element.
+
{{ domxref("Element.releasePointerCapture")}}
+
Releases (stops) pointer capture that was previously set for a specific {{domxref("PointerEvent","pointer event")}}.
+
{{domxref("ChildNode.remove()")}} {{experimental_inline}}
+
Removes the element from the children list of its parent.
+
{{ domxref("Element.removeAttribute()") }}
+
Removes the named attribute from the current node.
+
{{ domxref("Element.removeAttributeNS()") }}
+
Removes the attribute with the specified name and namespace, from the current node.
+
{{ domxref("Element.removeAttributeNode()") }} {{obsolete_inline}}
+
Removes the node representation of the named attribute from the current node.
+
{{ domxref("EventTarget.removeEventListener()") }}
+
Removes an event listener from the element.
+
{{ domxref("Element.requestFullscreen()") }} {{experimental_inline}}
+
Asynchronously asks the browser to make the element full-screen.
+
{{ domxref("Element.requestPointerLock()")}} {{experimental_inline}}
+
Allows to asynchronously ask for the pointer to be locked on the given element.
+
+ +
+
{{ domxref("Element.scrollIntoView()") }} {{experimental_inline}}
+
Scrolls the page until the element gets into the view.
+
{{ domxref("Element.setAttribute()") }}
+
Sets the value of a named attribute of the current node.
+
{{ domxref("Element.setAttributeNS()") }}
+
Sets the value of the attribute with the specified name and namespace, from the current node.
+
{{ domxref("Element.setAttributeNode()") }} {{obsolete_inline}}
+
Sets the node representation of the named attribute from the current node.
+
{{ domxref("Element.setAttributeNodeNS()") }} {{obsolete_inline}}
+
Setw the node representation of the attribute with the specified name and namespace, from the current node.
+
{{ domxref("Element.setCapture()") }} {{non-standard_inline}}
+
Sets up mouse event capture, redirecting all mouse events to this element.
+
{{domxref("Element.setPointerCapture()")}}
+
Designates a specific element as the capture target of future {{domxref("PointerEvent","pointer events")}}.
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Shadow DOM')}}{{Spec2('Shadow DOM')}} 
{{SpecName("Web Animations", '', '')}}{{Spec2("Web Animations")}}Added the getAnimations() method.
{{SpecName('Undo Manager', '', 'Element')}}{{Spec2('Undo Manager')}}Added the undoScope and undoManager properties.
{{SpecName('Pointer Events 2', '#extensions-to-the-element-interface', 'Element')}}{{Spec2('Pointer Events 2')}}Added the following event handlers: ongotpointercapture and onlostpointercapture.
+ Added the following methods: setPointerCapture() and releasePointerCapture().
{{SpecName('Pointer Events', '#extensions-to-the-element-interface', 'Element')}}{{Spec2('Pointer Events')}}Added the following event handlers: ongotpointercapture and onlostpointercapture.
+ Added the following methods: setPointerCapture() and releasePointerCapture().
{{SpecName('Selectors API Level 2', '#interface-definitions', 'Element')}}{{Spec2('Selectors API Level 2')}}Added the following methods: matches() (implemented as mozMatchesSelector()), find(), findAll().
{{SpecName('Selectors API Level 1', '#interface-definitions', 'Element')}}{{Spec2('Selectors API Level 1')}}Added the following methods: querySelector() and querySelectorAll().
{{SpecName('Pointer Lock', 'index.html#element-interface', 'Element')}}{{Spec2('Pointer Lock')}}Added the requestPointerLock() method.
{{SpecName('Fullscreen', '#api', 'Element')}}{{Spec2('Fullscreen')}}Added the requestFullscreen() method.
{{SpecName('DOM Parsing', '#extensions-to-the-element-interface', 'Element')}}{{Spec2('DOM Parsing')}}Added the following properties: innerHTML, and outerHTML.
+ Added the following method: insertAdjacentHTML().
{{SpecName('CSSOM View', '#extensions-to-the-element-interface', 'Element')}}{{Spec2('CSSOM View')}}Added the following properties: scrollTop, scrollLeft, scrollWidth, scrollHeight, clientTop, clientLeft, clientWidth, and clientHeight.
+ Added the following methods: getClientRects(), getBoundingClientRect(), and scrollIntoView().
{{SpecName('Element Traversal', '#ecmascript-bindings', 'Element')}}{{Spec2('Element Traversal')}}Added inheritance of the {{domxref("ElementTraversal")}} interface.
{{SpecName('DOM WHATWG', '#interface-element', 'Element')}}{{Spec2('DOM WHATWG')}}Removed the following methods: closest(), setIdAttribute(), setIdAttributeNS(), and setIdAttributeNode().
+ Removed the schemaTypeInfo property.
+ Modified the return value of getElementsByTag() and getElementsByTagNS().
+ Moved hasAttributes() from the Node interface to this one.
+ Inserted insertAdjacentElement() and insertAdjacentText().
{{SpecName('DOM3 Core', 'core.html#ID-745549614', 'Element')}}{{Spec2('DOM3 Core')}}Added the following methods: setIdAttribute(), setIdAttributeNS(), and setIdAttributeNode(). These methods were never implemented and have been removed in later specifications.
+ Added the schemaTypeInfo property. This property was never implemented and has been removed in later specifications.
{{SpecName('DOM2 Core', 'core.html#ID-745549614', 'Element')}}{{Spec2('DOM2 Core')}}The normalize() method has been moved to {{domxref("Node")}}.
{{SpecName('DOM1', 'level-one-core.html#ID-745549614', 'Element')}}{{Spec2('DOM1')}}Initial definition.
+ +

瀏覽器相容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support1.0{{CompatVersionUnknown}}{{CompatGeckoDesktop("1")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}1.0
children{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9")}}7.0 with a significant bug [1]
+ 9.0 according to the spec
{{CompatVersionUnknown}}{{CompatNo}}
childElementCount, nextElementSibling, previousElementSibling{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.1")}}9.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}
firstElementChild, lastElementChild{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9")}}9.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}
classList{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.2")}} {{CompatVersionUnknown}}{{CompatVersionUnknown}}
outerHTML {{experimental_inline}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("11")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
clientLeft, clientTop {{experimental_inline}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.1")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
getBoundingClientRect(), getClientRects() {{experimental_inline}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
querySelector(), querySelectorAll()1.0{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.1")}}8.010.03.2 (525.3)
insertAdjacentHTML() {{experimental_inline}}1.0{{CompatVersionUnknown}}{{CompatGeckoDesktop("8")}}4.07.04.0 (527)
setCapture() {{non-standard_inline}}{{CompatNo}}{{CompatNo}}{{CompatGeckoDesktop("2")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
oncopy, oncut, onpaste {{non-standard_inline}}{{CompatNo}}{{CompatNo}}{{CompatGeckoDesktop("1.9")}}{{CompatVersionUnknown}} {{CompatNo}}
onwheel {{non-standard_inline}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("17")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
ongotpointercapture, onlostpointercapture, setPointerCapture(), and releasePointerCapture(){{CompatChrome(52.0)}} [4]{{CompatVersionUnknown}}{{CompatVersionUnknown}} [3]10.0{{CompatNo}}{{CompatNo}}
matches() {{experimental_inline}}{{CompatVersionUnknown}} with the non-standard name webkitMatchesSelector{{CompatVersionUnknown}} {{property_prefix("webkit")}} {{property_prefix("ms")}}{{CompatGeckoDesktop("1.9.2")}} with the non-standard name mozMatchesSelector
+ {{CompatGeckoDesktop("34")}} with the standard name
9.0 with the non-standard name msMatchesSelector11.5 with the non-standard name oMatchesSelector
+ 15.0 with the non-standard name webkitMatchesSelector
5.0 with the non-standard name webkitMatchesSelector
find() and findAll(){{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
requestPointerLock()16.0 {{property_prefix("webkit")}}, behind an about:flags
+ 22.0 {{property_prefix("webkit")}} (with special cases, progressively lifted see [2])
{{CompatVersionUnknown}}{{CompatGeckoDesktop("14")}}{{property_prefix("moz")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
requestFullscreen()14.0 {{property_prefix("webkit")}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("10")}} {{property_prefix("moz")}}11.0 {{property_prefix("ms")}}12.10
+ 15.0 {{property_prefix("webkit")}}
5.1 {{property_prefix("webkit")}}
undoManager and undoScope{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}} (behind the dom.undo_manager.enabled pref){{CompatNo}}{{CompatNo}}{{CompatNo}}
attributes{{CompatUnknown}}{{CompatNo}}{{CompatGeckoDesktop("22")}}
+ Before this it was available via the {{domxref("Node")}} interface that any element inherits.
{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
scrollTopMax() and scrollLeftMax(){{CompatNo}}{{CompatNo}}{{CompatGeckoDesktop("16")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
closest(){{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("35")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
hasAttributes(){{CompatVersionUnknown}}{{CompatNo}}{{CompatGeckoDesktop("1.0")}} (on the {{domxref("Node")}} interface)
+ {{CompatGeckoDesktop("35")}} (on this interface
{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
insertAdjacentElement(), insertAdjacentText(){{CompatVersionUnknown}}{{CompatNo}}{{CompatGeckoDesktop("48.0")}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
assignedSlot, attatchShadow, shadowRoot, and slot{{CompatChrome(53)}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
computedRole and computedName{{CompatChrome(41)}}[4]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}28[4]{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support1.0 {{CompatVersionUnknown}}{{CompatGeckoMobile("1")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}1.0 
scrollTopMax() and scrollLeftMax(){{CompatNo}} {{CompatNo}}{{CompatGeckoMobile("16")}}{{CompatNo}}{{CompatNo}}{{CompatNo}} 
closest(){{CompatUnknown}} {{CompatVersionUnknown}}{{CompatGeckoMobile("35")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}} 
hasAttributes(){{CompatVersionUnknown}} {{CompatNo}}{{CompatGeckoMobile("1.0")}} (on the {{domxref("Node")}} interface)
+ {{CompatGeckoMobile("35")}} (on this interface
{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}} 
insertAdjacentElement(), insertAdjacentText(){{CompatVersionUnknown}} {{CompatVersionUnknown}}{{CompatGeckoMobile("48.0")}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}} 
assignedSlot, attatchShadow, shadowRoot, and slot{{CompatNo}}{{CompatChrome(53.0)}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(53)}}
computedRole and computedName{{CompatNo}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}28[4]{{CompatUnknown}}{{CompatNo}}
+
+ +

[1] Internet Explorer 7 and 8 incorrectly return the comments as part of the children of an Element. This is fixed in Internet Explorer 9 and later.

+ +

[2] Chrome 16 allowed webkitRequestPointerLock() only in fullscreen; Chrome 21 for trusted web site (permission asked); Chrome 22 allowed it by default for all same-origin document; Chrome 23 allowed it in sandboxed {{HTMLElement("iframe")}} if the non-standard value webkit-allow-pointer-lock is set to the {{htmlattrxref("sandbox", "iframe")}} attribute.

+ +

[3] Implementation withdrawn. See {{Bug("1166347")}}.

+ +

[4] Behind a flag.

diff --git a/files/zh-tw/web/api/element/innerhtml/index.html b/files/zh-tw/web/api/element/innerhtml/index.html new file mode 100644 index 0000000000..df002176e4 --- /dev/null +++ b/files/zh-tw/web/api/element/innerhtml/index.html @@ -0,0 +1,215 @@ +--- +title: Element.innerHTML +slug: Web/API/Element/innerHTML +tags: + - 元素組件 + - 注譯 + - 裏HTML + - 裏超文本 +translation_of: Web/API/Element/innerHTML +--- +
{{APIRef("DOM")}}
+ + + +

 Element  的「innerHTML」屬性獲取或設置元素中包含的HTML或XML標記。

+ +
Note:  如{{HTMLElement("div")}}, {{HTMLElement("span")}}, or {{HTMLElement("noembed")}} 節點有包含字符(&),(<)或(>),innerHTML分別地回傳這些字符成為HTML的“&” “<” “>” 。 使用 Node.textContent 得到的這些文本節點的內容的原始拷貝件。
+ +

To insert the HTML into the document rather than replace the contents of an element, use the method {{domxref("Element.insertAdjacentHTML", "insertAdjacentHTML()")}}.

+ +

Syntax

+ +
const content = element.innerHTML;
+
+element.innerHTML = htmlString;
+
+ +

Value

+ +

A {{domxref("DOMString")}} containing the HTML serialization of the element's descendants. Setting the value of innerHTML removes all of the element's descendants and replaces them with nodes constructed by parsing the HTML given in the string htmlString.

+ +

Exceptions

+ +
+
SyntaxError
+
An attempt was made to set the value of innerHTML using a string which is not properly-formed HTML.
+
NoModificationAllowedError
+
An attempt was made to insert the HTML into a node whose parent is a {{domxref("Document")}}.
+
+ +

Usage notes

+ +

The innerHTML property can be used to examine the current HTML source of the page, including any changes that have been made since the page was initially loaded.

+ +

Reading the HTML contents of an element

+ +

Reading innerHTML causes the user agent to serialize the HTML or XML fragment comprised of the elment's descendants. The resulting string is returned.

+ +
let contents = myElement.innerHTML;
+ +

This lets you look at the HTML markup of the element's content nodes.

+ +
+

Note: The returned HTML or XML fragment is generated based on the current contents of the element, so the markup and formatting of the returned fragment is likely not to match the original page markup.

+
+ +
+

Note:基於元素的當前內容產生返回的HTML或XML片段,所以返回的片段的標記和格式可能不匹配原始頁面標記。

+
+ +

Replacing the contents of an element

+ +

Setting the value of innerHTML lets you easily replace the existing contents of an element with new content.

+ +

For example, you can erase the entire contents of a document by clearing the contents of the document's {{domxref("Document.body", "body")}} attribute:

+ +
document.body.innerHTML = "";
+ +

This example fetches the document's current HTML markup and replaces the "<" characters with the HTML entity "&lt;", thereby essentially converting the HTML into raw text. This is then wrapped in a {{HTMLElement("pre")}} element. Then the value of innerHTML is changed to this new string. As a result, the document contents are replaced with a display of the page's entire source code.

+ +
document.documentElement.innerHTML = "<pre>" +
+         document.documentElement.innerHTML.replace(/</g,"&lt;") +
+            "</pre>";
+ +

Operational details

+ +

What exactly happens when you set value of innerHTML? Doing so causes the user agent to follow these steps:

+ +
    +
  1. The specified value is parsed as HTML or XML (based on the document type), resulting in a {{domxref("DocumentFragment")}} object representing the new set of DOM nodes for the new elements.
  2. +
  3. If the element whose contents are being replaced is a {{HTMLElement("template")}} element, then the <template> element's {{domxref("HTMLTemplateElement.content", "content")}} attribute is replaced with the new DocumentFragment created in step 1.
  4. +
  5. For all other elements, the element's contents are replaced with the nodes in the new DocumentFragment.
  6. +
+ +

Security considerations

+ +

It is not uncommon to see innerHTML used to insert text into a web page. There is potential for this to become an attack vector on a site, creating a potential security risk.

+ +
const name = "John";
+// assuming 'el' is an HTML DOM element
+el.innerHTML = name; // harmless in this case
+
+// ...
+
+name = "<script>alert('I am John in an annoying alert!')</script>";
+el.innerHTML = name; // harmless in this case
+ +

Although this may look like a {{interwiki("wikipedia", "cross-site scripting")}} attack, the result is harmless. HTML5 specifies that a {{HTMLElement("script")}} tag inserted with innerHTML should not execute.

+ +

However, there are ways to execute JavaScript without using {{HTMLElement("script")}} elements, so there is still a security risk whenever you use innerHTML to set strings over which you have no control. For example:

+ +
const name = "<img src='x' onerror='alert(1)'>";
+el.innerHTML = name; // shows the alert
+ +

For that reason, it is recommended that you do not use innerHTML when inserting plain text; instead, use {{domxref("Node.textContent")}}. This doesn't parse the passed content as HTML, but instead inserts it as raw text.

+ +
+

Warning: If your project is one that will undergo any form of security review, using innerHTML most likely will result in your code being rejected. For example, if you use innerHTML in a browser extension and submit the extension to addons.mozilla.org, it will not pass the automated review process.

+
+ +

Example

+ +

This example uses innerHTML to create a mechanism for logging messages into a box on a web page.

+ +

JavaScript

+ +
function log(msg) {
+  var logElem = document.querySelector(".log");
+
+  var time = new Date();
+  var timeStr = time.toLocaleTimeString();
+  logElem.innerHTML += timeStr + ": " + msg + "<br/>";
+}
+
+log("Logging mouse events inside this container...");
+
+ +

The log() function creates the log output by getting the current time from a {{jsxref("Date")}} object using {{jsxref("Date.toLocaleTimeString", "toLocaleTimeString()")}}, and building a string with the timestamp and the message text. Then the message is appended to the box with the class "log".

+ +

We add a second method that logs information about {{domxref("MouseEvent")}} based events (such as {{event("mousedown")}}, {{event("click")}}, and {{event("mouseenter")}}):

+ +
function logEvent(event) {
+  var msg = "Event <strong>" + event.type + "</strong> at <em>" +
+            event.clientX + ", " + event.clientY + "</em>";
+  log(msg);
+}
+ +

Then we use this as the event handler for a number of mouse events on the box that contains our log:

+ +
var boxElem = document.querySelector(".box");
+
+boxElem.addEventListener("mousedown", logEvent);
+boxElem.addEventListener("mouseup", logEvent);
+boxElem.addEventListener("click", logEvent);
+boxElem.addEventListener("mouseenter", logEvent);
+boxElem.addEventListener("mouseleave", logEvent);
+ +

HTML

+ +

The HTML is quite simple for our example.

+ +
<div class="box">
+  <div><strong>Log:</strong></div>
+  <div class="log"></div>
+</div>
+ +

The {{HTMLElement("div")}} with the class "box" is just a container for layout purposes, presenting the contents with a box around it. The <div> whose class is "log" is the container for the log text itself.

+ +

CSS

+ +

The following CSS styles our example content.

+ +
.box {
+  width: 600px;
+  height: 300px;
+  border: 1px solid black;
+  padding: 2px 4px;
+  overflow-y: scroll;
+  overflow-x: auto;
+}
+
+.log {
+  margin-top: 8px;
+  font-family: monospace;
+}
+ +

Result

+ +

The resulting content looks like this. You can see output into the log by moving the mouse in and out of the box, clicking in it, and so forth.

+ +

{{EmbedLiveSample("Example", 640, 350)}}

+ +

Specification

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM Parsing', '#dom-element-innerhtml', 'Element.innerHTML')}}{{Spec2('DOM Parsing')}}Initial definition
+ +

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/zh-tw/web/api/element/insertadjacenthtml/index.html b/files/zh-tw/web/api/element/insertadjacenthtml/index.html new file mode 100644 index 0000000000..6b9da0f403 --- /dev/null +++ b/files/zh-tw/web/api/element/insertadjacenthtml/index.html @@ -0,0 +1,135 @@ +--- +title: Element.insertAdjacentHTML() +slug: Web/API/Element/insertAdjacentHTML +translation_of: Web/API/Element/insertAdjacentHTML +--- +
{{APIRef("DOM")}}
+ +

insertAdjacentHTML() 把傳入的字串解析成 HTML 或 XML,並把該節點插入到 DOM 樹指定的位置。它不會重新解析被使用的元素,因此他不會破壞該元素裡面原有的元素。這避免了序列化的複雜步驟,使得它比直接操作  innerHTML 快上許多。

+ +

Syntax

+ +
element.insertAdjacentHTML(position, text);
+ +

Parameters

+ +
+
position
+
A {{domxref("DOMString")}} representing the position relative to the element; must be one of the following strings: +
    +
  • 'beforebegin': 在 element 之前。
  • +
  • 'afterbegin': 在 element 裡面,第一個子元素之前。
  • +
  • 'beforeend': 在 element 裡面,最後一個子元素之後。
  • +
  • 'afterend': 在 element 之後。
  • +
+
+
text
+
text 是即將被解析並插入到 DOM 樹裡的字串。
+
+ +

Visualization of position names

+ +
<!-- beforebegin -->
+<p>
+  <!-- afterbegin -->
+  foo
+  <!-- beforeend -->
+</p>
+<!-- afterend -->
+ +
Note:  beforebegin 和 afterend 只在該節點位於 DOM 樹內、並且有母元素時有效。
+ +

Example

+ +
// <div id="one">one</div>
+var d1 = document.getElementById('one');
+d1.insertAdjacentHTML('afterend', '<div id="two">two</div>');
+
+// At this point, the new structure is:
+// <div id="one">one</div><div id="two">two</div>
+ +

Notes

+ +

Security Considerations

+ +

When inserting HTML into a page by using insertAdjacentHTML be careful not to use user input that hasn't been escaped.

+ +

It is not recommended you use insertAdjacentHTML when inserting plain text; instead, use the Node.textContent property or Element.insertAdjacentText() method. This doesn't interpret the passed content as HTML, but instead inserts it as raw text.

+ +

Specification

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM Parsing', '#widl-Element-insertAdjacentHTML-void-DOMString-position-DOMString-text', 'Element.insertAdjacentHTML()')}}{{ Spec2('DOM Parsing') }} 
+ +

Browser compatibility

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support1.0{{ CompatGeckoDesktop("8.0") }}4.07.04.0 (527)
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}{{ CompatGeckoMobile("8.0") }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

See also

+ + diff --git a/files/zh-tw/web/api/element/queryselectorall/index.html b/files/zh-tw/web/api/element/queryselectorall/index.html new file mode 100644 index 0000000000..6f777763bf --- /dev/null +++ b/files/zh-tw/web/api/element/queryselectorall/index.html @@ -0,0 +1,140 @@ +--- +title: Element.querySelectorAll() +slug: Web/API/Element/querySelectorAll +translation_of: Web/API/Element/querySelectorAll +--- +
{{APIRef("DOM")}}
+ +

總覽

+ +

Returns a non-live NodeList of all elements descended from the element on which it is invoked that matches the specified group of CSS selectors. (The base element itself is not included, even if it matches.)

+ +

表達式

+ +
elementList = baseElement.querySelectorAll(selectors);
+ +
+
elementList
+
is a non-live node list [ NodeList[elements] of element objects.
+
baseElement
+
is an element object.
+
selectors
+
is a group of selectors to match on or elements of the DOM. 
+
+ +

範例

+ +

下例是從整個網頁的 body 中,取得所有 p 元素:

+ +
let matches = document.body.querySelectorAll('p');
+
+ +

This example returns a list of p children elements under a container, whose parent is a div that has the class 'highlighted':

+ +
let el = document.querySelector('#test');    //return an element with id='test'
+let matches = el.querySelectorAll('div.highlighted > p'); // return a NodeList of p wrapped in a div with attribute class "highlighted"
+
+ +

下例是取得所有有 attribute data-srciframe 元素:

+ +
let matches = el.querySelectorAll('iframe[data-src]');
+
+ +

+ +

If the specified “selectors” are not found inside the DOM of the page, the method queryselectorAll returns an empty NodeList as specified below:

+ +
> let x = document.body.querySelectorAll('.highlighted'); //case: if the class highlighted doesn't exist in any attribute "class" of the DOM the result is
+> [] //empty NodeList
+ +

querySelectorAll() was introduced in the WebApps API.

+ +

The string argument pass to querySelectorAll must follow the CSS syntax. See {{domxref("document.querySelector")}} for a concrete example.

+ +

We could access a single item inside the NodeList in the following way:

+ +
let x = document.body.querySelectorAll('.highlighted');
+x.length; //return the size of x
+x[i_item]; //where i_item has a value between 0 and x.length-1. The operator "[]" return as in an array the element at index "i_item"
+
+ +

We could iterate inside a NodeList with the construct for(....) {...} as in the following code:

+ +
 let x = document.body.querySelectorAll('.highlighted');
+ let index = 0;
+ for( index=0; index < x.length; index++ ) {
+       console.log(x[index]);
+ }
+ +

So in the above way, it is possible to manage and modify the behaviour of the page.

+ +

Quirks

+ +

querySelectorAll() behaves differently than most common JavaScript DOM libraries, which might lead to unexpected results:

+ +
<div class="outer">
+  <div class="select">
+    <div class="inner">
+    </div>
+  </div>
+</div>
+ +
let select = document.querySelector('.select');
+let inner = select.querySelectorAll('.outer .inner');
+inner.length; // 1, not 0!
+
+ +

In this example, when selecting .outer .inner in the context of .select, .inner is still found, even though .outer is not a descendant of the baseElement (.select).
+ querySelectorAll() only verifies that the last element in the selector is within the baseElement.

+ +

The :scope pseudo-class restores the expected behavior, only matching selectors on descendants of the baseElement:

+ +
let select = document.querySelector('.select');
+let inner = select.querySelectorAll(':scope .outer .inner');
+inner.length; // 0
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
規範狀態評論
{{SpecName('DOM4','#dom-parentnode-queryselectorallselectors','querySelectorAll')}}{{Spec2('DOM4')}} 
{{SpecName('Selectors API Level 2','#queryselectorall','querySelectorAll')}}{{Spec2('Selectors API Level 2')}} 
{{SpecName('Selectors API Level 1','#queryselectorall','querySelectorAll')}}{{Spec2('Selectors API Level 1')}} 
+ +

瀏覽器相容性

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

[1] Supported in Opera 15+ by enabling the "Enable <style scoped>" or "Enable experimental Web Platform features" flag in chrome://flags.

+ +

參見

+ + diff --git a/files/zh-tw/web/api/element/scrollheight/index.html b/files/zh-tw/web/api/element/scrollheight/index.html new file mode 100644 index 0000000000..eabf9987bf --- /dev/null +++ b/files/zh-tw/web/api/element/scrollheight/index.html @@ -0,0 +1,170 @@ +--- +title: Element.scrollHeight +slug: Web/API/Element/scrollHeight +tags: + - API + - Reference +translation_of: Web/API/Element/scrollHeight +--- +

{{APIRef("DOM")}}

+ +

Element.scrollHeight 是衡量元素包含因為 overflow 而沒顯示在螢幕上的內容高度的唯讀屬性. scrollHeight 的值相等於元素要求 clientHeight 在視域中沒有使用滾動條顯示所有內容的最小高度值 . 這當中只包含 padding, 並不包含 margin.

+ +
+

這個屬性會以四捨五入進位取整數. 如果要使用非整數值, 使用 {{ domxref("Element.getBoundingClientRect()") }}.

+
+ +

表達式

+ +
var intElemScrollHeight = document.getElementById(id_attribute_value).scrollHeight;
+
+ +

intElemScrollHeight 是個儲存了元素 scrollHeight 的正整數變數. scrollHeight是唯讀的屬性.

+ +

範例

+ +
+
+

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:scrollHeight.png

+ +

問題與解決方法

+ +

了解元素是否被滾輪完全滾過

+ +

下面的等式代表如果元素被完全滾過將會回傳 true ,  否則回傳 false.

+ +
element.scrollHeight - element.scrollTop === element.clientHeight
+ +

scrollHeight 範例

+ +

藉由 onscroll 事件, 這個等式對於決定使用者是否已經讀完文字內容是很有用 (參見 element.scrollTopelement.clientHeight 屬性). 範例:

+ +

HTML

+ +
<form name="registration">
+  <p>
+    <textarea id="rules">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum at laoreet magna.
+Aliquam erat volutpat. Praesent molestie, dolor ut eleifend aliquam, mi ligula ultrices sapien, quis cursus
+neque dui nec risus. Duis tincidunt lobortis purus eu aliquet. Quisque in dignissim magna. Aenean ac lorem at
+velit ultrices consequat. Nulla luctus nisi ut libero cursus ultrices. Pellentesque nec dignissim enim. Phasellus
+ut quam lacus, sed ultricies diam. Vestibulum convallis rutrum dolor, sit amet egestas velit scelerisque id.
+Proin non dignissim nisl. Sed mi odio, ullamcorper eget mattis id, malesuada vitae libero. Integer dolor lorem,
+mattis sed dapibus a, faucibus id metus. Duis iaculis dictum pulvinar. In nisi nibh, dapibus ac blandit at, porta
+at arcu. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Praesent
+dictum ipsum aliquet erat eleifend sit amet sollicitudin felis tempus. Aliquam congue cursus venenatis. Maecenas
+luctus pellentesque placerat. Mauris nisl odio, condimentum sed fringilla a, consectetur id ligula. Praesent sem
+sem, aliquet non faucibus vitae, iaculis nec elit. Nullam volutpat, lectus et blandit bibendum, nulla lorem congue
+turpis, ac pretium tortor sem ut nibh. Donec vel mi in ligula hendrerit sagittis. Donec faucibus viverra fermentum.
+Fusce in arcu arcu. Nullam at dignissim massa. Cras nibh est, pretium sit amet faucibus eget, sollicitudin in
+ligula. Vivamus vitae urna mauris, eget euismod nunc. Aenean semper gravida enim non feugiat. In hac habitasse
+platea dictumst. Cras eleifend nisl volutpat ante condimentum convallis. Donec varius dolor malesuada erat
+consequat congue. Donec eu lacus ut sapien venenatis tincidunt. Quisque sit amet tellus et enim bibendum varius et
+a orci. Donec aliquet volutpat scelerisque. Proin et tortor dolor. Ut aliquet, dolor a mattis sodales, odio diam
+pulvinar sem, egestas pretium magna eros vitae felis. Nam vitae magna lectus, et ornare elit. Morbi feugiat, ipsum
+ac mattis congue, quam neque mollis tortor, nec mollis nisl dolor a tortor. Maecenas varius est sit amet elit
+interdum quis placerat metus posuere. Duis malesuada justo a diam vestibulum vel aliquam nisi ornare. Integer
+laoreet nisi a odio ornare non congue turpis eleifend. Cum sociis natoque penatibus et magnis dis parturient montes,
+nascetur ridiculus mus. Cras vulputate libero sed arcu iaculis nec lobortis orci fermentum.
+    </textarea>
+  </p>
+  <p>
+    <input type="checkbox" name="accept" id="agree" />
+    <label for="agree">I agree</label>
+    <input type="submit" id="nextstep" value="Next" />
+  </p>
+</form>
+ +

CSS

+ +
#notice {
+  display: inline-block;
+  margin-bottom: 12px;
+  border-radius: 5px;
+  width: 600px;
+  padding: 5px;
+  border: 2px #7FDF55 solid;
+}
+
+#rules {
+  width: 600px;
+  height: 130px;
+  padding: 5px;
+  border: #2A9F00 solid 2px;
+  border-radius: 5px;
+}
+ +

JavaScript

+ +
function checkReading () {
+  if (checkReading.read) {
+    return;
+  }
+  checkReading.read = this.scrollHeight - this.scrollTop === this.clientHeight;
+  document.registration.accept.disabled = document.getElementById("nextstep").disabled = !checkReading.read;
+  checkReading.noticeBox.innerHTML = checkReading.read ? "Thank you." : "Please, scroll and read the following text.";
+}
+
+onload = function () {
+  var oToBeRead = document.getElementById("rules");
+  checkReading.noticeBox = document.createElement("span");
+  document.registration.accept.checked = false;
+  checkReading.noticeBox.id = "notice";
+  oToBeRead.parentNode.insertBefore(checkReading.noticeBox, oToBeRead);
+  oToBeRead.parentNode.insertBefore(document.createElement("br"), oToBeRead);
+  oToBeRead.onscroll = checkReading;
+  checkReading.call(oToBeRead);
+}
+ +

{{ EmbedLiveSample('scrollHeight_Demo', '640', '400') }}

+ +

規範

+ +

scrollHeight 是 MSIE's DHTML 物件模型的一部份. scrollHeight 紀錄在下列的規範: {{SpecName("CSSOM View")}}.

+ +

瀏覽器相容性

+ + + + + + + + + + + + + + + + + + + + + + + + +
瀏覽器最低版本
Internet Explorer8.0
Firefox (Gecko)3.0 (1.9)
Opera?
Safari | Chrome | WebKit4.0 | 4.0 | ?
+ +

In FireFox versions earlier than 21: When an element's content does not generate a vertical scrollbar, then its scrollHeight property is equal to its clientHeight property. This can mean either the content is too short to require a scrollbar or that the element has CSS style overflow value of visible (non-scrollable).

+ +

參見

+ + diff --git a/files/zh-tw/web/api/element/scrolltop/index.html b/files/zh-tw/web/api/element/scrolltop/index.html new file mode 100644 index 0000000000..f4fdfe8e09 --- /dev/null +++ b/files/zh-tw/web/api/element/scrolltop/index.html @@ -0,0 +1,73 @@ +--- +title: Element.scrollTop +slug: Web/API/Element/scrollTop +tags: + - API + - CSSOM View + - Reference +translation_of: Web/API/Element/scrollTop +--- +

{{ APIRef("DOM") }}

+ +

Element.scrollTop 屬性可以設置和獲取元素被向上捲動的高度(pixels). 元素的 scrollTop 是元素頂端和能被看見的最頂端之間的距離. 當元素並未產生滾動條, 那麼 scrollTop 的值預設為 0.

+ +

表達式

+ +
// 獲得已經被滾動的距離(pixels)
+var  intElemScrollTop = someElement.scrollTop;
+
+ +

intElemScrollTop 為 {{domxref("element")}}已經被滾動的距離(pixels ).

+ +
// 設置已經被滾動的距離(pixels)
+element.scrollTop = intValue;
+
+ +

scrollTop 可以被設置為任何和正整數, 注意事項:

+ + + +

範例

+ +
+
+

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

+ +

規範

+ + + + + + + + + + + + + + +
規範狀態
{{SpecName('CSSOM View', '#dom-element-scrolltop', 'scrollTop')}}{{Spec2("CSSOM View")}} 
+ +

參閱

+ + diff --git a/files/zh-tw/web/api/element/touchcancel_event/index.html b/files/zh-tw/web/api/element/touchcancel_event/index.html new file mode 100644 index 0000000000..99fa1c27a2 --- /dev/null +++ b/files/zh-tw/web/api/element/touchcancel_event/index.html @@ -0,0 +1,169 @@ +--- +title: touchcancel +slug: Web/API/Element/touchcancel_event +translation_of: Web/API/Element/touchcancel_event +--- +

{{APIRef}}

+ +

touchcancel 觸控點發生失效的事件被觸發(例如太多觸控點時)

+ +

一般資訊

+ +
+
規範
+
Touch Events
+
介面
+
TouchEvent
+
起泡事件
+
+
可取消
+
+
對象
+
Document, Element
+
預設行為
+
+
+ +

屬性

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

範例

+ +

各種觸控事件的範例:Touch events

+ +

瀏覽器相容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome("22.0")}}{{CompatGeckoDesktop("18.0")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("6.0")}}{{CompatVersionUnknown}}11{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

相關事件

+ +

{{ domxref("GlobalEventHandlers.ontouchcancel","ontouchcancel")}}

diff --git a/files/zh-tw/web/api/errorevent/index.html b/files/zh-tw/web/api/errorevent/index.html new file mode 100644 index 0000000000..27e406ed7c --- /dev/null +++ b/files/zh-tw/web/api/errorevent/index.html @@ -0,0 +1,148 @@ +--- +title: ErrorEvent +slug: Web/API/ErrorEvent +translation_of: Web/API/ErrorEvent +--- +

{{APIRef("HTML DOM")}}

+ +

ErrorEvent 介面是用來提供程式碼或是檔案的錯誤訊息的事件。

+ +

Properties

+ +

此介面繼承了其父 {{domxref("Event")}} 的 properties 。

+ +
+
{{domxref("ErrorEvent.message")}} {{readonlyInline}}
+
一 {{domxref("DOMString")}} 提供具可讀性的關於問題的錯誤訊息。
+
{{domxref("ErrorEvent.filename")}} {{readonlyInline}}
+
一 {{domxref("DOMString")}} ,為發生錯誤的程式碼檔案的檔名。
+
{{domxref("ErrorEvent.lineno")}} {{readonlyInline}}
+
一 整數 ,為發生問題的程式的行數。
+
{{domxref("ErrorEvent.colno")}} {{readonlyInline}}
+
整數 ,為發生問題的程式的欄數。
+
{{domxref("ErrorEvent.error")}} {{readonlyInline}} {{experimental_inline}}
+
一個參與該事件的 JavaScript Object 。
+
+ +

Constructor

+ +
+
{{domxref("ErrorEvent.ErrorEvent", "ErrorEvent()")}}
+
建立一 ErrorEvent 事件,其包含提供的參數。
+
+ +

Methods

+ +

此介面繼承了其父 {{domxref("Event")}} 的 methods。

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('HTML WHATWG', 'webappapis.html#the-errorevent-interface', 'ErrorEvent') }}{{ Spec2('HTML WHATWG') }}追加 error propriety 以及 constructor 的第5個the 5th 參數。
{{ SpecName('HTML5 W3C', 'webappapis.html#the-errorevent-interface', 'ErrorEvent') }}{{ Spec2('HTML5 W3C') }}初始定義。
+ +

瀏覽器支援度比較

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
colno property and 4th argument to constructor{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
error property and 5th argument to constructor{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
colno property and 4th argument to constructor{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
error property and 5th argument to constructor{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

延伸閱讀

+ + diff --git a/files/zh-tw/web/api/event/bubbles/index.html b/files/zh-tw/web/api/event/bubbles/index.html new file mode 100644 index 0000000000..4a495fc672 --- /dev/null +++ b/files/zh-tw/web/api/event/bubbles/index.html @@ -0,0 +1,63 @@ +--- +title: Event.bubbles +slug: Web/API/Event/bubbles +translation_of: Web/API/Event/bubbles +--- +

{{ ApiRef("DOM") }}

+ +

概述

+ +

表示事件是否會向上冒泡傳遞。

+ +

語法

+ +
var bool = event.bubbles;
+
+ +

回傳一個布林值,若事件會向上冒泡傳遞則回傳 true

+ +

備註

+ +

Only certain events can bubble. Events that do bubble have this property set to true. You can use this property to check if an event is allowed to bubble or not.

+ +

範例

+ +
 function goInput(e) {
+  // checks bubbles and
+  if (!e.bubbles) {
+     // passes event along if it's not
+     passItOn(e);
+  }
+  // already bubbling
+  doOutput(e)
+}
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-event-bubbles', 'Event.bubbles')}}{{ Spec2('DOM WHATWG') }} 
{{SpecName('DOM4', '#dom-event-bubbles', 'Event.bubbles')}}{{ Spec2('DOM4') }} 
{{SpecName('DOM2 Events', '#Events-Event-canBubble', 'Event.bubbles')}}{{ Spec2('DOM2 Events') }}Initial definition.
diff --git a/files/zh-tw/web/api/event/comparison_of_event_targets/index.html b/files/zh-tw/web/api/event/comparison_of_event_targets/index.html new file mode 100644 index 0000000000..211463b1a7 --- /dev/null +++ b/files/zh-tw/web/api/event/comparison_of_event_targets/index.html @@ -0,0 +1,164 @@ +--- +title: Comparison of Event Targets +slug: Web/API/Event/Comparison_of_Event_Targets +translation_of: Web/API/Event/Comparison_of_Event_Targets +--- +

{{ ApiRef() }}

+ +

Event targets

+ +

It's easy to get confused about which target to examine when writing an event handler. This article should clarify the use of the target properties.

+ +

There are 5 targets to consider:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyDefined inPurpose
event.targetDOM Event Interface +

The DOM element on the lefthand side of the call that triggered this event, eg:

+ +
+element.dispatchEvent(event)
+
+
event.currentTargetDOM Event InterfaceThe EventTarget whose EventListeners are currently being processed. As the event capturing and bubbling occurs this value changes.
event.relatedTargetDOM MouseEvent InterfaceIdentifies a secondary target for the event.
event.explicitOriginalTarget{{ Source("/dom/public/idl/events/nsIDOMNSEvent.idl", "nsIDOMNSEvent.idl") }}{{ Non-standard_inline() }} If the event was retargeted for some reason other than an anonymous boundary crossing, this will be set to the target before the retargeting occurs. For example, mouse events are retargeted to their parent node when they happen over text nodes ({{ Bug("185889") }}), and in that case .target will show the parent and .explicitOriginalTarget will show the text node.
+ Unlike .originalTarget, .explicitOriginalTarget will never contain anonymous content.
event.originalTarget{{ Source("/dom/public/idl/events/nsIDOMNSEvent.idl", "nsIDOMNSEvent.idl") }}{{ Non-standard_inline() }} The original target of the event, before any retargetings. See Anonymous Content#Event_Flow_and_Targeting for details.
+ +

Use of explicitOriginalTarget and originalTarget

+ +

TODO: Only available in a Mozilla-based browser? TODO: Only suitable for extension-developers?

+ +

範例

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

Use of target and relatedTarget

+ +

The relatedTarget property for the mouseover event holds the node that the mouse was previously over. For the mouseout event, it holds the node that the mouse moved to.

+ + + + + + + + + + + + + + + + + + + +
Event typeevent.targetevent.relatedTarget
mouseoverthe EventTarget which the pointing device enteredthe EventTarget which the pointing device exited
mouseoutthe EventTarget which the pointing device exitedthe EventTarget which the pointing device entered
+ +

TODO: Also needs descriptions about dragenter and dragexit events.

+ +

範例

+ +
<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/zh-tw/web/api/event/createevent/index.html b/files/zh-tw/web/api/event/createevent/index.html new file mode 100644 index 0000000000..fd60d1089d --- /dev/null +++ b/files/zh-tw/web/api/event/createevent/index.html @@ -0,0 +1,29 @@ +--- +title: Event.createEvent() +slug: Web/API/Event/createEvent +translation_of: Web/API/Document/createEvent +--- +

{{APIRef("DOM")}}

+ +

建立一個新的事件,該事件必須先以其 init() method 初始化才行。

+ +

語法

+ +
document.createEvent(type) 
+ +
+
type
+
一個 string 。表示所建立的事件名稱。
+
+ +

這個 method 會回傳一個新的 DOM {{ domxref("Event") }} object ,其事件類型為傳入的 type 。該事件必須先初始化才能使用。

+ +

範例

+ +
var newEvent = document.createEvent("UIEvents");
+ +

規格定義

+ + diff --git a/files/zh-tw/web/api/event/currenttarget/index.html b/files/zh-tw/web/api/event/currenttarget/index.html new file mode 100644 index 0000000000..2be9aeb4e7 --- /dev/null +++ b/files/zh-tw/web/api/event/currenttarget/index.html @@ -0,0 +1,70 @@ +--- +title: Event.currentTarget +slug: Web/API/Event/currentTarget +translation_of: Web/API/Event/currentTarget +--- +
{{APIRef("DOM")}}
+ +

{{domxref("Event")}} 介面的唯讀屬性 currentTarget 會標明事件指向(current target)、還有該事件所遍歷的 DOM。屬性總會指向當時處理該事件的事件監聽器所註冊的 DOM 物件,而 {{domxref("event.target")}} 屬性則是永遠指向觸發事件的 DOM 物件。

+ +

範例

+ +

event.currentTarget 在把相同的事件監聽器,附加到多個元素時,會出現很有趣的事情:

+ +
function hide(e){
+  e.currentTarget.style.visibility = "hidden";
+  // 在這個函式用於事件監聽器時: this === e.currentTarget
+}
+
+var ps = document.getElementsByTagName('p');
+
+for(var i = 0; i < ps.length; i++){
+  ps[i].addEventListener('click', hide, false);
+}
+
+// 單擊四周的話 p 元素就會消失
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
規範狀態註解
{{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")}}Initial definition
+ +

瀏覽器相容性

+ + + +

{{Compat("api.Event.currentTarget")}}

+ +

參見

+ + diff --git a/files/zh-tw/web/api/event/defaultprevented/index.html b/files/zh-tw/web/api/event/defaultprevented/index.html new file mode 100644 index 0000000000..d0814682a8 --- /dev/null +++ b/files/zh-tw/web/api/event/defaultprevented/index.html @@ -0,0 +1,100 @@ +--- +title: Event.defaultPrevented +slug: Web/API/Event/defaultPrevented +translation_of: Web/API/Event/defaultPrevented +--- +
{{ APIRef("DOM") }}
+ +

概述

+ +

回傳一個布林值,表示事件的預設行為是否被取消,也就是事件物件是否曾執行 {{domxref("event.preventDefault()", "preventDefault()")}} 方法。

+ +
註:You should use this instead of the non-standard, deprecated getPreventDefault() method (see {{ bug(691151) }}).
+ +

語法

+ +
bool = event.defaultPrevented 
+ +

範例

+ +
 if (e.defaultPrevented) {
+   /* the default was prevented */
+ }
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-event-defaultprevented', 'Event.defaultPrevented()')}}{{ Spec2('DOM WHATWG') }} 
{{SpecName('DOM4', '#dom-event-defaultprevented', 'Event.defaultPrevented')}}{{Spec2('DOM4')}}Initial definition.
+ +

瀏覽器相容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatChrome(18) }}{{ CompatGeckoDesktop("6.0") }}{{ CompatIE(9.0) }}{{ CompatOpera(11.0) }}{{ CompatSafari("5.0") }}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}{{ CompatGeckoMobile("6.0") }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatSafari(5.0) }}
+
+ + diff --git a/files/zh-tw/web/api/event/event/index.html b/files/zh-tw/web/api/event/event/index.html new file mode 100644 index 0000000000..bbbd74c5b2 --- /dev/null +++ b/files/zh-tw/web/api/event/event/index.html @@ -0,0 +1,87 @@ +--- +title: Event() +slug: Web/API/Event/Event +translation_of: Web/API/Event/Event +--- +

{{APIRef("DOM")}}

+ +

Event() constructor 能用來建立一個 {{domxref("Event", "事件")}} 。

+ +

語法

+ +
event = new Event(typeArg, eventInit);
+ +

參數

+ +
+
typeArg
+
為一 {{domxref("DOMString")}} ,用來表示事件名稱。
+
eventInit{{optional_inline}}
+
一個 EventInit object,包含以下欄位 + + + + + + + + + + + + + + + + + + + + + + + + + + +
參數可選默認值類型說明
"bubbles"false{{jsxref("Boolean")}}表示該事件是否懸浮(bubble up)。
"cancelable"false{{jsxref("Boolean")}}表示該事件是否已取消(canale)。
+
+
+ +

範例

+ +
// 建立一個 bubbles up 、並未被取消的事件 “look” 。
+var ev = new Event("look", {"bubbles":true, "cancelable":false});
+document.dispatchEvent(ev);
+
+ +

規格

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG','#interface-event','Event()')}}{{Spec2('DOM WHATWG')}}Initial definition.
+ +

瀏覽器相容性

+ + + +

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

+ +

參見

+ + diff --git a/files/zh-tw/web/api/event/eventphase/index.html b/files/zh-tw/web/api/event/eventphase/index.html new file mode 100644 index 0000000000..e146e7b230 --- /dev/null +++ b/files/zh-tw/web/api/event/eventphase/index.html @@ -0,0 +1,179 @@ +--- +title: Event.eventPhase +slug: Web/API/Event/eventPhase +translation_of: Web/API/Event/eventPhase +--- +

{{ApiRef("DOM")}}

+ +

表示事件物件目前於事件流(Event Flow)中傳遞的進度為哪一個階段。

+ +

語法

+ +
var phase = event.eventPhase;
+
+ +

回傳一個整數值以代表目前事件於事件流中的傳遞階段,可能的值將於{{anch("事件傳遞階段常數")}}說明。

+ +

常數

+ +

事件傳遞階段常數

+ +

These values describe which phase the event flow is currently being evaluated.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
常數說明
{{domxref("Event.NONE")}} {{readonlyinline}}0No event is being processed at this time.
{{domxref("Event.CAPTURING_PHASE")}} {{readonlyinline}}1The event is being propagated through the target's ancestor objects. This process starts with the {{domxref("Window")}}, then {{domxref("Document")}}, then the {{domxref("HTMLHtmlElement")}}, and so on through the elements until the target's parent is reached. {{domxref("EventListener", "Event listeners", "", 1)}} registered for capture mode when {{domxref("EventTarget.addEventListener()")}} was called are triggered during this phase.
{{domxref("Event.AT_TARGET")}} {{readonlyinline}}2The event has arrived at {{domxref("EventTarget", "the event's target", "", 1)}}. Event listeners registered for this phase are called at this time. If {{domxref("Event.bubbles")}} is false, processing the event is finished after this phase is complete.
{{domxref("Event.BUBBLING_PHASE")}} {{readonlyinline}}3The event is propagating back up through the target's ancestors in reverse order, starting with the parent, and eventually reaching the containing {{domxref("Window")}}. This is known as bubbling, and occurs only if {{domxref("Event.bubbles")}} is true. {{domxref("EventListener", "Event listeners", "", 1)}} registered for this phase are triggered during this process.
+ +

For more details, see section 3.1, Event dispatch and DOM event flow, of the DOM Level 3 Events specification.

+ +

範例

+ +

HTML Content

+ +
<h4>Event Propagation Chain</h4>
+<ul>
+  <li>Click 'd1'</li>
+  <li>Analyse event propagation chain</li>
+  <li>Click next div and repeat the experience</li>
+  <li>Change Capturing mode</li>
+  <li>Repeat the experience</li>
+</ul>
+<input type="checkbox" id="chCapture" />
+<label for="chCapture">Use Capturing</label>
+ <div id="d1">d1
+  <div id="d2">d2
+      <div id="d3">d3
+          <div id="d4">d4</div>
+      </div>
+  </div>
+ </div>
+ <div id="divInfo"></div>
+
+ +

CSS Content

+ +
div {
+  margin: 20px;
+  padding: 4px;
+  border: thin black solid;
+}
+
+#divInfo {
+  margin: 18px;
+  padding: 8px;
+  background-color:white;
+  font-size:80%;
+}
+ +

JavaScript Content

+ +
var clear = false, divInfo = null, divs = null, useCapture = false;
+window.onload = function () {
+  divInfo = document.getElementById("divInfo");
+  divs = document.getElementsByTagName('div');
+  chCapture = document.getElementById("chCapture");
+  chCapture.onclick = function () {
+    RemoveListeners();
+    AddListeners();
+  }
+  Clear();
+  AddListeners();
+}
+
+function RemoveListeners() {
+  for (var i = 0; i < divs.length; i++) {
+    var d = divs[i];
+    if (d.id != "divInfo") {
+      d.removeEventListener("click", OnDivClick, true);
+      d.removeEventListener("click", OnDivClick, false);
+    }
+  }
+}
+
+function AddListeners() {
+  for (var i = 0; i < divs.length; i++) {
+    var d = divs[i];
+    if (d.id != "divInfo") {
+      d.addEventListener("click", OnDivClick, false);
+      if (chCapture.checked)
+        d.addEventListener("click", OnDivClick, true);
+      d.onmousemove = function () { clear = true; };
+    }
+  }
+}
+
+function OnDivClick(e) {
+  if (clear) {
+    Clear(); clear = false;
+  }
+  if (e.eventPhase == 2)
+    e.currentTarget.style.backgroundColor = 'red';
+  var level = e.eventPhase == 0 ? "none" : e.eventPhase == 1 ? "capturing" : e.eventPhase == 2 ? "target" : e.eventPhase == 3 ? "bubbling" : "error";
+  divInfo.innerHTML += e.currentTarget.id + "; eventPhase: " + level + "<br/>";
+}
+
+function Clear() {
+  for (var i = 0; i < divs.length; i++) {
+    if (divs[i].id != "divInfo")
+      divs[i].style.backgroundColor = (i & 1) ? "#f6eedb" : "#cceeff";
+  }
+  divInfo.innerHTML = '';
+}
+
+ +

{{ EmbedLiveSample('Example', '', '700', '', 'Web/API/Event/eventPhase') }}

+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("DOM WHATWG", "#dom-event-eventphase", "Event.eventPhase")}}{{Spec2("DOM WHATWG")}} 
{{SpecName("DOM4", "#dom-event-eventphase", "Event.eventPhase")}}{{Spec2("DOM4")}} 
{{SpecName("DOM2 Events", "#Events-Event-eventPhase", "Event.eventPhase")}}{{Spec2("DOM2 Events")}}Initial definition
diff --git a/files/zh-tw/web/api/event/index.html b/files/zh-tw/web/api/event/index.html new file mode 100644 index 0000000000..4213c20080 --- /dev/null +++ b/files/zh-tw/web/api/event/index.html @@ -0,0 +1,210 @@ +--- +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")}}

+ +

Event 介面表示了一個在 DOM 物件上所發生的事件。

+ +

一個事件可以是由使用者的操作行為所產生(如:點擊滑鼠按鈕或敲打鍵盤),或是來自 API 因處理非同步任務所產生。事件也可以為程式所觸發,例如呼叫元素的 HTMLElement.click() 方法,或是自行定義事件並使用 EventTarget.dispatchEvent() 發送至特定的目標。

+ +

事件有多種不同的類型,部分事件是使用基於 Event 的子介面。Event 本身包含了所有事件共同的屬性及方法。

+ +

許多 DOM 元素可被設定接受(accept,或稱為 listen "監聽")這些事件,並在發生時執行處理(process、handle)事件的程式碼。事件處理器(Event-handlers)通常會使用 EventTarget.addEventListener() 來被連結(connected,或稱為 attached "附加")至各個 HTML 元素(例如 <button>、<div>、<div>、<span> 等),且此方式一般也是用來取代舊的 HTML 事件處理器屬性(attributes)。此外,在需要時也可以使用 removeEventListener() 來中斷事件處理器與元素的連結。請留意一個元素可以擁有多個事件處理器(即使是處理同一種事件的不同處理器),特別是那些被切分開來彼此獨立且有不同目標的程式模組(舉例來說,廣告及統計模組可以同時監控網頁中的影片觀看資訊)。

+ +

When there are many nested elements, each with its own handler(s), event processing can become very complicated -- especially where a parent element receives the very same event as its child elements because "spatially" they overlap so the event technically occurs in both, and the processing order of such events depends on the Event bubbling and capture settings of each handler triggered.

+ +

基於 Event 的子介面

+ +

Below is a list of interfaces which are based on the main Event interface, with links to their respective documentation in the MDN API reference. Note that all event interfaces have names which end in "Event".

+ +
+ +
+ +

建構式

+ +
+
{{domxref("Event.Event", "Event()")}}
+
建立一個 Event 物件。
+
+ +

屬性

+ +
+
{{domxref("Event.bubbles")}} {{readonlyinline}}
+
布林值,表示事件是否會向上冒泡傳遞。
+
{{domxref("Event.cancelBubble")}}
+
由於歷史性因素,此屬性的效果等同於 {{domxref("Event.stopPropagation()", "stopPropagation()")}} 方法。若在事件處理器回傳前設定此值為 true,可阻止事件繼續向上冒泡傳遞。
+
{{domxref("Event.cancelable")}} {{readonlyinline}}
+
布林值,表示事件是否能被取消。
+
{{domxref("Event.composed")}} {{ReadOnlyInline}}
+
A Boolean value indicating whether or not the event can bubble across the boundary between the shadow DOM and the regular DOM.
+
{{domxref("Event.currentTarget")}} {{readonlyinline}}
+
指向目前處理事件之監聽器所屬的 DOM 物件。
+
{{domxref("Event.deepPath")}} {{non-standard_inline}}
+
An {{jsxref("Array")}} of DOM {{domxref("Node")}}s through which the event has bubbled.
+
{{domxref("Event.defaultPrevented")}} {{readonlyinline}}
+
布林值,表示事件的預設行為是否被 {{domxref("event.preventDefault()", "preventDefault()")}} 方法所取消。
+
{{domxref("Event.eventPhase")}} {{readonlyinline}}
+
表示事件目前的傳遞階段。
+
{{domxref("Event.explicitOriginalTarget")}} {{non-standard_inline}} {{readonlyinline}}
+
事件的明確原定目標(Mozilla 專屬)。
+
{{domxref("Event.originalTarget")}} {{non-standard_inline}} {{readonlyinline}}
+
事件重新導向前的原定目標(Mozilla 專屬)。
+
{{domxref("Event.returnValue")}}
+
非標準屬性。用以替代 {{domxref("Event.preventDefault()", "preventDefault()")}} 方法與 {{domxref("Event.defaultPrevented", "defaultPrevented")}} 屬性(舊版 Internet Explorer 專屬)。
+
{{domxref("Event.scoped")}} {{readonlyinline}} {{obsolete_inline}}
+
A {{jsxref("Boolean")}} indicating whether the given event will bubble across through the shadow root into the standard DOM. This property has been renamed to {{domxref("Event.composed", "composed")}}.
+
{{domxref("Event.srcElement")}} {{non-standard_inline}}
+
非標準屬性。為 {{domxref("Event.target", "target")}} 屬性的別名(舊版 Internet Explorer 專屬)。
+
{{domxref("Event.target")}} {{readonlyinline}}
+
指向最初觸發事件的 DOM 物件。
+
{{domxref("Event.timeStamp")}} {{readonlyinline}}
+
事件發生(事件物件建立)至今的時間。
+
{{domxref("Event.type")}} {{readonlyinline}}
+
事件類型(不區分大小寫)。
+
{{domxref("Event.isTrusted")}} {{readonlyinline}}
+
表示事件物件是否為瀏覽器建立(比如在用戶點擊之後),或由程式碼所建立(使用建立事件的方法,如 {{domxref("Event.initEvent()", "initEvent()")}})。
+
+ +

Obsolete properties

+ +
+
{{domxref("Event.scoped")}} {{readonlyinline}} {{obsolete_inline}}
+
A {{jsxref("Boolean")}} indicating whether the given event will bubble across through the shadow root into the standard DOM. This property has been renamed to {{domxref("Event.composed", "composed")}}.
+
+ +

方法

+ +
+
{{domxref("Event.createEvent()")}} {{deprecated_inline}}
+
+

Creates a new event, which must then be initialized by calling its initEvent() method.

+
+
{{domxref("Event.composedPath()")}}
+
Returns the event’s path (objects on which listeners will be invoked). This does not include nodes in shadow trees if the shadow root was created with its {{domxref("ShadowRoot.mode")}} closed.
+
+ +
+
{{domxref("Event.initEvent()")}} {{deprecated_inline}}
+
初始化已經建立的事件。若該事件已經被處理過,這方法就不會執行任何東西。
+
{{domxref("Event.preventDefault()")}}
+
取消該事件(如果該事件的 {{domxref("Event.cancelable", "cancelable")}} 屬性為 true)。
+
{{domxref("Event.stopImmediatePropagation()")}}
+
一旦事件物件呼叫此方法,目前元素中尚未執行的已註冊之相同事件類型監聽器將不會被呼叫,而事件也不會繼續捕捉或冒泡傳遞。
+
{{domxref("Event.stopPropagation()")}}
+
阻止事件物件繼續捕捉或冒泡傳遞。
+
+ +

已廢棄方法

+ +
+
{{domxref("Event.getPreventDefault()")}} {{non-standard_inline}}
+
非標準方法。回傳 defaultPrevented 屬性值。請直接改用 {{domxref("Event.defaultPrevented", "defaultPrevented")}} 屬性。
+
{{domxref("Event.preventBubble()")}} {{non-standard_inline}} {{Obsolete_inline(24)}}
+
已廢棄方法。阻止事件繼續冒泡傳遞。請改用 {{domxref("event.stopPropagation()", "stopPropagation()")}} 方法。
+
{{domxref("Event.preventCapture()")}} {{non-standard_inline}} {{Obsolete_inline(24)}}
+
已廢棄方法。請改用 {{domxref("event.stopPropagation()", "stopPropagation()")}} 方法。
+
+ +

規範

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#interface-event', 'Event')}}{{Spec2('DOM WHATWG')}} 
+ +

瀏覽器相容性

+ + + +

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

+ +

參見

+ + diff --git a/files/zh-tw/web/api/event/istrusted/index.html b/files/zh-tw/web/api/event/istrusted/index.html new file mode 100644 index 0000000000..fe35fcc393 --- /dev/null +++ b/files/zh-tw/web/api/event/istrusted/index.html @@ -0,0 +1,107 @@ +--- +title: Event.isTrusted +slug: Web/API/Event/isTrusted +translation_of: Web/API/Event/isTrusted +--- +

{{APIRef("DOM")}}

+ +

{{domxref("Event")}} 介面的 isTrusted 唯讀屬性為一個布林值,若事件物件是由使用者操作而產生,則 isTrusted 值為 true。若事件物件是由程式碼所建立、修改,或是透過 {{domxref("EventTarget.dispatchEvent()")}} 來觸發,則 isTrusted 值為 false

+ +

語法

+ +
var bool = event.isTrusted;
+
+ +

範例

+ +
 if (e.isTrusted) {
+     /* The event is trusted. */
+ } else {
+     /* The event is not trusted. */
+ }
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-event-istrusted', 'Event.isTrusted')}}{{ Spec2('DOM WHATWG') }} 
{{SpecName('DOM3 Events', '#trusted-events', 'Trusted events')}}{{Spec2('DOM3 Events')}}Adds requirements regarding trusted and untrusted events, though it does not itself define the isTrusted property.
{{SpecName('DOM4', '#dom-event-istrusted', 'Event.isTrusted')}}{{Spec2('DOM4')}}Initial definition.
+ +

瀏覽器相容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(46.0)}}{{CompatVersionUnknown}}{{CompatNo}} [1]{{CompatOpera(33)}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}{{CompatChrome(46.0)}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOperaMobile(33)}}{{CompatNo}}{{CompatChrome(46.0)}}
+
+ +

[1] In Internet Explorer, all events are trusted except those that are created with the createEvent() method.

diff --git a/files/zh-tw/web/api/event/preventdefault/index.html b/files/zh-tw/web/api/event/preventdefault/index.html new file mode 100644 index 0000000000..8553f5a23a --- /dev/null +++ b/files/zh-tw/web/api/event/preventdefault/index.html @@ -0,0 +1,129 @@ +--- +title: Event.preventDefault() +slug: Web/API/Event/preventDefault +translation_of: Web/API/Event/preventDefault +--- +
{{ ApiRef("DOM") }}
+ +
 
+ +

概要

+ +

如果事件可以被取消,就取消事件(即取消事件的預設行為)。但不會影響事件的傳遞,事件仍會繼續傳遞。

+ +

語法

+ +
event.preventDefault();
+ +

範例

+ +

Toggling a checkbox is the default action of clicking on a checkbox. This example demonstrates how to prevent that from happening:

+ +
<!DOCTYPE html>
+<html>
+<head>
+<title>preventDefault example</title>
+</head>
+
+<body>
+    <p>Please click on the checkbox control.</p>
+    <form>
+        <label for="id-checkbox">Checkbox</label>
+        <input type="checkbox" id="id-checkbox"/>
+    </form>
+    <script>
+        document.querySelector("#id-checkbox").addEventListener("click", function(event){
+            alert("preventDefault will stop you from checking this checkbox!")
+            event.preventDefault();
+        }, false);
+    </script>
+</body>
+</html>
+ +

You can see preventDefault in action here.

+ +

The following example demonstrates how invalid text input can be stopped from reaching the input field with 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>
+
+ +

Here is the result of the preceding code:

+ +

{{ EmbedLiveSample('preventDefault_invalid_text', '', '', '') }}

+ +

備註

+ +

Calling preventDefault during any stage of event flow cancels the event, meaning that any default action normally taken by the implementation as a result of the event will not occur.

+ +
+

Note: As of {{Gecko("6.0")}}, calling preventDefault() causes the {{ domxref("event.defaultPrevented") }} property's value to become true.

+
+ +

你可以查看 {{domxref("Event.cancelable")}} 屬性來檢查事件是否能夠被取消。對一個不能被取消的事件呼叫 preventDefault() 方法是沒有任何效果的。

+ +

preventDefault() 方法不會停止事件傳遞。若要停止事件繼續傳遞,可以使用 {{domxref("Event.stopPropagation()")}} 方法。

+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-event-preventdefault', 'Event.preventDefault()')}}{{ Spec2('DOM WHATWG') }}
{{SpecName('DOM4', '#dom-event-preventdefault', 'Event.preventDefault()')}}{{ Spec2('DOM4') }}
{{SpecName('DOM2 Events', '#Events-Event-preventDefault', 'Event.preventDefault()')}}{{ Spec2('DOM2 Events') }}Initial definition.
diff --git a/files/zh-tw/web/api/event/stopimmediatepropagation/index.html b/files/zh-tw/web/api/event/stopimmediatepropagation/index.html new file mode 100644 index 0000000000..8b08a441cc --- /dev/null +++ b/files/zh-tw/web/api/event/stopimmediatepropagation/index.html @@ -0,0 +1,94 @@ +--- +title: Event.stopImmediatePropagation() +slug: Web/API/Event/stopImmediatePropagation +tags: + - API + - Event +translation_of: Web/API/Event/stopImmediatePropagation +--- +

{{APIRef("DOM")}}

+ +

除了停止事件繼續捕捉或冒泡傳遞外,也阻止事件被傳入同元素中註冊的其它相同事件類型之監聽器。

+ +

語法

+ +
event.stopImmediatePropagation();
+
+ +

備註

+ +

如果一個元素中註冊了多個相同事件類型的監聽器,監聽器將會按照註冊的先後順序被呼叫。在其中任何一個監聽器執行的期間,若是呼叫了事件物件的 stopImmediatePropagation() 方法,則接下來尚未執行的監聽器皆不會被呼叫。

+ +

規範

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-event-stopimmediatepropagation', 'Event.stopImmediatePropagation()')}}{{Spec2('DOM WHATWG')}} 
{{SpecName('DOM4', '#dom-event-stopimmediatepropagation', 'Event.stopImmediatePropagation()')}}{{Spec2('DOM4')}}Initial definition
+ +

瀏覽器相容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("6.0")}}{{CompatGeckoDesktop("10.0")}}{{CompatIE(9.0)}}{{CompatOpera("15.0")}}{{CompatSafari("5.0")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
diff --git a/files/zh-tw/web/api/event/stoppropagation/index.html b/files/zh-tw/web/api/event/stoppropagation/index.html new file mode 100644 index 0000000000..652231306b --- /dev/null +++ b/files/zh-tw/web/api/event/stoppropagation/index.html @@ -0,0 +1,63 @@ +--- +title: Event.stopPropagation() +slug: Web/API/Event/stopPropagation +tags: + - API + - DOM + - Event + - Method + - NeedsRewrite + - Reference +translation_of: Web/API/Event/stopPropagation +--- +
{{APIRef("DOM")}}
+ +

{{domxref("Event")}} 介面的 stopPropagation() 方法可阻止當前事件繼續進行捕捉(capturing)及冒泡(bubbling)階段的傳遞。

+ +

語法

+ +
event.stopPropagation();
+ +

範例

+ +

請參考範例五:事件傳遞章節中關於此方法與 DOM 事件傳遞的更詳細範例。

+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("DOM WHATWG", "#dom-event-stoppropagation", "Event.stopPropagation()")}}{{Spec2("DOM WHATWG")}}
{{SpecName("DOM4", "#dom-event-stoppropagation", "Event.stopPropagation()")}}{{Spec2("DOM4")}}
{{SpecName("DOM2 Events", "#Events-Event-stopPropagation", "Event.stopPropagation()")}}{{Spec2("DOM2 Events")}}Initial definition
+ +

瀏覽器相容性

+ + + +

{{Compat("api.Event.stopPropagation")}}

+ +

參見

+ + diff --git a/files/zh-tw/web/api/event/target/index.html b/files/zh-tw/web/api/event/target/index.html new file mode 100644 index 0000000000..9599be68c7 --- /dev/null +++ b/files/zh-tw/web/api/event/target/index.html @@ -0,0 +1,134 @@ +--- +title: Event.target +slug: Web/API/Event/target +translation_of: Web/API/Event/target +--- +

{{ApiRef("DOM")}}

+ +

指向最初觸發事件的 DOM 物件。與 {{domxref("event.currentTarget")}} 屬性不同的是,event.currentTarget 屬性總會指向目前於冒泡或捕捉階段正在處理該事件之事件處理器所註冊的 DOM 物件,而 event.target 屬性則是永遠指向觸發事件的 DOM 物件。

+ +

語法

+ +
theTarget = event.target
+ +

範例

+ +

The event.target property can be used in order to implement event delegation.

+ +
// Make a list
+var ul = document.createElement('ul');
+document.body.appendChild(ul);
+
+var li1 = document.createElement('li');
+var li2 = document.createElement('li');
+ul.appendChild(li1);
+ul.appendChild(li2);
+
+function hide(e){
+  // e.target refers to the clicked <li> element
+  // This is different than e.currentTarget which would refer to the parent <ul> in this context
+  e.target.style.visibility = 'hidden';
+}
+
+// Attach the listener to the list
+// It will fire when each <li> is clicked
+ul.addEventListener('click', hide, false);
+
+ +

規範

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

瀏覽器相容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Compatibility notes

+ +

On IE 6-8 the event model is different. Event listeners are attached with the non-standard {{domxref('EventTarget.attachEvent')}} method. In this model, the event object has a {{domxref('Event.srcElement')}} property, instead of the target property, and it has the same semantics as event.target.

+ +
function hide(e) {
+  // Support IE6-8
+  var target = e.target || e.srcElement;
+  target.style.visibility = 'hidden';
+}
+
+ +

參見

+ + diff --git a/files/zh-tw/web/api/event/timestamp/index.html b/files/zh-tw/web/api/event/timestamp/index.html new file mode 100644 index 0000000000..3ec006a09e --- /dev/null +++ b/files/zh-tw/web/api/event/timestamp/index.html @@ -0,0 +1,54 @@ +--- +title: Event.timeStamp +slug: Web/API/Event/timeStamp +translation_of: Web/API/Event/timeStamp +--- +
{{ApiRef("DOM")}}
+ +

說明

+ +

回傳事件建立的時間(單位是毫秒;從 epoch 開始計算)。

+ +

Syntax

+ +
event.timeStamp
+
+ +

範例

+ +
var number = event.timeStamp;
+
+ +

下面是一個較為完整的範例:

+ +
<html>
+<head>
+
+<title>timeStamp example</title>
+
+<script type="text/javascript">
+function getTime(event) {
+  document.getElementById("time").firstChild.nodeValue = event.timeStamp;
+}
+</script>
+</head>
+
+<body onkeypress="getTime(event)">
+
+<p>Press any key to get the current timestamp
+for the onkeypress event.</p>
+<p>timeStamp: <span id="time">-</span></p>
+
+</body>
+</html>
+
+ +

注意

+ +

這個 property 僅在瀏覽器支持該事件才會有用。

+ +

詳細資料

+ + diff --git a/files/zh-tw/web/api/event/type/index.html b/files/zh-tw/web/api/event/type/index.html new file mode 100644 index 0000000000..12fcf0176d --- /dev/null +++ b/files/zh-tw/web/api/event/type/index.html @@ -0,0 +1,97 @@ +--- +title: Event.type +slug: Web/API/Event/type +translation_of: Web/API/Event/type +--- +

{{APIRef}}

+ +

Event.type 唯讀屬性會回傳一個代表此事件物件類型的字串。Event.type 屬性是於事件物件建立時被設定,而其屬性值-事件類型名稱也常被當作是特定的事件。

+ +

傳至 {{ domxref("EventTarget.addEventListener()") }} 和 {{ domxref("EventTarget.removeEventListener()") }} 方法中,代表事件類型的參數 event 是不區分大小寫的。

+ +

可用的事件類型,可參考 event reference

+ +

語法

+ +
event.type
+
+ +

範例

+ +
<!DOCTYPE html>
+<html lang="en">
+<head>
+    <meta charset="utf-8">
+
+    <title>Event.type Example</title>
+
+    <script>
+        var currEvent = null;
+        function getEvtType(evt) {
+            console.log("//Start------------getEvtType(evt)------------ ");
+
+            currEvent = evt.type;
+            console.log(currEvent);
+
+            //document.getElementById("Etype").firstChild.nodeValue = currEvent;
+            document.getElementById("Etype").innerHTML = currEvent;
+
+            console.log("//End--------------getEvtType(evt)------------ ");
+        }
+
+        //Keyboard events
+        document.addEventListener("keypress", getEvtType, false); //[second]
+
+        document.addEventListener("keydown", getEvtType, false); //first
+        document.addEventListener("keyup", getEvtType, false); //third
+
+        //Mouse events
+        document.addEventListener("click", getEvtType, false); // third
+
+        document.addEventListener("mousedown", getEvtType, false); //first
+        document.addEventListener("mouseup", getEvtType, false); //second
+
+    </script>
+</head>
+
+<body>
+
+<p>Press any key or click the mouse to get the event type.</p>
+<p>Event type: <span id="Etype" style="color:red">-</span></p>
+
+</body>
+</html>
+
+ +

Result

+ +

{{EmbedLiveSample('Example')}}

+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-event-type', 'Event.type')}}{{ Spec2('DOM WHATWG') }}
{{SpecName('DOM4', '#dom-event-type', 'Event.type')}}{{ Spec2('DOM4') }}
{{SpecName('DOM2 Events', '#Events-Event-type', 'Event.type')}}{{ Spec2('DOM2 Events') }}Initial definition.
diff --git a/files/zh-tw/web/api/eventlistener/index.html b/files/zh-tw/web/api/eventlistener/index.html new file mode 100644 index 0000000000..8db3fba758 --- /dev/null +++ b/files/zh-tw/web/api/eventlistener/index.html @@ -0,0 +1,93 @@ +--- +title: EventListener +slug: Web/API/EventListener +tags: + - DOM + - 事件 + - 事件監聽 +translation_of: Web/API/EventListener +--- +
{{APIRef("DOM Events")}}
+ +

EventListener 介面表示一個可以處理由 {{domxref("EventTarget")}} 物件分派事件的物件。

+ +
+

注意:基於相容舊版內容的需要, EventListener 可以接受一個函式及一個帶有 handleEvent() 屬性函式的物件。相關的範例顯示在下方。

+
+ +

屬性

+ +

這個介面並不實作且不繼承任何屬性。

+ +

方法

+ +

這個介面不繼承任何方法。

+ +
+
{{domxref("EventListener.handleEvent()")}}
+
一個可以在指定類型事件發生時被呼叫的函數。
+
+ +

範例

+ +

HTML

+ +
<button id="btn">Click here!</button>
+ +

JavaScript

+ +
const buttonElement = document.getElementById('btn');
+
+// 透過提供回呼函數的方式對「click」事件新增處理器。
+// 當元素被點選後會出現「Element clicked!」的彈出訊息。
+buttonElement.addEventListener('click', function (event) {
+  alert('Element clicked through function!');
+});
+
+// 基於相容性,一個帶有 `handleEvent` 的非函式物件可被視為處理函式。
+buttonElement.addEventListener('click', {
+  handleEvent: function (event) {
+    alert('Element clicked through handleEvent property!');
+  }
+});
+
+ +

結果

+ +

{{EmbedLiveSample('Example')}}

+ +

檢閱相關:

+ + + +

規格

+ + + + + + + + + + + + + + + + + + + + + +
規格狀態註解
{{SpecName('DOM WHATWG', '#callbackdef-eventlistener', 'EventListener')}}{{Spec2('DOM WHATWG')}}No change.
{{SpecName('DOM2 Events', '#Events-EventListener', 'EventListener')}}{{Spec2('DOM2 Events')}}Initial definition.
+ +

瀏覽器相容性

+ + + +

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

diff --git a/files/zh-tw/web/api/eventtarget/dispatchevent/index.html b/files/zh-tw/web/api/eventtarget/dispatchevent/index.html new file mode 100644 index 0000000000..8977c22c9e --- /dev/null +++ b/files/zh-tw/web/api/eventtarget/dispatchevent/index.html @@ -0,0 +1,134 @@ +--- +title: EventTarget.dispatchEvent() +slug: Web/API/EventTarget/dispatchEvent +translation_of: Web/API/EventTarget/dispatchEvent +--- +

{{APIRef("DOM Events")}}

+ +

於此 {{domxref("EventTarget")}} 物件上觸發特定的 {{domxref("Event")}} 物件實體,相當於依照註冊的順序呼叫它的 {{domxref("EventListener")}}。一般事件處理規則(包含捕捉(capturing)和可選的冒泡(bubbling)階段)也適用於用 dispatchEvent() 手動觸發事件。

+ +

語法

+ +
cancelled = !target.dispatchEvent(event)
+
+ +

參數

+ + + +

回傳值

+ + + +

若遇到以下 3 種情況,dispatchEvent 會拋出錯誤資訊--  UNSPECIFIED_EVENT_TYPE_ERR :

+ +
    +
  1. 執行 dispatchEvent 前並未藉由初始化事件指定事件類型
  2. +
  3. 事件類型為 null
  4. +
  5. 事件類型是個空白字串。
  6. +
+ +

這些異常,處理器會報告「異常未捕獲(uncaught exceptions)」;

+ +

事件處理器(event handlers)會在一群呼叫堆(nested callstack)上執行:事件的呼叫方(caller)會先由處理器會阻擋暫停執行,直到事件完成才繼續執行,但是要注意的是,事件若發生異常並不會傳回給呼叫方。

+ +

注意

+ +

dispatchEvent 是「建立→初始化→觸發」的最後一步驟。這些步驟是用來觸發事件,讓事件完成。事件有多種建立方式,例如用 {{domxref("​document.createEvent")}} 並用 initEvent 或其他特殊 methods ,像是 initMouseEventinitUIEvent 來初始化。

+ +

詳請可參考《{{domxref("Event")}}》。

+ +

範例

+ +

請參閱《建立或觸發事件》。

+ +

規格

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-eventtarget-dispatchevent', 'EventTarget.dispatchEvent()')}}{{ Spec2('DOM WHATWG') }} 
{{SpecName('DOM4', '#dom-eventtarget-dispatchevent', 'EventTarget.dispatchEvent()')}}{{ Spec2('DOM4') }} 
{{SpecName('DOM2 Events', '#Events-EventTarget-dispatchEvent', 'EventTarget.dispatchEvent()')}}{{ Spec2('DOM2 Events') }}初始定義
+ +

瀏覽器支援度

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support4{{CompatVersionUnknown}}29 [1]9.64 (probably earlier)3.2 (probably earlier)
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}{{CompatVersionUnknown}}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

[1]:早期的 IE 版本只支持 IE 特有的 {{domxref("EventTarget.fireEvent()")}} 方法來觸發事件。

diff --git a/files/zh-tw/web/api/eventtarget/index.html b/files/zh-tw/web/api/eventtarget/index.html new file mode 100644 index 0000000000..4c10aa133e --- /dev/null +++ b/files/zh-tw/web/api/eventtarget/index.html @@ -0,0 +1,177 @@ +--- +title: EventTarget +slug: Web/API/EventTarget +tags: + - API + - DOM + - DOM Events + - Interface + - NeedsTranslation + - TopicStub + - 待翻譯 +translation_of: Web/API/EventTarget +--- +

{{ ApiRef("DOM Events") }}

+ +

EventTarget 介面定義了其實作的物件具有接收事件的能力,也可能擁有處理事件的監聽器。

+ +

除了最為常見的 {{domxref("Element")}}、{{domxref("Document")}} 與 {{domxref("Window")}} 繼承或實作了 EventTarget 介面之外,其它的物件還有 {{domxref("XMLHttpRequest")}}、{{domxref("AudioNode")}}、{{domxref("AudioContext")}}⋯等等。

+ +

許多 EventTarget(包括 Element、Document 和 Window)除了透過 {{domxref("EventTarget.addEventListener()", "addEventListener()")}} 方法外,還可藉由 {{domxref("Document_Object_Model", "DOM")}} 物件的屬性({{Glossary("property/JavaScript", "property")}})或 HTML 元素屬性({{Glossary("attribute")}})來設定事件處理器

+ +

{{InheritanceDiagram}}

+ +

方法

+ +
+
{{domxref("EventTarget.addEventListener()")}}
+
EventTarget 物件上註冊指定事件的監聽器。
+
{{domxref("EventTarget.removeEventListener()")}}
+
移除 EventTarget 物件上的指定事件監聽器。
+
{{domxref("EventTarget.dispatchEvent()")}}
+
對此 EventTarget 物件派送(dispatch)一個事件物件,也就是於此 EventTarget 物件上觸發一個指定的事件物件實體。
+
+ +

Mozilla chrome code 的額外方法

+ +

Mozilla extensions for use by JS-implemented event targets to implement on* properties. See also WebIDL bindings.

+ + + +

範例

+ +

Simple implementation of EventTarget

+ +
var EventTarget = function() {
+  this.listeners = {};
+};
+
+EventTarget.prototype.listeners = null;
+EventTarget.prototype.addEventListener = function(type, callback) {
+  if (!(type in this.listeners)) {
+    this.listeners[type] = [];
+  }
+  this.listeners[type].push(callback);
+};
+
+EventTarget.prototype.removeEventListener = function(type, callback) {
+  if (!(type in this.listeners)) {
+    return;
+  }
+  var stack = this.listeners[type];
+  for (var i = 0, l = stack.length; i < l; i++) {
+    if (stack[i] === callback){
+      stack.splice(i, 1);
+      return;
+    }
+  }
+};
+
+EventTarget.prototype.dispatchEvent = function(event) {
+  if (!(event.type in this.listeners)) {
+    return true;
+  }
+  var stack = this.listeners[event.type];
+  event.target = this;
+  for (var i = 0, l = stack.length; i < l; i++) {
+    stack[i].call(this, event);
+  }
+  return !event.defaultPrevented;
+};
+
+ +

{{ EmbedLiveSample('_Simple_implementation_of_EventTarget') }}

+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#interface-eventtarget', 'EventTarget')}}{{Spec2('DOM WHATWG')}}No change.
{{SpecName('DOM3 Events', 'DOM3-Events.html#interface-EventTarget', 'EventTarget')}}{{Spec2('DOM3 Events')}}A few parameters are now optional (listener), or accepts the null value (useCapture).
{{SpecName('DOM2 Events', 'events.html#Events-EventTarget', 'EventTarget')}}{{Spec2('DOM2 Events')}}Initial definition.
+ +

瀏覽器相容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support1.0{{CompatVersionUnknown}}{{CompatGeckoDesktop("1")}}9.071.0[1]
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support1.0{{CompatVersionUnknown}}{{CompatGeckoMobile("1")}}9.06.01.0
+
+ +

[1] window.EventTarget does not exist.

+ +

參見

+ + diff --git a/files/zh-tw/web/api/eventtarget/removeeventlistener/index.html b/files/zh-tw/web/api/eventtarget/removeeventlistener/index.html new file mode 100644 index 0000000000..136aa0cf58 --- /dev/null +++ b/files/zh-tw/web/api/eventtarget/removeeventlistener/index.html @@ -0,0 +1,274 @@ +--- +title: EventTarget.removeEventListener() +slug: Web/API/EventTarget/removeEventListener +translation_of: Web/API/EventTarget/removeEventListener +--- +

{{APIRef("DOM Events")}}

+ +

EventTarget.removeEventListener() 方法可以移除先前由 {{domxref("EventTarget.addEventListener()", "addEventListener()")}} 所註冊的事件監聽器。

+ +

語法

+ +
target.removeEventListener(type, listener[, options]);
+target.removeEventListener(type, listener[, useCapture]);
+
+ +

參數

+ +
+
type
+
A string representing the event type to remove.
+
listener
+
The {{domxref("EventListener")}} function to remove from the event target.
+
options {{optional_inline}}
+
An options object that specifies characteristics about the event listener. The available options are: +
    +
  • capture: A {{jsxref("Boolean")}} that indicates that events of this type will be dispatched to the registered listener before being dispatched to any EventTarget beneath it in the DOM tree.  
  • +
  • passive: A {{jsxref("Boolean")}} indicating that the listener will never call preventDefault(). If it does, the user agent should ignore it and generate a console warning.
  • +
  • {{non-standard_inline}} mozSystemGroup: Available only in code running in XBL or in Firefox' chrome, it is a {{jsxref("Boolean")}} defining if the listener is added to the system group.
  • +
+
+
useCapture {{optional_inline}}
+
Specifies whether the {{domxref("EventListener")}} to be removed is registered as a capturing listener or not. If this parameter is absent, a default value of false is assumed.
+
If a listener is registered twice, one with capture and one without, remove each one separately. Removal of a capturing listener does not affect a non-capturing version of the same listener, and vice versa.
+
+ +
Note: useCapture was required in most major browsers' early versions. If broad compatibility is desired, you should always provide the useCapture parameter.
+ +

回傳值

+ +

無。

+ +

備註

+ +

If an {{domxref("EventListener")}} is removed from an {{domxref("EventTarget")}} while it is processing an event, it will not be triggered by the current actions. An {{domxref("EventListener")}} will not be invoked for the event it was registered for after being removed, however it can be reattached.

+ +

Calling removeEventListener() with arguments that do not identify any currently registered {{domxref("EventListener")}} on the EventTarget has no effect.

+ +

範例

+ +

This example shows how to add a click-based event listener and remove a mouseover-based event listener.

+ +
var body =
+        document.querySelector('body'),
+    clickTarget =
+        document.getElementById('click-target'),
+    mouseOverTarget =
+        document.getElementById('mouse-over-target'),
+    toggle = false;
+
+function makeBackgroundYellow() {
+    'use strict';
+
+    if (toggle) {
+        body.style.backgroundColor = 'white';
+    } else {
+        body.style.backgroundColor = 'yellow';
+    }
+
+    toggle = !toggle;
+}
+
+clickTarget.addEventListener('click',
+    makeBackgroundYellow,
+    false
+);
+
+mouseOverTarget.addEventListener('mouseover', function () {
+    'use strict';
+
+    clickTarget.removeEventListener('click',
+        makeBackgroundYellow,
+        false
+    );
+});
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("DOM WHATWG", "#dom-eventtarget-removeeventlistener", "EventTarget.removeEventListener()")}}{{Spec2("DOM WHATWG")}} 
{{SpecName("DOM4", "#dom-eventtarget-removeeventlistener", "EventTarget.removeEventListener()")}}{{Spec2("DOM4")}} 
{{SpecName("DOM2 Events", "#Events-EventTarget-removeEventListener", "EventTarget.removeEventListener()")}}{{Spec2("DOM2 Events")}}Initial definition
+ +

瀏覽器相容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support1.0[1][2]{{CompatGeckoDesktop("1")}}[3]9.07[4]1.0[1]
useCapture made optional{{CompatVersionUnknown}}6.09.011.60{{CompatVersionUnknown}}
options parameter{{CompatChrome(49.0)}}    
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support1.0[1]{{CompatVersionUnknown}}[2]{{CompatGeckoMobile("1")}}[3]9.06.0[4]1.0[1]{{CompatVersionUnknown}}[2]
useCapture made optional{{CompatUnknown}}{{CompatVersionUnknown}}    {{CompatVersionUnknown}}
options parameter{{CompatNo}}{{CompatChrome(49.0)}}    {{CompatChrome(49.0)}}
+
+ +

[1] Although WebKit explicitly added "[optional]" to the useCapture parameter for Safari 5.1 and Chrome 13, it had been working before the change.

+ +

[2] Before Chrome 49, the type and listener parameters were optional.

+ +

[2] Prior to Firefox 6, the browser would throw an exception if the useCapture parameter was not explicitly false. Prior to Gecko 9.0 {{geckoRelease("9.0")}}, addEventListener() would throw an exception if the listener parameter was null; now the method returns without error, but without doing anything.

+ +

[4] Opera 11.60 made the useCapture parameter optional (source).

+ +

[5] For backwards compatibility, browsers that support options allow the third parameter to be either options or Boolean.

+ +

Polyfill to support older browsers

+ +

addEventListener() and removeEventListener() are not present in older browsers. You can work around this by inserting the following code at the beginning of your scripts, allowing the use of addEventListener() and removeEventListener() in implementations that do not natively support it. However, this method will not work on Internet Explorer 7 or earlier, since extending the Element.prototype was not supported until 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/zh-tw/web/api/fetch_api/index.html b/files/zh-tw/web/api/fetch_api/index.html new file mode 100644 index 0000000000..2cd6f23d22 --- /dev/null +++ b/files/zh-tw/web/api/fetch_api/index.html @@ -0,0 +1,84 @@ +--- +title: Fetch API +slug: Web/API/Fetch_API +translation_of: Web/API/Fetch_API +--- +
{{DefaultAPISidebar("Fetch API")}}
+ +
Fetch API 提供了一個能獲取包含跨網路資源在的資源介面。它有點像我們所熟悉的 {{domxref("XMLHttpRequest")}} ,但這個新的 API 提供了更強更彈性的功能。
+ +

概念與應用

+ +

Fetch 提供了 {{domxref("Request")}} 與 {{domxref("Response")}} 物件,還有其他牽涉網路請求的通用定義。這能讓他們在需要的時候被使用到,不管是 service worker、Cache API、還是其他處理或更動請求回應的相類事物、或是任何需要產生有序化產生回應的用例(use case)。

+ +

它也提供了諸如 CORS 與 HTTP origin 標頭語意的分散定義,能取代分散的定義。

+ +

要發動請求並取得資源的話,請使用 {{domxref("GlobalFetch.fetch")}} 方法。他實作了數種介面,並指定了 {{domxref("Window")}} 與 {{domxref("WorkerGlobalScope")}},使它可以在任何想獲取資源的環境中使用。

+ +

fetch() 方法有一個強制性的參數,就是要取得資源的網址。該方法會回傳一個不論請求成敗,都會 resolve 的 promise {{domxref("Response","回應")}}。你也能選擇性地使用第二個稱為 init 的物件參數(請參見 {{domxref("Request")}})。

+ +

當 {{domxref("Response")}} 檢索後,在請求體裡面會定義一些請求體為何,還有要如何處理的方法(請參見 {{domxref("Body")}})。

+ +

你也可以直接用 {{domxref("Request.Request","Request()")}} 與 {{domxref("Response.Response","Response()")}} 建構子來建立請求與回應,不過你不太可能直接使用他,反而更可能是以其他 API 行動的結果為形式存在。(例如來自 service worker 的 {{domxref("FetchEvent.respondWith")}})

+ +
+

注意:你可以在使用 Fetch深入理解 Fetch,並在Fetch 的基本概念文章內理解概念。

+
+ +

中斷一次 Fetch

+ +

各家瀏覽器已經開始加入 {{DOMxRef("AbortController")}} 與 {{DOMxRef("AbortSignal")}} 介面(也就是 Abort API)的實驗性支援,讓 Fetch 和 XHR 這類的操作在完成前可以被中斷。詳情請參閱相關介面的文件。

+ +

Fetch 介面

+ +
+
{{DOMxRef("WindowOrWorkerGlobalScope.fetch()")}}
+
用於取得資源的 fetch() 方法。
+
{{domxref("Headers")}}
+
代表請求/回應標頭,讓你能 query 並針對結果不同,採取不同行動。
+
{{domxref("Request")}}
+
代表資源請求。
+
{{domxref("Response")}}
+
代表資源請求的回應。
+
+ +

Fetch mixin

+ +
+
{{domxref("Body")}}
+
提供請求/回應訊息體的相關方法,能宣告內容的類別為何,以及該如何處理。
+
+ +

規範

+ + + + + + + + + + + + + + +
規範狀態註解
{{SpecName('Fetch')}}{{Spec2('Fetch')}}初始定義
+ +

瀏覽器相容性

+ + + +

{{Compat("api.WindowOrWorkerGlobalScope.fetch")}}

+ +

參見

+ + diff --git a/files/zh-tw/web/api/fetch_api/using_fetch/index.html b/files/zh-tw/web/api/fetch_api/using_fetch/index.html new file mode 100644 index 0000000000..3af949b659 --- /dev/null +++ b/files/zh-tw/web/api/fetch_api/using_fetch/index.html @@ -0,0 +1,379 @@ +--- +title: Using Fetch +slug: Web/API/Fetch_API/Using_Fetch +tags: + - Fetch + - HTTP + - Promise + - Response + - request +translation_of: Web/API/Fetch_API/Using_Fetch +--- +

{{DefaultAPISidebar("Fetch API")}}

+ +
+

Fetch API 提供了一種 JavaScript Interface 來操作 HTTP pipeline,比方 request 和 response。同時它也提供了 global 的 {{domxref("GlobalFetch.fetch","fetch()")}} method,使得在網路上非同步地 fetch resources 這件事變得簡單易懂。

+
+ +

同樣的功能,以前都是使用 {{domxref("XMLHttpRequest")}},而 Fetch 作為其替代方案,能更方便地整合在如 {{domxref("ServiceWorker_API", "Service Workers")}} 等相關技術上。此外,Fetch 具備額外的 logical palce,能拿來定義其他和 HTTP 有關的東西,像是 CORS 和 HTTP extensions。

+ +

 fetch 和 jQuery.ajax() 有三個主要的差異:

+ + + +

使用 Fetch 發送請求 ( request )

+ +

用法簡單,如下:

+ +
fetch('http://example.com/movies.json')
+  .then(function(response) {
+    return response.json();
+  })
+  .then(function(myJson) {
+    console.log(myJson);
+  });
+
+
+ +

這裡要使用 fetch 透過網路取得 json 然後印出在 console,最簡單的方式只需要一個參數就是資料的 URI,fetch 會回傳一個包含 response 的 promise 。

+ +

這個範例使用的 url 只是示意用。

+ +

回傳的 response 需要透過 {{domxref("Body.json","json()")}} (在 {{domxref("Body")}} 可以找到定義, Body 是用 {{domxref("Request")}} 和 {{domxref("Response")}} 實作出來的物件.)

+ +
+

備註: 其實 Body 還提供了其他類似的功能可以將內容輸成其他類型格式,詳見{{anch("Body")}} 

+
+ +

Fetch 請求的安全性 Content Security Policy(內容安全策略) 是由 header 中的 connect-src directive 所設定 ,並非其他 directive ( 比如:img-src、default-src 等)。

+ +

Request 可用的設定值

+ +

fetch() 第二個參數是選用的,可以傳送一個 init Object 來設定 request。

+ +

更多可以用的設定值詳見 {{domxref("GlobalFetch.fetch","fetch()")}} 

+ +
// 來發個 POST Request:
+
+postData('http://example.com/answer', {answer: 42})
+  .then(data => console.log(data)) // JSON from `response.json()` call
+  .catch(error => console.error(error))
+
+function postData(url, data) {
+  // Default options are marked with *
+  return fetch(url, {
+    body: JSON.stringify(data), // must match 'Content-Type' header
+    cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
+    credentials: 'same-origin', // include, same-origin, *omit
+    headers: {
+      'user-agent': 'Mozilla/4.0 MDN Example',
+      'content-type': 'application/json'
+    },
+    method: 'POST', // *GET, POST, PUT, DELETE, etc.
+    mode: 'cors', // no-cors, cors, *same-origin
+    redirect: 'follow', // manual, *follow, error
+    referrer: 'no-referrer', // *client, no-referrer
+  })
+  .then(response => response.json()) // 輸出成 json
+}
+
+ +

包含憑證(Credentials) 的 Request 用法

+ +

要讓瀏覽器將 credentials 跟著 request 一起送出, 方式就是在 init object 加上 credentials: 'include' 

+ +
fetch('https://example.com', {
+  credentials: 'include'
+})
+ +

如果只想要把 credentials 發送給同源的 URL ,加上credentials: 'same-origin'

+ +
// The calling script is on the origin 'https://example.com'
+
+fetch('https://example.com', {
+  credentials: 'same-origin'
+})
+ +

或要確保瀏覽器不會帶著 credentials 請求,可以用 credentials: 'omit' 。

+ +
fetch('https://example.com', {
+  credentials: 'omit'
+})
+ +

上傳JSON資料

+ +

使用 {{domxref("GlobalFetch.fetch","fetch()")}} 來 POST JSON 格式的資料。

+ +
var url = 'https://example.com/profile';
+var data = {username: 'example'};
+
+fetch(url, {
+  method: 'POST', // or 'PUT'
+  body: JSON.stringify(data), // data can be `string` or {object}!
+  headers: new Headers({
+    'Content-Type': 'application/json'
+  })
+}).then(res => res.json())
+.catch(error => console.error('Error:', error))
+.then(response => console.log('Success:', response));
+
+ +

上傳檔案

+ +

上傳檔案可以透過使用HTML <input type="file" /> input element, {{domxref("FormData.FormData","FormData()")}} 與{{domxref("GlobalFetch.fetch","fetch()")}}.

+ +
var formData = new FormData();
+var fileField = document.querySelector("input[type='file']");
+
+formData.append('username', 'abc123');
+formData.append('avatar', fileField.files[0]);
+
+fetch('https://example.com/profile/avatar', {
+  method: 'PUT',
+  body: formData
+})
+.then(response => response.json())
+.catch(error => console.error('Error:', error))
+.then(response => console.log('Success:', response));
+
+ +

如何確認fetch是否成功

+ +

當{{domxref("GlobalFetch.fetch","fetch()")}}遇到CORS或server設定錯誤導致network error時,  promise會reject並附上{{jsxref("TypeError")}}的回應, 但在權限或類似問題導致404的常見狀況下, 卻不會導致network error.

+ +

因此, 確認fetch()是否成功的正確方式, 應包含檢查promise resolved, 以及檢查{{domxref("Response.ok")}}的屬性是否為true. 代碼如下例:

+ +
fetch('flowers.jpg').then(function(response) {
+  if(response.ok) {
+    return response.blob();
+  }
+  throw new Error('Network response was not ok.');
+}).then(function(myBlob) {
+  var objectURL = URL.createObjectURL(myBlob);
+  myImage.src = objectURL;
+}).catch(function(error) {
+  console.log('There has been a problem with your fetch operation: ', error.message);
+});
+ +

Supplying your own request object

+ +

Instead of passing a path to the resource you want to request into the fetch() call, you can create a request object using the {{domxref("Request.Request","Request()")}} constructor, and pass that in as a fetch() method argument:

+ +
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() accepts exactly the same parameters as the fetch() method. You can even pass in an existing request object to create a copy of it:

+ +
var anotherRequest = new Request(myRequest, myInit);
+ +

This is pretty useful, as request and response bodies are one use only. Making a copy like this allows you to make use of the request/response again, while varying the init options if desired.  The copy must be made before the body is read, and reading the body in the copy will also mark it as read in the original request.

+ +
+

Note: There is also a {{domxref("Request.clone","clone()")}} method that creates a copy. Both methods of creating a copy will fail if the body of the original request or response has already been read, but reading the body of a cloned response or request will not cause it to be marked as read in the original.

+
+ +

Headers

+ +

The {{domxref("Headers")}} interface allows you to create your own headers object via the {{domxref("Headers.Headers","Headers()")}} constructor. A headers object is a simple multi-map of names to values:

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

The same can be achieved by passing an array of arrays or an object literal to the constructor:

+ +
myHeaders = new Headers({
+  "Content-Type": "text/plain",
+  "Content-Length": content.length.toString(),
+  "X-Custom-Header": "ProcessThisImmediately",
+});
+ +

The contents can be queried and retrieved:

+ +
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.get("X-Custom-Header")); // ["ProcessThisImmediately", "AnotherValue"]
+
+myHeaders.delete("X-Custom-Header");
+console.log(myHeaders.get("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.includes("application/json")) {
+      return response.json();
+    }
+    throw new TypeError("Oops, we haven't got JSON!");
+  })
+  .then(function(json) { /* process your JSON further */ })
+  .catch(function(error) { console.log(error); });
+ +

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.

+ +

The most common response properties you'll use are:

+ + + +

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) { // ServiceWorker intercepting a fetch
+  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.)

+ + + +
+

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.

+ +

特性偵測

+ +

想確認是否支持 Fetch API,可透過檢查 {{domxref("Headers")}}、{{domxref("Request")}}、{{domxref("Response")}} 或 {{domxref("GlobalFetch.fetch","fetch()")}} 是否存在 {{domxref("Window")}} 或 {{domxref("Worker")}} 域中。例如:

+ +
if (self.fetch) {
+    // run my fetch request here
+} else {
+    // do something with XMLHttpRequest?
+}
+ +

Polyfill

+ +

在不支援 Fetch 的瀏覽器, 可改用 Fetch Polyfill 來重新支持缺少的 fetch 功能。

+ +

技術指標

+ + + + + + + + + + + + + + +
技術名稱狀態說明
{{SpecName('Fetch')}}{{Spec2('Fetch')}}Initial definition
+ +

瀏覽器相容性

+ +
+ + +

{{Compat("api.WindowOrWorkerGlobalScope.fetch")}}

+
+ +

參見

+ + diff --git a/files/zh-tw/web/api/file/file/index.html b/files/zh-tw/web/api/file/file/index.html new file mode 100644 index 0000000000..1990248f72 --- /dev/null +++ b/files/zh-tw/web/api/file/file/index.html @@ -0,0 +1,112 @@ +--- +title: File.File() +slug: Web/API/File/File +translation_of: Web/API/File/File +--- +

{{APIRef("File")}}

+ +

File()  建構子建立一個新的 {{domxref("File")}} 物件實例

+ +

語法

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

參數

+ +
+
bits
+
An {{jsxref("Array")}} of {{jsxref("ArrayBuffer")}}, {{domxref("ArrayBufferView")}}, {{domxref("Blob")}}, or {{domxref("DOMString")}} objects — 或是由這些物件組成的集合。這是以 UTF-8 編碼的檔案內容。
+
name
+
檔案名稱或檔案的路徑({{domxref("USVString")}})。
+
options {{optional_inline}}
+
物件選項,包含物件非必要的屬性,以下為可得到的屬性: +
    +
  • type: 物件的 MIME 類型({{domxref("DOMString")}} )將被放進檔案中,預設為 ""(空值)。
  • +
  • lastModified: 檔案最後修改時間,格式為毫秒,預設為 {{jsxref("Date.now()")}}.
  • +
+
+
+ +

範例

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

規格

+ + + + + + + + + + + + + + +
規格狀態說明
{{SpecName('File API')}}{{Spec2('File API')}}初始化定義
+ +

瀏覽器相容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support13{{CompatNo}}{{CompatGeckoDesktop("7")}}{{CompatNo}}11.510.1
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support4.4.4{{CompatVersionUnknown}}{{CompatGeckoMobile("7")}}{{CompatNo}}{{CompatNo}}6.0
+
+ +

看更多

+ + diff --git a/files/zh-tw/web/api/file/filename/index.html b/files/zh-tw/web/api/file/filename/index.html new file mode 100644 index 0000000000..0e6cceb4f3 --- /dev/null +++ b/files/zh-tw/web/api/file/filename/index.html @@ -0,0 +1,32 @@ +--- +title: File.fileName +slug: Web/API/File/fileName +translation_of: Web/API/File/fileName +--- +

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

+ +

{{deprecated_header(7.0)}}

+ +

總覽

+ +

回傳檔案名稱,基於安全因素,檔案路徑不包含這個屬性。

+ +
這個檔案是廢棄的,使用 {{domxref("File.name")}} 取代。
+ +

語法

+ +
var name = instanceOfFile.fileName
+ +

數值

+ +

字串

+ +

格式

+ +

尚無資料

+ +

看更多

+ + diff --git a/files/zh-tw/web/api/file/index.html b/files/zh-tw/web/api/file/index.html new file mode 100644 index 0000000000..0dce936ff8 --- /dev/null +++ b/files/zh-tw/web/api/file/index.html @@ -0,0 +1,121 @@ +--- +title: File +slug: Web/API/File +tags: + - API + - File API + - Interface + - Reference + - Web + - 介面 + - 參考 + - 檔案 API + - 檔案API + - 網路 +translation_of: Web/API/File +--- +
{{APIRef}}
+ +

File 介面提供了檔案的資訊並且允許網頁中的 JavaScript 存取檔案的內容。

+ +

File 物件通常是從使用者於 {{HTMLElement("input")}} 元素選擇之檔案所回傳的 {{domxref("FileList")}} 物件當中取得,也可以來自拖放操作所產生的 {{domxref("DataTransfer")}} 物件之中,或是由 {{domxref("HTMLCanvasElement")}} 物件(元素物件)執行 mozGetAsFile() 方法後回傳。在 Gecko 引擎中,有專屬的程式碼能不需使用者操作即建立 File 物件來表示本地端的任一檔案(請參考 {{anch("Implementation notes")}} 以閱讀更多資訊)。

+ +

File 物件是一種特殊的 {{domxref("Blob")}},且可被用在任何接受 Blob 物件的地方。特別是 {{domxref("FileReader")}}、{{domxref("URL.createObjectURL()")}}、{{domxref("ImageBitmapFactories.createImageBitmap()", "createImageBitmap()")}} 和 {{domxref("XMLHttpRequest", "", "send()")}} 都能夠同樣接受 Blob 以及 File

+ +

請參考在網頁應用程式中使用本地檔案的更多細節與範例。

+ +

{{InheritanceDiagram}}

+ +

建構式

+ +
+
{{domxref("File.File", "File()")}}
+
回傳一個新建構的 File 物件。
+
+ +

屬性

+ +
+
{{domxref("File.lastModified")}} {{readonlyinline}}
+
回值檔案的最後修改時間,為 UNIX epoch 毫秒(自西元 1970 年一月 1 日零時至今)。
+
{{domxref("File.lastModifiedDate")}} {{readonlyinline}} {{deprecated_inline}} {{gecko_minversion_inline("15.0")}}
+
File 物件所代表之檔案的最後修改日期(Date)。
+
{{domxref("File.name")}} {{readonlyinline}}
+
File 物件所代表之檔案的名稱。
+
{{domxref("File.size")}} {{readonlyinline}}
+
回傳檔案大小。
+
{{domxref("File.webkitRelativePath")}} {{readonlyinline}} {{non-standard_inline}}
+
回傳相對於 {{domxref("File")}} 的網址位置。
+
{{domxref("File.type")}} {{readonlyinline}}
+
回傳檔案的 MIME 類型。
+
+ +

File 實作了 {{domxref("Blob")}},因此它也有以下可用屬性:

+ +
+
{{domxref("File.size")}} {{readonlyinline}}
+
回傳檔案大小(單位為位元組)。
+
{{domxref("File.type")}} {{readonlyinline}}
+
回傳檔案的 MIME 類型。
+
+ +

方法

+ +

File 介面沒有定義任何方法,但繼承了 {{domxref("Blob")}} 介面的方法:

+ +
+
{{domxref("Blob.slice()", "Blob.slice([start[, end[, contentType]]])")}}
+
+

回傳新的 Blob 物件,包含 Blob 來源之指定位元組範圍的資料。

+
+
+ +

規範

+ + + + + + + + + + + + + + +
規範狀態備註
{{SpecName('File API')}}{{Spec2('File API')}}初次定義
+ +

瀏覽器相容性

+ +
+ + +

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

+
+ +

 

+ +

實作備註

+ + + +

參見

+ + diff --git a/files/zh-tw/web/api/file/using_files_from_web_applications/index.html b/files/zh-tw/web/api/file/using_files_from_web_applications/index.html new file mode 100644 index 0000000000..52bd1928b3 --- /dev/null +++ b/files/zh-tw/web/api/file/using_files_from_web_applications/index.html @@ -0,0 +1,411 @@ +--- +title: 在網頁應用程式中使用本地檔案 +slug: Web/API/File/Using_files_from_web_applications +tags: + - 待翻譯 +translation_of: Web/API/File/Using_files_from_web_applications +--- +

 {{ gecko_minversion_header("1.9.2") }}

+ +

現在可以透過新增至HTML5 DOM的File API讓web內容要求使用者選取本地端的檔案後讀取被選取檔案中的內容。檔案的選取動作可以使用HTML的 input 元素,或是用拖曳檔案(drag and drop)的方式來完成。

+ +

如果你想要使用 DOM 檔案 API 的文件擴展或是其他Chrome 程式碼,你可以參考使用DOM檔案API在FireFox外觀代碼中

+ +

使用HTML選擇本地檔案

+ +

HTML 語法:

+ +
<input type="file" id="input">
+ +

File API 可以從 {{ domxref("File") }} 物件中讀取 {{ domxref("FileList") }} ,{{domxref("FileList") }} 內包含使用者所選取的檔案。

+ +

如果使用者只選擇一個檔案,那麼我們只需要考慮第一個檔案物件。

+ +

使用 DOM 獲取選擇的檔案:

+ +
var selectedFile = document.getElementById('input').files[0];
+ +

使用 jQuery 獲取選擇的檔案:

+ +
var selectedFile = $('#input').get(0).files[0];
+
+var selectedFile = $('#input')[0].files[0];
+
+ +
+

如果獲取 "files is undefined" 錯誤: 代表未選擇正確的 HTML 元素, 這時忘記 jQuery 回傳符合 DOM 元素的清單. 改使用 DOM 元素呼叫  "files" 方法.

+
+ +

使用 change event 獲取選擇的檔案

+ +

使用File API選擇單一檔案是非常簡單的,如下

+ +
<input type="file" id="input" onchange="handleFiles(this.files)">
+
+ +

當使用者選取一個檔案,呼叫 handleFiles() 會得到一個 {{domxref("FileList") }} 的物件。{{domxref("FileList") }} 裡面還會有一個 {{domxref("File")}} 的物件,裡面的東西就是使用者選取的檔案。

+ +

如果你想要讓使用者一次選擇多個檔案,可以在 input 元素中使用 multiple 的屬性:

+ +
<input type="file" id="input" multiple="true" onchange="handleFiles(this.files)">
+
+
+ +

在上述這個例子中,檔案名單會傳遞到 handleFiles() 函數,其中包含了使用者選的每個檔案 {{domxref("File")}} 物件

+ +

使用 EventListener 動態地監聽

+ +

如果使用了其他的函數庫(jQuery),你會需要使用 {{domxref("EventTarget.addEventListener()") }} 去監聽事件,例如:

+ +
var inputElement = document.getElementById("inputField");
+inputElement.addEventListener("change", handleFiles, false);
+
+function handleFiles() {
+  var fileList = this.files;
+
+  /* now you can work with the file list */
+}
+
+ +

在這個例子中,handleFiles() 函數找尋檔案清單而非接收參數, 因為這樣增加的 event listeners 不能接受參數.

+ +

獲得選取檔案的資訊

+ +

由DOM提供的 {{domxref("FileList") }} 物件代表使用者選取的所有檔案,每個又是 {{domxref("File")}} 物件。可以藉由 {{domxref("FileList") }} 的 length 屬性得知使用者選取的檔案數量:

+ +
var numFiles = files.length;
+
+ +

使用陣列獲取 {{domxref("File")}} 物件:

+ +
for (var i = 0; i < files.length; i++) {
+  var file = files[i];
+  ..
+}
+
+ +

上述的例子顯示獲取在檔案清單裡所有檔案物件的方法。

+ +

{{domxref("File")}} 提供三個包含檔案重要訊息的屬性。

+ +
+
name
+
唯讀的檔案名稱,並未包含檔案路徑。
+
size
+
為 64 位元的整數,用以表示檔案的 byte 的長度。
+
type
+
為唯讀字串。表示檔案的 MIME-type 。若是無法取得檔案的 Mime-type ,則其值會是一個空字串 ""
+
+ +

 

+ +

使用click() 方法隱藏檔案輸入元素

+ +

從 Gecko 2.0 {{ geckoRelease("2.0") }}開始,為了顯示個人化開啟檔案的UI和使用者選擇的檔案可以隱藏 {{ HTMLElement("input") }} 元素和顯示個人化的設計。可以藉由設置CSS 「display:none」 和對 {{ HTMLElement("input") }} 元素呼叫 click() 方法。

+ +

HTML 如下:

+ +
<input type="file" id="fileElem" multiple="true" accept="image/*" style="display:none" onchange="handleFiles(this.files)">
+<a href="#" id="fileSelect">Select some files</a>
+
+ +

doClick() 方法:

+ +
var fileSelect = document.getElementById("fileSelect"),
+  fileElem = document.getElementById("fileElem");
+
+fileSelect.addEventListener("click", function (e) {
+  if (fileElem) {
+    fileElem.click();
+  }
+  e.preventDefault(); // prevent navigation to "#"
+}, false);
+
+ +

很明顯的,可以使用CSS來設計新的上傳檔案的按鈕。

+ +

使用拖放選取檔案

+ +

使用者可以使用拖放來選取檔案,首先要設置放的區域,確定文件可以接收放的檔案,方法如下:

+ +
var dropbox;
+
+dropbox = document.getElementById("dropbox");
+dropbox.addEventListener("dragenter", dragenter, false);
+dropbox.addEventListener("dragover", dragover, false);
+dropbox.addEventListener("drop", drop, false);
+
+ +

在這個範例中,我們將 ID "dropbox" 設為放的區域,這是由於我們監聽了 dragenter dragover drop事件

+ +

我們甚至不需要處理 dragenter 和 dragover事件,所以這些函數很簡單。他們阻止了事件的傳播和預設事件的發生:

+ +
function dragenter(e) {
+  e.stopPropagation();
+  e.preventDefault();
+}
+
+function dragover(e) {
+  e.stopPropagation();
+  e.preventDefault();
+}
+
+ +

神奇的 drop() 函數:

+ +
function drop(e) {
+  e.stopPropagation();
+  e.preventDefault();
+
+  var dt = e.dataTransfer;
+  var files = dt.files;
+
+  handleFiles(files);
+}
+
+ +

這邊我們用 dataTransfer 來獲取檔案清單, 並傳遞給 handleFiles().。 我們可以發現,不論使用拖放或是其他取得檔案,處理檔案的方式都是相同。

+ +
+
+ +

範例:顯示選取的圖片

+ +

假設要開發一個分享照片的網站,想使用 HTML5 來讓使用者在上傳圖片前預覽縮圖。簡單來說就是像先前討論地一樣建立 input 元素或是 drop 區域,接著再呼叫類似 handleFiles() 的函數。

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

這邊迴圈處理了使用者選取的每個檔案並檢查每個檔案的類型是不是圖檔(藉由使用正規表達式檢查是否符合字串 "image.*")。每一個是圖片的檔案,我們創建一個 img 元素。CSS 被使用來美化外框、陰影、還有設定圖片的尺寸,所以那些並不需要在這邊寫入。

+ +

為了使圖片可以在DOM裡面更容易被找到,所以每個圖片都有設定CSS class “obj”。 我們也在每個圖檔標記 file 屬性以辨認 File;這使我們更容易取得真正要上傳的圖檔。最後我們使用{{ domxref("Node.appendChild()") }} 在文件中增加縮圖的元素。

+ +

FileReader 處理要非同步讀取的圖檔並跟 img 元素連接。在創建 FileReader 物件後,我們設置了 onload 並 呼叫 readAsDataURL() 在背景呼叫讀取的程序。當所有圖檔都被讀取時,他們被轉換為傳到 onload callback  data URL。 這個範例簡易的設置img 元素的 src 屬性來讀取圖檔並在螢幕上顯示。

+ +

使用 object URLs

+ +

Gecko 2.0 {{ geckoRelease("2.0") }} 支援 DOM 的{{ domxref("window.URL.createObjectURL()") }} 和 {{ domxref("window.URL.revokeObjectURL()") }} 方法。可以藉由這些方法創建表示任何為 DOM File 物件的 data URL 字串,包含了使用者電腦上的檔案。

+ +

可以使 File 物件作為 HTML 元素 URL 的參考,創建 object URL 的方法:

+ +
var objectURL = window.URL.createObjectURL(fileObj);
+
+ +

object URL 為表示 File 物件的字串。即使已經對相同檔案創建了 object URL,每次呼叫 {{ domxref("window.URL.createObjectURL()") }},就會創建一個 object URL。當文檔卸載時他們將會被自動釋放,如果要動態地使用,需要呼叫 {{ domxref("window.URL.revokeObjectURL()") }} 釋放:

+ +
window.URL.revokeObjectURL(objectURL);
+ +

範例:使用 object URLs 顯示圖片

+ +

{{ geckoRelease("2.0") }}這個範例使用 object URLs 顯示圖像縮圖。此外也顯示了其他包含檔案名稱和檔案大小的訊息。線上範例 (註:瀏覽器版本要求 11/22 之後的火狐版本)。

+ +
註: 這個 API 在較早的 Firefox 4 betas 存在但是 11/22 號後的版本有改變, 所以確定瀏覽器在最新的版本!
+ +

HTML:

+ +
<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 doClick() method that invokes the file picker.

+ +

The handleFiles() method follows:

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

範例:上傳檔案

+ +

接下來這個範例顯示如何非同步的上傳檔案到伺服器。

+ +

新增上傳的工作

+ +

接續先前創建縮圖的範例,將每個縮圖都設置 CSS class “obj”,  這使得我們可以很容易地使用{{ domxref("Document.querySelectorAll()") }} 選擇使用者要上傳的圖檔,例如:

+ +
function sendFiles() {
+  var imgs = document.querySelectorAll(".obj");
+
+  for (var i = 0; i < imgs.length; i++) {
+    new FileUpload(imgs[i], imgs[i].file);
+  }
+}
+
+ +

第二行創建了 imgs 陣列,存放著所有文件中 CSS class 為 “obj” 的 Node。在這個範例中,我們使用這個來創建縮圖。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.

+ +

處理上傳檔案的程序

+ +

FileUpload 函數接受圖檔和檔案.

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

FileUpload() 函數創建被用來顯示上傳進度的 throbber,接著創建 {{domxref("XMLHttpRequest")}} 上傳檔案.

+ +

傳輸資料前的幾個準備工作:

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

註: 範例中非標準的 sendAsBinary 方法已經在 Gecko 31 {{ geckoRelease(31) }} 廢棄且很快將會被移除。可以改使用標準的 send(Blob data)。

+
+ +

非同步處理上傳檔案的程序

+ +
function fileUpload(file) {
+  // Please report improvements to: marco.buratto at tiscali.it
+
+  var fileName = file.name,
+    fileSize = file.size,
+    fileData = file.getAsBinary(), // works on TEXT data ONLY.
+    boundary = "xxxxxxxxx",
+    uri = "serverLogic.php",
+    xhr = new XMLHttpRequest();
+
+  xhr.open("POST", uri, true);
+  xhr.setRequestHeader("Content-Type", "multipart/form-data, boundary="+boundary); // simulate a file MIME POST request.
+  xhr.setRequestHeader("Content-Length", fileSize);
+
+  xhr.onreadystatechange = function() {
+    if (xhr.readyState == 4) {
+      if ((xhr.status >= 200 && xhr.status <= 200) || xhr.status == 304) {
+
+        if (xhr.responseText != "") {
+          alert(xhr.responseText); // display response.
+        }
+      }
+    }
+  }
+
+  var body = "--" + boundary + "\r\n";
+  body += "Content-Disposition: form-data; name='fileId'; filename='" + fileName + "'\r\n";
+  body += "Content-Type: application/octet-stream\r\n\r\n";
+  body += fileData + "\r\n";
+  body += "--" + boundary + "--";
+
+  xhr.send(body);
+  return true;
+}
+
+ +

使用二進制數據時,這些程式碼還需要修改。

+ +

你也可以參考這些文章

+ + + +

{{ HTML5ArticleTOC() }}

diff --git a/files/zh-tw/web/api/file_handle_api/index.html b/files/zh-tw/web/api/file_handle_api/index.html new file mode 100644 index 0000000000..bd603fe78a --- /dev/null +++ b/files/zh-tw/web/api/file_handle_api/index.html @@ -0,0 +1,233 @@ +--- +title: FileHandle API +slug: Web/API/File_Handle_API +translation_of: Web/API/File_Handle_API +--- +

FileHandle API 可操作檔案,例如建立檔案、修改檔案內容 (不同於 File API)。而正在編輯中的部分,將使用回合制的鎖定機制,以避免發生競態 (Race) 問題。

+

API

+

建立 FileHandle

+

若要建立 FileHandle 物件,則需要 IndexedDB Database

+
+
var idbreq = indexedDB.open("MyTestDatabase");
+
+idbreq.onsuccess = function(){
+  var db = idbreq.result;
+  var handleReq = db.mozCreateFileHandle("test.bin", "binary");
+
+  handleReq.onsuccess = function(){
+    var handle = handleReq.result;
+    console.log('handle', handle);
+  };
+};
+
+
+

mozCreateFileHandle() 共使用 2 組參數 (Argument):1 組名稱與 1 組檔案類別 (Optional type)。但這 2 組數均只屬於敘述性數,不會用於資料庫。舉例來說,名稱可能是空白字串,而且不需為專屬字串。所以 API 根本不會注意這些參數值。

+

另請注意,上列程式碼僅會建立「暫時性檔案」,亦即當你保留 FileHandle 物件時,該檔案才會存在。如果你要在重新整理頁面/重新啟動 App 之後,仍能保留檔案,則必須將 Handle 儲存於更永久性的位置 (如資料庫本身之內) 中。

+
var transaction = db.transaction(["test"], "readwrite");
+var objectStore = transaction.objectStore("test");
+objectStore.add(myFile, myKey).onsuccess = function(event) {
+  // The file is now referenced from database too.
+}
+
+

FileHandle 介面

+
interface FileHandle
+{
+  LockedFile open(optional DOMString mode);
+  DOMRequest getFile()
+  readonly attribute DOMString name;
+  readonly attribute DOMString type;
+  attribute Function? onabort;
+  attribute Function? onerror;
+};
+
+
+ open([mode="readonly"])
+
+ 可回傳 LockedFilemode 可為「readonly」或「readwrite」。
+
+ getFile()
+
+ 針對檔案而回傳 DOMRequest。若成功,就會收到以 File 物件形式呈現的唯讀「snapshot」檔案內容 (可用於任何接受 Blob 的地方,如 FileReaderXMLHttpRequest 等)。 +
myFile.getFile().onsuccess = function(event) {
+  var file = event.target.result;
+  var transcation = myDatabase.transaction(["snapshots"], "readwrite");
+  var objectStore = transaction.objectStore("snapshots");
+  objectStore.add(file, snapshotKey).onsuccess = function(event) {
+    // A new readonly copy of the file has been created.
+  }
+}
+
+
+
+ name
+
+ 檔案名稱。
+
+ type
+
+ 代表 content-type。
+
+ abort event
+
+ 放棄已鎖定的檔案,就會發生此事件。
+
+ error event
+
+ 任何內部錯誤,都會發生此事件。
+
+

LockedFile 介面

+
interface LockedFile
+{
+  readonly attribute FileHandle fileHandle;
+  readonly attribute DOMString mode;
+  readonly attribute boolean active;
+  attribute any? location;
+  FileRequest getMetadata(optional FileMetadataParameters parameters);
+  FileRequest readAsArrayBuffer(unsigned long long size);
+  FileRequest readAsText(unsigned long long size, optional DOMString encoding);
+  FileRequest write(DOMString or ArrayBuffer or Blob value);
+  FileRequest append(DOMString or ArrayBuffer or Blob value);
+  FileRequest truncate(optional unsigned long long size);
+  FileRequest flush();
+  void abort();
+  attribute Function? oncomplete;
+  attribute Function? onabort;
+  attribute Function? onerror;
+};
+
+
+ fileHandle
+
+ 來自於解鎖的 FileHandle 物件。
+
+ mode
+
+ 「readonly」或「readwrite」。
+
+ active
+
+ 一旦建立之後,就隨即啟動 LockedFile。此 LockedFile 是「可寫入存取 (Write access) 實際底層檔案」的唯一物件。LockedFile 上的作業,均於 isolation 之中執行;也就是說,只要啟動了 LockedFile,則此 LockedFile 的所有作業都一定會在底層檔案上依序執行,而不會與其他 LockedFiles 的作業交錯執行。
+
+ 若停用了 LockedFile,則只要在同樣的 LockedFile 上執行讀/寫作業,都會丟出錯誤訊息。
+
+
+
+ location
+
+ 檔案中的位置 (Offset)。每次讀/寫作業之後,此數值均將自動變更。讀寫作業均從該 location 開始,而 null 代表檔案末端。
+
+ getMetadata(parameters)
+
+ 針對後設資料 (Metadata) 而回傳 FileRequest。此數亦屬於物件,其中將參數名稱作為物件鍵值,布林值作為數值,進而非同步檢索既有的屬性。無數值則代表 true。目前僅有 sizelastModified 為可能的參數。
+
+ readAsArrayBuffer(size)
+
+ 針對既有 size ArrayBuffer,回傳 FileRequest。此作業均從 location 開始,另根據讀取位元組的數目,移動 location
+
+ readAsText(size [, encoding])
+
+ 針對既有 size 的字串,以既定的 encoding 回傳 FileRequest。此作業均從 location 開始,另根據讀取位元組的數目,移動 locationFileReader API 中的對等函式,也以相同方式運作。 +
var lockedFile = myFile.open();
+var request = lockedFile.readAsText(3);
+request.onsuccess = function(event) {
+  var text = request.result;
+  // 3 characters have been read.
+}
+
+
+
+ write(value)
+
+ 針對成功/失敗的寫入作業,回傳 FileRequest。寫入作業將從 location 開始,另根據寫入位元組的數目,移動位置。 +
var lockedFile = myFile.open("readwrite");
+var request = lockedFile.write("foo");
+request.onsuccess = function(event) {
+  // The string "foo" has been written.
+}
+
+
+
+ append(value)
+
+ 針對成功/失敗的附加 (Append) 作業,回傳 FileRequest。不論 location 為何,該數值均附加於檔案末端。在附加資料完畢後,location 隨即設定為 null
+
+ truncate([size])
+
+ 針對成功/失敗的截斷 (Truncate) 作業,回傳 FileRequest。
+
+ 如果是以單一數呼叫該函式,則截斷成功之後,則不論 location 為何,檔案將剩下第一個 size 的位元組。
+
+ 若沒有用任何數呼叫該函式,則檔案將剩下 location 的第一個位元組。
+
+ flush()
+
+ 強制移轉緩衝過的資料至磁碟上,作業成功之後將回傳 FileRequest。此時即便 App 當機或非刻意中止,都能確保資料已經位於磁碟上了。
+
+ abort()
+
+ 停用 LockedFile 並取消全部尚未執行的作業。
+
+ complete, abort, error events
+
+

FileRequest 介面

+

此類型的物件,均是由 LockedFile 介面的所有非同步作業所回傳。此介面繼承了 DOMRequest 並類似 IDBRequest,同時還擁有 onprogress 事件。在成功之後,則可透過 result 屬性而取得必要檔案作業的結果。

+
interface FileRequest : DOMRequest
+{
+  readonly attribute LockedFile lockedFile;
+  attribute Function? onprogress;
+};
+
+
+  
+
+

說明

+

API 與 FileWriter 的差異?

+

FileWriter 規格定義了 FileWriter,也就是用以呈現「可編輯的檔案」的物件。Public-webapps 討論串則下了結論:若單一檔案同時寫入不同的實體 (Entity),將導致 API 成效不彰。最後就是 FileHandle API 應具備自己的 LockedFile 與交易機制。

+

瀏覽器相容性

+
+ {{CompatibilityTable}}
+
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatNo}}15{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}15{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+

 

diff --git a/files/zh-tw/web/api/filelist/index.html b/files/zh-tw/web/api/filelist/index.html new file mode 100644 index 0000000000..56c2f02235 --- /dev/null +++ b/files/zh-tw/web/api/filelist/index.html @@ -0,0 +1,149 @@ +--- +title: FileList +slug: Web/API/FileList +translation_of: Web/API/FileList +--- +
{{APIRef("File API")}}{{gecko_minversion_header("1.9")}}
+ +

FileList 型別物件通常來自 HTML {{HTMLElement("input")}} 元素 {{domxref("Document_Object_Model", "DOM")}} 物件的 files 屬性({{Glossary("property/JavaScript", "property")}})。你可以操作 FileList 物件來存取使用者透過 <input type="file"> 元素所選取的檔案,或由拖放操作所產生的檔案(請參考 {{domxref("DataTransfer")}} 物件的更多使用細節)。

+ +
+

註:在 {{Gecko("1.9.2")}} 之前,{{HTMLElement("input")}} 元素只支援一次選取一個檔案,這代表了 FileList 只能夠包含一個 File 物件。從 {{Gecko("1.9.2")}} 開始,假如 <input> 元素的 multiple 屬性(attribute)為 true,則 FileList 就可能會包含多個檔案。

+
+ +

使用 FileList

+ +

所有 <input> 元素節點的 {{domxref("Document_Object_Model", "DOM")}} 物件都擁有 files 屬性({{Glossary("property/JavaScript", "property")}}),此屬性即為 FileList,是一個可藉此存取使用者選取之檔案的類陣列物件。以下範例展示了一個 type 屬性({{Glossary("attribute")}})值為 file 的 HTML <input> 元素:

+ +
<input id="fileItem" type="file">
+
+ +

下面範例演示了如何取得 <input> 元素節點中所包含的第一個 {{domxref("File")}} 型別物件:

+ +
var file = document.getElementById('fileItem').files[0];
+
+ +

方法概觀

+ + + + + + + +
File item(index);
+ +

屬性

+ + + + + + + + + + + + + + +
屬性名稱型別描述
lengthinteger表示 FileList 物件中的檔案數量,唯讀。
+ +

方法

+ +

item()

+ +

回傳 FileList 中指定索引的 {{domxref("File")}} 物件。

+ +
File item(
+  index
+);
+
+ +
參數
+ +
+
index
+
要取得的檔案之索引(起始於零)。
+
+ +
回傳值
+ +

要求的 {{domxref("File")}} 物件。

+ +

範例

+ +

此範例演示了迭代所有之使用者於 <input> 元素選取的檔案:

+ +
// fileInput is an HTML input element: <input type="file" id="myfileinput" multiple>
+var fileInput = document.getElementById("myfileinput");
+
+// files is a FileList object (similar to NodeList)
+var files = fileInput.files;
+var file;
+
+// loop through files
+for (var i = 0; i < files.length; i++) {
+
+    // get item
+    file = files.item(i);
+    //or
+    file = files[i];
+
+    alert(file.name);
+}
+
+ +

以下是更完整的範例:

+ +
<!DOCTYPE HTML>
+<html>
+<head>
+</head>
+<body>
+<!--multiple is set to allow multiple files to be selected-->
+
+<input id="myfiles" multiple type="file">
+
+</body>
+
+<script>
+
+var pullfiles=function(){
+    // love the query selector
+    var fileInput = document.querySelector("#myfiles");
+    var files = fileInput.files;
+    // cache files.length
+    var fl = files.length;
+    var i = 0;
+
+    while ( i < fl) {
+        // localize file var in the loop
+        var file = files[i];
+        alert(file.name);
+        i++;
+    }
+}
+
+// set the input element onchange to call pullfiles
+document.querySelector("#myfiles").onchange=pullfiles;
+
+//a.t
+</script>
+
+</html>
+ +

規範

+ + + +

參見

+ + diff --git a/files/zh-tw/web/api/filereader/error/index.html b/files/zh-tw/web/api/filereader/error/index.html new file mode 100644 index 0000000000..572509db9e --- /dev/null +++ b/files/zh-tw/web/api/filereader/error/index.html @@ -0,0 +1,102 @@ +--- +title: FileReader.error +slug: Web/API/FileReader/error +translation_of: Web/API/FileReader/error +--- +
{{APIRef("File API")}}
+ +

總覽

+ +

回傳讀取檔案時發生的錯誤。

+ +

語法

+ +
var error = instanceOfFileReader.error
+
+ +

Value

+ +

A {{domxref("DOMError")}}

+ +

規格

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

瀏覽器相容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureFirefox (Gecko)ChromeEdgeInternet ExplorerOperaSafari
Basic support{{CompatGeckoDesktop("1.9.2")}}[1]7{{CompatVersionUnknown}}10[2]12.02[3]6.0.2
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureFirefox Mobile (Gecko)AndroidEdgeIE MobileOpera MobileSafari Mobile
Basic support323{{CompatVersionUnknown}}1011.56.1
+
+ +

[1] Prior to Gecko 2.0 beta 7 (Firefox 4.0 beta 7), all {{domxref("Blob")}} parameters below were {{domxref("File")}} parameters; this has since been updated to match the specification correctly. Prior to Gecko 13.0 {{geckoRelease("13.0")}} the FileReader.error property returned a {{domxref("FileError")}} object. This interface has been removed and FileReader.error is now returning the {{domxref("DOMError")}} object as defined in the latest FileAPI draft.

+ +

[2] IE9 has a File API Lab.

+ +

[3] Opera has partial support in 11.1.

+ +

閱讀更多

+ + diff --git a/files/zh-tw/web/api/filereader/index.html b/files/zh-tw/web/api/filereader/index.html new file mode 100644 index 0000000000..4b80e334a4 --- /dev/null +++ b/files/zh-tw/web/api/filereader/index.html @@ -0,0 +1,213 @@ +--- +title: FileReader +slug: Web/API/FileReader +tags: + - API + - File API + - Files + - Interface + - Reference +translation_of: Web/API/FileReader +--- +
{{APIRef("File API")}}
+ +

藉由 FileReader 物件,Web 應用程式能以非同步(asynchronously)方式讀取儲存在用戶端的檔案(或原始資料暫存)內容,可以使用 {{domxref("File")}} 或 {{domxref("Blob")}} 物件指定要讀取的資料。

+ +

File 物件可以從使用者於 {{HTMLElement("input")}} 元素選擇之檔案所回傳的 {{domxref("FileList")}} 物件當中取得,或是來自拖放操作所產生的 {{domxref("DataTransfer")}} 物件之中,也能由 {{domxref("HTMLCanvasElement")}} 物件(元素物件)執行 mozGetAsFile() 方法後回傳。

+ +

{{AvailableInWorkers}}

+ +

建構式

+ +
+
{{domxref("FileReader.FileReader", "FileReader()")}}
+
建立新的 FileReader 物件。
+
+ +

請參考在網頁應用程式中使用本地檔案的更多細節與範例。

+ +

屬性

+ +
+
{{domxref("FileReader.error")}} {{readonlyinline}}
+
此 {{domxref("DOMException")}} 類型的物件記錄了讀取資料時發生的錯誤資訊。
+
{{domxref("FileReader.readyState")}} {{readonlyinline}}
+
表示目前 FileReader 狀態的數字,其代表的意義為: + + + + + + + + + + + + + + + + + + +
EMPTY0尚未讀入任何資料。
LOADING1正在讀入資料。
DONE2完成資料讀取。
+
+
{{domxref("FileReader.result")}} {{readonlyinline}}
+
讀入的資料內容。只有在讀取完成之後此屬性才有效,而資料的格式則取決於是由哪一個方法進行讀取。
+
+ +

事件處理器

+ +
+
{{domxref("FileReader.onabort")}}
+
{{event("abort")}} 事件處理器,於讀取被中斷時觸發。
+
{{domxref("FileReader.onerror")}}
+
{{event("error")}} 事件處理器,於讀取發生錯誤時觸發。
+
{{domxref("FileReader.onload")}}
+
{{event("load")}} 事件處理器,於讀取完成時觸發。
+
{{domxref("FileReader.onloadstart")}}
+
{{event("loadstart")}} 事件處理器,於讀取開始時觸發。
+
{{domxref("FileReader.onloadend")}}
+
{{event("loadend")}} 事件處理器,於每一次讀取結束之後觸發(不論成功或失敗),會於 onloadonerror 事件處理器之後才執行。
+
{{domxref("FileReader.onprogress")}}
+
{{event("progress")}} 事件處理器,於讀取 {{domxref("Blob")}} 內容時觸發。
+
+ +
+

FileReader 物件繼承自 {{domxref("EventTarget")}},其所有的事件也都能夠透過 {{domxref("EventTarget.addEventListener()","addEventListener")}} 方法來註冊事件監聽器。

+
+ +

方法

+ +
+
{{domxref("FileReader.abort()")}}
+
中斷目前的讀取,此方法回傳後屬性 readyState 將會是 DONE
+
{{domxref("FileReader.readAsArrayBuffer()")}} {{gecko_minversion_inline("7.0")}}
+
開始讀取指定的 {{domxref("Blob")}},讀取完成後屬性 result 將以 {{domxref("ArrayBuffer")}} 物件來表示讀入的資料內容。
+
{{domxref("FileReader.readAsBinaryString()")}} {{non-standard_inline}}
+
開始讀取指定的 {{domxref("Blob")}},讀取完成後屬性 result 將以字串型式來表示讀入的原始二進位資料(raw binary data)。
+
{{domxref("FileReader.readAsDataURL()")}}
+
開始讀取指定的 {{domxref("Blob")}},讀取完成後屬性 result 將以 data: URL 格式(base64 編碼)的字串來表示讀入的資料內容。
+
{{domxref("FileReader.readAsText()")}}
+
開始讀取指定的 {{domxref("Blob")}},讀取完成後屬性 result 將以文字字串型式來表示讀入的資料內容。
+
+ +

規範

+ + + + + + + + + + + + + + +
規範狀態註解
{{SpecName("File API", "#dfn-filereader", "FileReader")}}{{Spec2("File API")}}Initial definition
+ +

瀏覽器相容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
功能Firefox (Gecko)ChromeEdgeInternet ExplorerOperaSafari
基本支援{{CompatGeckoDesktop("1.9.2")}}[1]7{{CompatVersionUnknown}}10[2]12.02[2]6.0
在 Web Workers 的支援{{CompatGeckoDesktop(46)}}{{CompatVersionUnknown()}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown()}}{{CompatNo}}
error property uses {{domxref("DOMException")}}, not {{domxref("DOMError")}}{{CompatGeckoDesktop(58)}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}{{CompatNo}}{{CompatVersionUnknown()}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
功能Firefox Mobile (Gecko)AndroidEdgeIE MobileOpera MobileSafari Mobile
基本支援323{{CompatVersionUnknown}}1011.56.1
在 Web Workers 的支援{{CompatGeckoMobile(46)}}{{CompatVersionUnknown()}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown()}}{{CompatNo}}
error property uses {{domxref("DOMException")}}, not {{domxref("DOMError")}}{{CompatGeckoMobile(58)}}{{CompatUnknown()}}{{CompatVersionUnknown()}}{{CompatNo}}{{CompatVersionUnknown()}}{{CompatNo}}
+
+ +

[1] 在 Gecko 2.0 beta 7 (Firefox 4.0 beta 7) 以前,所有的 {{domxref("Blob")}} 參數都屬於 {{domxref("File")}} 參數;之後為了更符合規範,所以更新了這個特徵。在 Gecko 13.0 {{geckoRelease("13.0")}} 以前,FileReader.error 屬性回傳了 {{domxref("FileError")}} 物件。這個介面之後被移除、而 FileReader.error 目前會回傳 {{domxref("DOMError")}} 並定義為 FileAPI draft。

+ +

[2] Opera 在 11.1 有限度支援

+ +

參見

+ + diff --git a/files/zh-tw/web/api/filereader/readystate/index.html b/files/zh-tw/web/api/filereader/readystate/index.html new file mode 100644 index 0000000000..f6ff1fa5f6 --- /dev/null +++ b/files/zh-tw/web/api/filereader/readystate/index.html @@ -0,0 +1,98 @@ +--- +title: FileReader.readyState +slug: Web/API/FileReader/readyState +translation_of: Web/API/FileReader/readyState +--- +
{{APIRef("File API")}}
+ +

提供目前讀取狀態

+ +

語法

+ +
var state = instanceOfFileReader.readyState
+
+ +

數值

+ +

數字代表 {{domxref("FileReader")}} API 三個可能的狀態:

+ +

{{page("/en-US/docs/Web/API/FileReader","State constants")}}

+ +

規格

+ + + + + + + + + + + + + + +
規格狀態說明
{{SpecName("File API", "#FileReader-interface", "FileReader")}}{{Spec2("File API")}}初始化定義
+ +

瀏覽器相容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
功能Firefox (Gecko)ChromeInternet ExplorerOperaSafari
基本支援{{CompatGeckoDesktop("1.9.2")}}[1]710[2]12.02[3]6.0.2
+
+ +
+ + + + + + + + + + + + + + + + + + + +
功能Firefox 手機版 (Gecko)AndroidIE 手機版Opera 手機版Safari 手機版
基本支援3231011.56.1
+
+ +

[1] Prior to Gecko 2.0 beta 7 (Firefox 4.0 beta 7), all {{domxref("Blob")}} parameters below were {{domxref("File")}} parameters; this has since been updated to match the specification correctly. Prior to Gecko 13.0 {{geckoRelease("13.0")}} the FileReader.error property returned a {{domxref("FileError")}} object. This interface has been removed and FileReader.error is now returning the {{domxref("DOMError")}} object as defined in the latest FileAPI draft.

+ +

[2] IE9 has a File API Lab.

+ +

[3] Opera has partial support in 11.1.

+ +

閱讀更多

+ + diff --git a/files/zh-tw/web/api/filesystem/index.html b/files/zh-tw/web/api/filesystem/index.html new file mode 100644 index 0000000000..49b4f70b84 --- /dev/null +++ b/files/zh-tw/web/api/filesystem/index.html @@ -0,0 +1,118 @@ +--- +title: FileSystem +slug: Web/API/FileSystem +tags: + - 檔案系統 +translation_of: Web/API/FileSystem +--- +

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

+ +

FileSystem 實作文件和目錄介面,描述一個檔案系統。在任何檔案系統上,這個物件包含 {{domxref("FileSystemEntry.filesystem", "filesystem")}}的特性。某些網頁瀏覽器提供額外的API去創建和管理檔案系統,如Google Chrome的{{domxref("LocalFileSystem.requestFileSystem", "requestFileSystem()")}}函式。

+ +
+

此介面並非標準API, 代表規格並未依造標準制定, 因此必須注意並非所有網頁瀏覽器都有實作此介面, 有實作的網頁瀏覽器可能只有實作一小部分. 請在{{anch("Browser compatibility")}} 查看更多細節.

+
+ +

基礎概念

+ +

存取 FileSystem 物件的兩種方法:

+ +
    +
  1. 你可以直接要求一個使用window.requestFileSystem(),只用在你的網頁應用程式的沙盒類型 FileSystem 物件。如果要求成功,將會執行callback handler去接收描述檔案系統的FileSystem物件參數。
  2. +
  3. 你可以從檔案系統接口物件取得,透過他的{{domxref("FileSystemEntry.filesystem", "filesystem")}}特性
  4. +
+ +

屬性

+ +
+
{{domxref("FileSystem.name")}} {{ReadOnlyInline}}
+
{{domxref("USVString")}} 代表檔案系統的名稱. 此名稱在整個已宣告的檔案系統清單中是唯一的。
+
{{domxref("FileSystem.root")}} {{ReadOnlyInline}}
+
 {{domxref("FileSystemDirectoryEntry")}} 物件表示檔案系統的根目錄。 透過此物件, 你可以取得權限存取所有檔案系統中的文件和目錄
+
+ +

規範

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('File System API')}}{{Spec2('File System API')}}Draft of proposed API
+ +

This API has no official W3C or WHATWG specification.

+ +

瀏覽器相容性

+ +

{{ CompatibilityTable }}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerMicrosoft EdgeOperaSafari (WebKit)
Basic support13{{ property_prefix("webkit") }}{{ CompatGeckoDesktop(50) }}{{ CompatNo }}{{CompatVersionUnknown}}[1]{{ CompatNo }}{{ CompatNo }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{ CompatNo }}0.16{{ property_prefix("webkit") }}{{ CompatGeckoMobile(50) }}{{ CompatNo }}{{ CompatNo }}{{ CompatNo }}
+
+ +

[1] Microsoft Edge 使用 WebKitFileSystem 名稱實作, 且只被用在 drag-and-drop scenarios 透過 {{domxref("DataTransferItem.webkitGetAsEntry()")}} 函式. 此函式不被使用在文件和目錄選擇的面板( 如當你以{{domxref("HTMLInputElement.webkitdirectory")}} 標籤使用 {{HTMLElement("input")}} 物件

+ +

參見

+ + diff --git a/files/zh-tw/web/api/formdata/get/index.html b/files/zh-tw/web/api/formdata/get/index.html new file mode 100644 index 0000000000..b234ecb551 --- /dev/null +++ b/files/zh-tw/web/api/formdata/get/index.html @@ -0,0 +1,145 @@ +--- +title: FormData.get() +slug: Web/API/FormData/get +translation_of: Web/API/FormData/get +--- +

{{APIRef("XMLHttpRequest")}}

+ +

{{domxref("FormData")}} 的  get() 方法會返回 FormData 物件中,指定 key 值所對應之第一組物件中的 value 值 。然而,如果您想要獲得多組以及全部的 value ,那應該使用 {{domxref("FormData.getAll()","getAll()")}} 方法。

+ +

注意:  這個方法已可以在 Web Workers 中使用。

+ +

語法

+ +
formData.get(name);
+ +

參數

+ +
+
name
+
一個 {{domxref("USVString")}} ,代表您想要得到的 value 所對應的 key 值名稱。
+
+ +

回傳值

+ +

A {{domxref("FormDataEntryValue")}} containing the value.

+ +

範例

+ +

下面一行程式會產生一個空的 FormData 物件:

+ +
var formData = new FormData();
+ +

用 {{domxref("FormData.append")}} 方法新增兩組 username 值

+ +
formData.append('username', 'Chris');
+formData.append('username', 'Bob');
+ +

接下來使用 get() 方法,將只會返回上一步驟,第一組新增的 username 所對應的值

+ +
formData.get('username'); // Returns "Chris"
+ +

規範

+ + + + + + + + + + + + + + +
規範狀態註解
{{SpecName('XMLHttpRequest','#dom-formdata-get','get()')}}{{Spec2('XMLHttpRequest')}} 
+ +

瀏覽器相容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(50.0)}}{{CompatGeckoDesktop('39.0')}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}
Available in web workers{{CompatChrome(50.0)}}{{CompatGeckoDesktop('39.0')}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OS (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatChrome(50.0)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}} +

{{CompatVersionUnknown}}

+
{{CompatNo}}{{CompatChrome(50.0)}}
Available in web workers{{CompatNo}}{{CompatChrome(50.0)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatChrome(50.0)}}
+
+ +

 

+ +

延伸閱讀

+ + diff --git a/files/zh-tw/web/api/formdata/index.html b/files/zh-tw/web/api/formdata/index.html new file mode 100644 index 0000000000..4151641a6e --- /dev/null +++ b/files/zh-tw/web/api/formdata/index.html @@ -0,0 +1,218 @@ +--- +title: FormData +slug: Web/API/FormData +translation_of: Web/API/FormData +--- +

{{APIRef("XMLHttpRequest")}}

+ +

FormData 介面可為表單資料中的欄位/值建立相對應的的鍵/值對(key/value)集合,之後便可使用 {{domxref("XMLHttpRequest.send()")}} 方法來送出資料。它在編碼類型設定為 multipart/form-data 時會採用與表單相同的格式送出。

+ +

實作 FormData 的物件可以直接利用 {{jsxref("Statements/for...of", "for...of")}} 語法結構來替代 {{domxref('FormData.entries()', 'entries()')}}:for (var p of myFormData) 等同於 for (var p of myFormData.entries())

+ +
+

備註:此特性適用於 Web Workers

+
+ +

建構式

+ +
+
{{domxref("FormData.FormData","FormData()")}}
+
建立一個新的 FormData 物件。
+
+ +

方法

+ +
+
{{domxref("FormData.append()")}}
+
追加新值到 FormData 物件已有的對應鍵上;若該鍵不存在,則為其追加新的鍵。
+
{{domxref("FormData.delete()")}}
+
刪除指定的鍵值對。
+
{{domxref("FormData.entries()")}}
+
回傳 {{jsxref("Iteration_protocols","iterator")}},可用來處理物件中所有的鍵值對。
+
{{domxref("FormData.get()")}}
+
回傳指定的鍵在 FormData 物件中找到的第一個對應值。
+
{{domxref("FormData.getAll()")}}
+
回傳指定的鍵在 FormData 物件中所有對應值的陣列。
+
{{domxref("FormData.has()")}}
+
回傳 FormData 物件是否含有指定鍵值對的布林值。
+
{{domxref("FormData.keys()")}}
+
回傳 {{jsxref("Iteration_protocols", "iterator")}},可用來處理物件中所有鍵值對之中的鍵。
+
{{domxref("FormData.set()")}}
+
為 FormData 物件已有的鍵設定新值;若該鍵不存在,則為其追加新的鍵。
+
{{domxref("FormData.values()")}}
+
回傳 {{jsxref("Iteration_protocols", "iterator")}},可用來處理物件中所有鍵值對之中的值。
+
+ +

規範

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('XMLHttpRequest','#interface-formdata','FormData')}}{{Spec2('XMLHttpRequest')}}FormData defined in XHR spec
+ +

瀏覽器相容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(7.0)}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("2.0")}}[1]10125
append with filename{{CompatVersionUnknown}}{{CompatNo}}{{CompatGeckoDesktop("22.0")}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
delete(), get(), getAll(), has(), set(){{CompatChrome(50.0)}}{{CompatNo}}{{CompatGeckoDesktop("39.0")}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}
entries(), keys(), values(), and support of for...of{{CompatChrome(50.0)}}{{CompatNo}}{{CompatGeckoDesktop("44.0")}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatNo}}
Available in web workers{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("39.0")}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewEdgeFirefox Mobile (Gecko)Firefox OS (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support3.0[2]{{CompatVersionUnknown}}[2]{{CompatVersionUnknown}}{{CompatGeckoMobile("2.0")}}[1]1.0.1{{CompatUnknown}}12{{CompatUnknown}}{{CompatVersionUnknown}}
append with filename{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatGeckoMobile("22.0")}}1.2{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
delete(), get(), getAll(), has(), set(){{CompatVersionUnknown}}{{CompatChrome(50.0)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatChrome(50.0)}}
entries(), keys(), values(), and support of for...of{{CompatUnknown}}{{CompatChrome(50.0)}}{{CompatNo}}{{CompatGeckoMobile("44.0")}}2.5{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(50.0)}}
Available in web workers{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown}}
+
+ +

[1] 在 Gecko 7.0 {{geckoRelease("7.0")}} 之前,若把 {{domxref("Blob")}} 設定為物件中的值,則 HTTP 標頭中 "Content-Disposition" 的檔案名稱會是空字串,此行為會被某些伺服器視為錯誤。Gecko 7.0 之後則會將檔名設為 "blob" 送出。

+ +

[2] XHR in Android 4.0 sends empty content for FormData with blob.

+ +

參見

+ + diff --git a/files/zh-tw/web/api/formdata/using_formdata_objects/index.html b/files/zh-tw/web/api/formdata/using_formdata_objects/index.html new file mode 100644 index 0000000000..e01b15eb90 --- /dev/null +++ b/files/zh-tw/web/api/formdata/using_formdata_objects/index.html @@ -0,0 +1,137 @@ +--- +title: Using FormData Objects +slug: Web/API/FormData/Using_FormData_Objects +translation_of: Web/API/FormData/Using_FormData_Objects +--- +

The FormData object lets you compile a set of key/value pairs to send using XMLHttpRequest. It is 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 {{domxref("HTMLFormElement.submit","submit()")}} method would use to send the data if the form's encoding type were set to multipart/form-data.

+ +

Creating a FormData object from scratch

+ +

You can build a FormData object yourself, instantiating it then appending fields to it by calling its {{domxref("FormData.append","append()")}} method, like this:

+ +
var formData = new FormData();
+
+formData.append("username", "Groucho");
+formData.append("accountnum", 123456); // number 123456 is immediately converted to a string "123456"
+
+// HTML file input, chosen by user
+formData.append("userfile", fileInputElement.files[0]);
+
+// JavaScript file-like object
+var content = '<a id="a"><b id="b">hey!</b></a>'; // the body of the new file...
+var blob = new Blob([content], { type: "text/xml"});
+
+formData.append("webmasterfile", blob);
+
+var request = new XMLHttpRequest();
+request.open("POST", "http://foo.com/submitform.php");
+request.send(formData);
+
+ +
Note: The fields "userfile" and "webmasterfile" both contain a file. The number assigned to the field "accountnum" is immediately converted into a string by the FormData.append() method (the field's value can be a {{ domxref("Blob") }}, {{ domxref("File") }}, or a string: if the value is neither a Blob nor a File, the value is converted to a string).
+ +

This example builds a FormData instance containing values for fields named "username", "accountnum", "userfile" and "webmasterfile", then uses the XMLHttpRequest method send() to send the form's data. The field "webmasterfile" is a {{domxref("Blob")}}. A Blob object represents a file-like object of immutable, raw data. Blobs represent data that isn't necessarily in a JavaScript-native format. The {{ domxref("File") }} interface is based on Blob, inheriting blob functionality and expanding it to support files on the user's system. In order to build a Blob you can invoke the {{domxref("Blob.Blob","Blob() constructor")}}.

+ +

Retrieving a FormData object from an HTML form

+ +

To construct a FormData object that contains the data from an existing {{ HTMLElement("form") }}, specify that form element when creating the FormData object:

+ +
var formData = new FormData(someFormElement);
+
+ +

For example:

+ +
var formElement = document.querySelector("form");
+var request = new XMLHttpRequest();
+request.open("POST", "submitform.php");
+request.send(new FormData(formElement));
+
+ +

You can also append additional data to the FormData object between retrieving it from a form and sending it, like this:

+ +
var formElement = document.querySelector("form");
+var formData = new FormData(formElement);
+var request = new XMLHttpRequest();
+request.open("POST", "submitform.php");
+formData.append("serialnumber", serialNumber++);
+request.send(formData);
+ +

This lets you augment the form's data before sending it along, to include additional information that's not necessarily user-editable.

+ +

使用 FormData 物件傳送檔案

+ +

You can also send files using FormData. Simply include an {{ HTMLElement("input") }} element of type file in your {{htmlelement("form")}}:

+ +
<form enctype="multipart/form-data" method="post" name="fileinfo">
+  <label>Your email address:</label>
+  <input type="email" autocomplete="on" autofocus name="userid" placeholder="email" required size="32" maxlength="64" /><br />
+  <label>Custom file label:</label>
+  <input type="text" name="filelabel" size="12" maxlength="32" /><br />
+  <label>File to stash:</label>
+  <input type="file" name="file" required />
+  <input type="submit" value="Stash the file!" />
+</form>
+<div></div>
+
+ +

Then you can send it using code like the following:

+ +
var form = document.forms.namedItem("fileinfo");
+form.addEventListener('submit', function(ev) {
+
+  var oOutput = document.querySelector("div"),
+      oData = new FormData(form);
+
+  oData.append("CustomField", "This is some extra data");
+
+  var oReq = new XMLHttpRequest();
+  oReq.open("POST", "stash.php", true);
+  oReq.onload = function(oEvent) {
+    if (oReq.status == 200) {
+      oOutput.innerHTML = "Uploaded!";
+    } else {
+      oOutput.innerHTML = "Error " + oReq.status + " occurred when trying to upload your file.<br \/>";
+    }
+  };
+
+  oReq.send(oData);
+  ev.preventDefault();
+}, false);
+
+ +
+

Note: If you pass in a reference to the form the method specified in the form will be used over the method specified in the open() call.

+
+ +

You can also append a {{ domxref("File") }} or {{ domxref("Blob") }} directly to the {{ domxref("FormData") }} object, like this:

+ +
data.append("myfile", myBlob, "filename.txt");
+
+ +

When using the {{domxref("FormData.append","append()")}} method it is possible to use the third optional parameter to pass a filename inside the Content-Disposition header that is sent to the server. When no filename is specified (or the parameter isn't supported), the name "blob" is used.

+ +

You can also use FormData with jQuery if you set the right options:

+ +
var fd = new FormData(document.querySelector("form"));
+fd.append("CustomField", "This is some extra data");
+$.ajax({
+  url: "stash.php",
+  type: "POST",
+  data: fd,
+  processData: false,  // tell jQuery not to process the data
+  contentType: false   // tell jQuery not to set contentType
+});
+
+ +

Submitting forms and uploading files via AJAX without FormData objects

+ +

If you want to know how to serialize and submit a form via AJAX without using FormData objects, please read this paragraph.

+ +

參見

+ + diff --git a/files/zh-tw/web/api/fullscreen_api/index.html b/files/zh-tw/web/api/fullscreen_api/index.html new file mode 100644 index 0000000000..182f96c922 --- /dev/null +++ b/files/zh-tw/web/api/fullscreen_api/index.html @@ -0,0 +1,240 @@ +--- +title: 使用全螢幕模式 +slug: Web/API/Fullscreen_API +translation_of: Web/API/Fullscreen_API +--- +

{{DefaultAPISidebar("Fullscreen API")}}

+ +

全螢幕 API 提供一個簡便的方式使網頁可以使用佔用使用者的整個螢幕的方式來顯示內容。該 API 讓您能夠容易地指示瀏覽器使某個元素及其子系(如有)佔用整個螢幕,並隱藏螢幕上所有瀏覽器使用者介面及其他應用程式。

+ +
目前並非所有瀏覽器均使用 API 的沒有前綴的版本。請查閱有關前綴以及名稱差異的表格(您也可以使用 Fscreen 來提供跨瀏覽器 API 存取)。
+ +

啟動全螢幕模式

+ +

如果您有一個元素打算以全螢幕模式展示(例如 {{ HTMLElement("video") }}),您可以呼叫該元素之 {{ domxref("Element.requestFullscreen()") }} 方法使之以全螢幕模式顯示。

+ +

考慮此 {{ HTMLElement("video") }} 元素:

+ +
<video controls id="myvideo">
+  <source src="somevideo.webm"></source>
+  <source src="somevideo.mp4"></source>
+</video>
+
+ +

我們可以使用指令碼將此影片全螢幕顯示:

+ +
var elem = document.getElementById("myvideo");
+if (elem.requestFullscreen) {
+  elem.requestFullscreen();
+} else if (elem.msRequestFullscreen) {
+  elem.msRequestFullscreen();
+} else if (elem.mozRequestFullScreen) {
+  elem.mozRequestFullScreen();
+} else if (elem.webkitRequestFullscreen) {
+  elem.webkitRequestFullscreen();
+}
+
+ +

呈現差異

+ +

值得留意的是,Gecko 及 WebKit 的實作有關鍵分別:Gecko 會增加 CSS 規則讓全螢幕的元素展延至填滿整個螢幕:"width: 100%; height: 100%"。WebKit 則不會執行此動作,取而代之的是把該元素置中,並以原先的大小顯示。要取得同樣的全螢幕行為,您需要為該元素自行添加 "width: 100%; height: 100%;" 的 CSS 規則:

+ +
#myvideo:-webkit-full-screen {
+  width: 100%;
+  height: 100%;
+}
+
+ +

另一方面,如果您嘗試在 Gecko 上模擬 WebKit 的行為,您需要把呈現的元素放置在另一個實際調整為全螢幕的元素裡面,再使用 CSS 規則來調整內部元素至您想要的外觀。

+ +

通知

+ +

如果成功進入全螢幕模式,包含該元素的文件將會接收到 {{ event("fullscreenchange") }} 事件。當離開全螢幕模式時,則會收到 {{ event("fullscreenchange") }} 事件。注意 {{ event("fullscreenchange") }} 事件並不提供任何資訊指示進入或離開全螢幕模式,但如果文件的 {{ domxref("document.fullscreenElement", "fullscreenElement") }} 屬性的值不為 null,則表示您正在處於全螢幕模式。

+ +

全螢幕要求失敗

+ +

並不是所有情況下都保證可以進入全螢幕模式。例如,{{ HTMLElement("iframe") }} 元素含有 {{ HTMLAttrXRef("allowfullscreen", "iframe") }} 屬性來選擇是否容許其內容能以全螢幕方式呈現。而且,例如視窗式外掛程式等的某些內容並不可以在全螢幕模式中顯示。把無法呈現為全螢幕的元素設定為全螢幕模式的嘗試都沒有作用,而要求顯示為全螢幕的元素會接收到 mozfullscreenerror 事件。當全螢幕要求失敗時,Firefox 會在網頁主控台上紀錄一則錯誤訊息,解釋要求失敗的原因。但在 Chrome 以及新版的 Opera 上,則不會產生這些錯誤訊息。

+ +
+

注意:全螢幕要求必須在事件處理常式中呼叫,否則將會被拒絕。

+
+ +

離開全螢幕模式

+ +

使用者永遠可以自行離開全螢幕模式,詳見 {{ anch("Things your users want to know") }}。您也可以呼叫 {{domxref("Document.exitFullscreen()")}} 方法來達到相同效果。

+ +

其他資訊

+ +

{{ domxref("document") }} 提供一些附加資訊,對於開發全螢幕網頁應用程式的時候非常有用:

+ +
+
{{ domxref("document.fullscreenElement", "fullscreenElement") }}
+
fullscreenElement 屬性傳回正在顯示為全螢幕模式的 {{ domxref("element") }}。如其為非 null 值,表示文件目前在全螢幕模式。如其為 null,表示文件目前不在全螢幕模式。
+
{{ domxref("document.fullscreenEnabled", "fullscreenEnabled") }}
+
fullscreenEnabled 屬性傳回文件是否容許您要求進入全螢幕訊息。
+
+ +

使用者可能想了解的訊息

+ +

您可能會讓使用者知道他們可以按 ESCF11 鍵來離開全螢幕模式。

+ +

此外,瀏覽其他頁面、切換分頁、或切換到其他應用程式(例如按 鍵)亦會離開全螢幕模式。

+ +

範例

+ +

In this example, a video is presented in a web page. Pressing the Return or Enter key lets the user toggle between windowed and fullscreen presentation of the video.

+ +

查看示例

+ +

監視 Enter 鍵

+ +

When the page is loaded, this code is run to set up an event listener to watch for the 'enter' key.

+ +
document.addEventListener("keydown", function(e) {
+  if (e.keyCode == 13) {
+    toggleFullScreen();
+  }
+}, false);
+
+ +

Toggling fullscreen mode

+ +

This code is called when the user hits the Enter key, as seen above.

+ +
function toggleFullScreen() {
+  if (!document.fullscreenElement &&    // alternative standard method
+      !document.mozFullScreenElement && !document.webkitFullscreenElement && !document.msFullscreenElement ) {  // current working methods
+    if (document.documentElement.requestFullscreen) {
+      document.documentElement.requestFullscreen();
+    } else if (document.documentElement.msRequestFullscreen) {
+      document.documentElement.msRequestFullscreen();
+    } else if (document.documentElement.mozRequestFullScreen) {
+      document.documentElement.mozRequestFullScreen();
+    } else if (document.documentElement.webkitRequestFullscreen) {
+      document.documentElement.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
+    }
+  } else {
+    if (document.exitFullscreen) {
+      document.exitFullscreen();
+    } else if (document.msExitFullscreen) {
+      document.msExitFullscreen();
+    } else if (document.mozCancelFullScreen) {
+      document.mozCancelFullScreen();
+    } else if (document.webkitExitFullscreen) {
+      document.webkitExitFullscreen();
+    }
+  }
+}
+
+ +

This starts by looking at the value of the fullscreenElement attribute on the {{ domxref("document") }} (checking it prefixed with both moz, ms, and webkit). If it's null, the document is currently in windowed mode, so we need to switch to fullscreen mode. Switching to fullscreen mode is done by calling either {{ domxref("element.mozRequestFullScreen()") }} msRequestFullscreen()or webkitRequestFullscreen(), depending on which is available.

+ +

If fullscreen mode is already active (fullscreenElement is non-null), we call {{ domxref("document.mozCancelFullScreen()") }}, msExitFullscreen or webkitExitFullscreen(), again depending on which browser is in use.

+ +

瀏覽器兼容性

+ +

Although  Gecko , Trident, and WebKit implement a draft of this API, there are some subtle differences. This document doesn't necessarily try to call them all into focus. The article will be revised as the spec and implementations fall closer into alignment with one another.

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support15 {{ property_prefix("-webkit") }}{{ CompatGeckoDesktop("9.0") }} {{ property_prefix("-moz") }}11 {{ property_prefix("-ms") }}12.105.0 {{ property_prefix("-webkit") }}
fullscreenEnabled20 {{ property_prefix("-webkit") }}{{ CompatGeckoDesktop("10.0") }} {{ property_prefix("-moz") }}11 {{ property_prefix("-ms") }}12.105.1 {{ property_prefix("-webkit") }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChromeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}28 {{ property_prefix("-webkit") }}{{ CompatGeckoMobile("9.0") }}{{ property_prefix("-moz") }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
fullscreenEnabled{{ CompatUnknown() }}28 {{ property_prefix("-webkit") }}{{ CompatGeckoMobile("10.0") }} {{ property_prefix("moz") }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

Gecko notes

+ +

Although this API was introduced in Gecko 9.0 {{ geckoRelease("9.0") }}, it's not enabled by default in that release. To enable it, set the full-screen-api.enabled preference to true. The API is enabled by default in Gecko 10.0 {{ geckoRelease("10.0") }}. In Gecko all the API is spelt "fullScreen".

+ +

規範

+ +

Fullscreen API

+ +

非標準方法

+ +

These are some of the methods that browsers implemented before the standard was drafted. Having the standard methods described above it's better to avoid using the following ones:

+ + + +

參見

+ + + + diff --git a/files/zh-tw/web/api/gainnode/gain/index.html b/files/zh-tw/web/api/gainnode/gain/index.html new file mode 100644 index 0000000000..895a356e25 --- /dev/null +++ b/files/zh-tw/web/api/gainnode/gain/index.html @@ -0,0 +1,113 @@ +--- +title: GainNode.gain +slug: Web/API/GainNode/gain +tags: + - API +translation_of: Web/API/GainNode/gain +--- +

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

+ +
+

{{ domxref("GainNode") }} 介面的 gain 屬性是 a-rate {{domxref("AudioParam")}},代表增益的數值。

+
+ +

語法

+ +
var audioCtx = new AudioContext();
+var gainNode = audioCtx.createGain();
+gainNode.gain.value = 0.5;
+
+ +

傳回值

+ +

一個 {{domxref("AudioParam")}}.

+ +
+

註: 雖然傳回的 AudioParam 是唯讀的,但是它所代表的值可以更改。

+
+ +

範例

+ +

{{page("/en-US/docs/Web/API/AudioContext.createGain","Example")}}

+ +

規格

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-GainNode-gain', 'gain')}}{{Spec2('Web Audio API')}} 
+ +

瀏覽器相容度

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

參見

+ + diff --git a/files/zh-tw/web/api/gainnode/index.html b/files/zh-tw/web/api/gainnode/index.html new file mode 100644 index 0000000000..1d52092799 --- /dev/null +++ b/files/zh-tw/web/api/gainnode/index.html @@ -0,0 +1,168 @@ +--- +title: GainNode +slug: Web/API/GainNode +translation_of: Web/API/GainNode +--- +

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

+ +
+

GainNode 介面代表的是音量改變。 這是 {{domxref("AudioNode")}} 音訊處理模組,可以對輸入的訊號做增益 (gain) 後輸出。一個 GainNode 有一個輸入和一個輸出,兩者有相同的聲道數。

+
+ +

增益 (gain) 是無單位的數值,隨時間變化,會用來和所有輸入聲道的取樣做相乘。 如果更改的話,新的增益會用 de-zippering 演算法處理,以避免輸出聲音出現難聽的「喀」聲。

+ +

The GainNode is increasing the gain of the output.

+ + + + + + + + + + + + + + + + + + + + + + + + +
Number of inputs1
Number of outputs1
Channel count mode"max"
Channel count2 (not used in the default count mode)
Channel interpretation"speakers"
+ +

Constructor

+ +
+
{{domxref("GainNode.GainNode", "GainNode()")}}
+
Creates a new instance of an GainNode object.
+
+ +

Properties

+ +

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

+ +
+
{{domxref("GainNode.gain")}} {{readonlyinline}}
+
a-rate {{domxref("AudioParam")}} ,代表增益值
+
+ +

Methods

+ +

No specific method; inherits methods from its parent, {{domxref("AudioNode")}}.

+ +

Example

+ +

{{page("/en-US/docs/Web/API/AudioContext.createGain","Example")}}

+ +

Specifications

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

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(10.0)}}{{property_prefix("webkit")}}{{CompatVersionUnknown}}{{CompatGeckoDesktop(25.0)}} {{CompatNo}}{{CompatOpera(15)}}{{property_prefix("webkit")}}
+ {{CompatOpera(22)}}
6.0{{property_prefix("webkit")}}
constructor{{CompatChrome(55.0)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOpera(42)}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewEdgeFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}26.01.2{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatChrome(33.0)}}
constructor{{CompatNo}}{{CompatChrome(55.0)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOpera(42)}}{{CompatUnknown}}{{CompatChrome(55.0)}}
+
+ +

See also

+ + diff --git a/files/zh-tw/web/api/geolocation/clearwatch/index.html b/files/zh-tw/web/api/geolocation/clearwatch/index.html new file mode 100644 index 0000000000..c1d2979db2 --- /dev/null +++ b/files/zh-tw/web/api/geolocation/clearwatch/index.html @@ -0,0 +1,132 @@ +--- +title: Geolocation.clearWatch() +slug: Web/API/Geolocation/clearWatch +translation_of: Web/API/Geolocation/clearWatch +--- +

{{ APIref("Geolocation API") }}

+ +

Geolocation.clearWatch() 這個函式是用來取消   {{domxref("Geolocation.watchPosition()")}} 註冊的函式。

+ +

語法

+ +
navigator.geolocation.clearWatch(id);
+ +

參數

+ +
+
編號(id)
+
這個編號(ID) 是由 {{domxref("Geolocation.watchPosition()")}} 這個函式所回傳,當你不再需要收到位置更新時,你可以用此編號,取消 {{domxref("Geolocation.watchPosition()")}} 的註冊。
+
+ +

範例

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

規格

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Geolocation')}}{{Spec2('Geolocation')}}Initial specification.
+ +

瀏覽器的相容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support5{{CompatGeckoDesktop("1.9.1")}}910.60
+ Removed in 15.0
+ Reintroduced in 16.0
5
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown()}}{{CompatUnknown()}}{{CompatGeckoMobile("4")}}{{CompatUnknown()}}10.60{{CompatUnknown()}}
+
+ +

請參考

+ + diff --git a/files/zh-tw/web/api/geolocation/getcurrentposition/index.html b/files/zh-tw/web/api/geolocation/getcurrentposition/index.html new file mode 100644 index 0000000000..78c26d3e8e --- /dev/null +++ b/files/zh-tw/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") }}

+ +

Geolocation.getCurrentPosition() 方法用來獲取設備當前的位置。

+ +

語法

+ +
navigator.geolocation.getCurrentPosition(success[, error[, options]])
+ +

參數

+ +
+
success
+
一個回呼函式(callback function) 會被傳入一個{{domxref("Position")}} 的物件。
+
error {{optional_inline}}
+
一個選擇性的錯誤回呼函式(callback function),會被傳入一個 {{domxref("PositionError")}} 的物件。
+
options {{optional_inline}}
+
一個選擇性的 {{domxref("PositionOptions")}} 的物件。
+
+ +

範例

+ +
var options = {
+  enableHighAccuracy: true,
+  timeout: 5000,
+  maximumAge: 0
+};
+
+function success(pos) {
+  var crd = pos.coords;
+
+  console.log('Your current position is:');
+  console.log('Latitude : ' + crd.latitude);
+  console.log('Longitude: ' + crd.longitude);
+  console.log('More or less ' + crd.accuracy + ' meters.');
+};
+
+function error(err) {
+  console.warn('ERROR(' + err.code + '): ' + err.message);
+};
+
+navigator.geolocation.getCurrentPosition(success, error, options);
+
+ +

規格

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Geolocation')}}{{Spec2('Geolocation')}}Initial specification.
+ +

瀏覽器的相容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support5{{CompatGeckoDesktop("1.9.1")}}910.60
+ Removed in 15.0
+ Reintroduced in 16.0
5
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown()}}{{CompatUnknown()}}{{CompatGeckoMobile("4")}}{{CompatUnknown()}}10.60{{CompatUnknown()}}
+
+ +

請參考

+ + diff --git a/files/zh-tw/web/api/geolocation/index.html b/files/zh-tw/web/api/geolocation/index.html new file mode 100644 index 0000000000..3dda732dbf --- /dev/null +++ b/files/zh-tw/web/api/geolocation/index.html @@ -0,0 +1,118 @@ +--- +title: Geolocation +slug: Web/API/Geolocation +tags: + - API + - Advanced + - Geolocation API + - Interface + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/API/Geolocation +--- +
{{APIRef("Geolocation API")}}
+ +

Geolocation 介面代表一個物件可以透過你的網頁程式去獲得你的裝置位置。這個介面提供了網站或應用程式根據使用者的位置去客製化呈現的內容。

+ +

{{domxref("Navigator")}} 此物件實作了 {{domxref("Navigator.geolocation")}} 介面。

+ +
+

備註: 因為隱私的因素,當網頁要求存取位置資訊時,用戶會被提示通知並且詢問授權與否。注意不同的瀏覽器在詢問授權時有各自不同的策略和方式。

+
+ +

性質

+ +

Geolocation 介面沒有繼承也沒有時做任何方法

+ +

方法

+ +

Geolocation 介面沒有繼承任何方法

+ +
+
{{domxref("Geolocation.getCurrentPosition()")}}
+
取得裝置當前位置,並回傳{{domxref("Position")}}。
+
{{domxref("Geolocation.watchPosition()")}}
+
返回一個長整數,註冊一個回呼函數。這個方法是用來註冊一個處理的函式,當使用者的裝置位置更新時,這個函式所傳入的回呼函式(callback function) 就會自動被呼叫。
+
{{domxref("Geolocation.clearWatch()")}}
+
移除指定註冊的 watchPosition()
+
+ +

規格

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Geolocation')}}{{Spec2('Geolocation')}}Initial specification.
+ +

瀏覽器相容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support5{{CompatGeckoDesktop("1.9.1")}}910.60
+ Removed in 15.0
+ Reintroduced in 16.0
5
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown()}}{{CompatUnknown()}}{{CompatGeckoMobile("4")}}{{CompatUnknown()}}10.60{{CompatUnknown()}}
+
+ +

請參考

+ + diff --git a/files/zh-tw/web/api/geolocation/using_geolocation/index.html b/files/zh-tw/web/api/geolocation/using_geolocation/index.html new file mode 100644 index 0000000000..cdc56770c4 --- /dev/null +++ b/files/zh-tw/web/api/geolocation/using_geolocation/index.html @@ -0,0 +1,251 @@ +--- +title: 地理位置定位 (Geolocation) +slug: Web/API/Geolocation/Using_geolocation +translation_of: Web/API/Geolocation_API +--- +

Web Apps 若需要使用者的位置,可透過 Geolocation API 取得相關資訊。而基於隱私權的考量,這些 Web Apps 均必須取得使用者的許可之後,才能發佈位置資訊。

+ +

地理位置定位 (Geolocation) 物件

+ +

Geolocation API,是透過 navigator.geolocation 物件所發佈。

+ +

若該物件可用,即可進行地理位置定位服務。因此可先測試地理位置定位是否存在:

+ +
if ("geolocation" in navigator) {
+  /* geolocation is available */
+} else {
+  /* geolocation IS NOT available */
+}
+
+ +
注意:在 Firefox 24 之後的版本,即使停用此 API,navigator 中的「geolocation」也同樣回傳 true。此問題已根據規格而於 Firefox 25 中修正 (bug 884921)。
+ +

取得目前位置

+ +

若要取得使用者目前的位置,可呼叫 getCurrentPosition() 函式。如此將啟動非同步化的請求,以偵測使用者的位置,並將查詢定位硬體而取得最新資訊。一旦決定位置,隨即執行特定的回呼常式 (Callback routine)。若發生錯誤,則可選擇是否提供第二次回呼。第三項參數為選項介面 (亦可選擇是否使用之),可設定位置回傳的的最長時間,與請求的等待時間。
+ 若不論定位精確度而想儘快固定單一位置,則可使用 getCurrentPosition()。以具備 GPS 的裝置為例,往往需耗時 1 分鐘或更長的時間而固定 GPS 資訊。也因此,getCurrentPosition() 可能取得較低精確度的資料 (IP 位置或 WiFi) 而隨即開始作業。

+ +
+

注意:依預設值,getCurrentPosition() 將儘快回傳較低精確度的結果。若不論精確度而只要儘快獲得答案,則可使用 getCurrentPosition()。舉例來說,搭載 GPS 的裝置可能需要一段時間才能取得 GPS 定位資訊,所以可能將低精確度的資料 (IP 位置或 Wifi) 回傳至 getCurrentPosition()

+
+ +
navigator.geolocation.getCurrentPosition(function(position) {
+  do_something(position.coords.latitude, position.coords.longitude);
+});
+ +

一旦取得定位位置之後,上列範例隨即將執行 do_something() 函式。

+ +

觀看目前位置

+ +

如果定位資料改變 (可能是裝置移動,或取得更精確的地理位置資訊),則可設定 1 組回呼函式,使其隨著更新過的定位資訊而呼叫之。而這個動作可透過 watchPosition() 函式完成。watchPosition() 所具備的輸入參數與 getCurrentPosition() 相同。回呼函式將呼叫數次,讓瀏覽器可於使用者移動期間更新位置,或可根據目前所使用的不同定位技術,提供更精確的定位資訊。若一直未回傳有效結果,則錯誤回呼 (Error Callback) 函式僅將呼叫 1 次。另請注意,錯誤回呼函式僅限於 getCurrentPosition(),因此為選填

+ +
+

注意:不需啟動 getCurrentPosition() 呼叫,亦可使用 watchPosition()

+
+ +
var watchID = navigator.geolocation.watchPosition(function(position) {
+  do_something(position.coords.latitude, position.coords.longitude);
+}
+);
+ +

watchPosition() 函式將回傳 1 組 ID 編號,專用以識別必要的定位監看員 (Watcher)。而此數值若搭配 clearWatch() 函式,即可停止觀看使用者的位置。

+ +
navigator.geolocation.clearWatch(watchID);
+
+ +

微調回應

+ +

getCurrentPosition()watchPosition() 均可容納 1 組成功回呼、1 組錯誤回呼 (選填)、1 組 PositionOptions 物件 (選填)。

+ +

watchPosition 的呼叫應類似如下:

+ +
function geo_success(position) {
+  do_something(position.coords.latitude, position.coords.longitude);
+}
+
+function geo_error() {
+  alert("Sorry, no position available.");
+}
+
+var geo_options = {
+  enableHighAccuracy: true,
+  maximumAge        : 30000,
+  timeout           : 27000
+};
+
+var wpid = navigator.geolocation.watchPosition(geo_success, geo_error, geo_options);
+ +

現成的 watchPosition Demo:http://www.thedotproduct.org/experiments/geo/
+ 

+ +

敘述位置

+ +

Position 物件參照 Coordinates 物件,即可敘述使用者的位置。

+ +

處理錯誤

+ +

在呼叫 getCurrentPosition()watchPosition() 時,若獲得錯誤回呼函式,則錯誤回呼函式的第一組參數將為 PositionError 物件:

+ +
function errorCallback(error) {  alert('ERROR(' + error.code + '): ' + error.message);};
+
+ +

地理位置定位實際範例

+ +

HTML 內容

+ +
<p><button onclick="geoFindMe()">Show my location</button></p>
+<div id="out"></div>
+ +

JavaScript 內容

+ +
function geoFindMe() {
+  var output = document.getElementById("out");
+
+  if (!navigator.geolocation){
+    output.innerHTML = "<p>Geolocation is not supported by your browser</p>";
+    return;
+  }
+
+  function success(position) {
+    var latitude  = position.coords.latitude;
+    var longitude = position.coords.longitude;
+
+    output.innerHTML = '<p>Latitude is ' + latitude + '° <br>Longitude is ' + longitude + '°</p>';
+
+    var img = new Image();
+    img.src = "http://maps.googleapis.com/maps/api/staticmap?center=" + latitude + "," + longitude + "&zoom=13&size=300x300&sensor=false";
+
+    output.appendChild(img);
+  };
+
+  function error() {
+    output.innerHTML = "Unable to retrieve your location";
+  };
+
+  output.innerHTML = "<p>Locating…</p>";
+
+  navigator.geolocation.getCurrentPosition(success, error);
+}
+
+ +

現場測試結果

+ +

若無法顯示,可至本文右上角「Language」切換回英文原文觀看。

+ + +

{{EmbedLiveSample('Examples', 350, 150, "", "", "", "geolocation")}}

+ + +

請求權限

+ +

addons.mozilla.org 上所提供的任何附加元件,只要使用地理位置定位資料,均必須明確取得許可才能繼續作業。下列函式詢問許可的方法,則類似網頁詢問許可的自動提示方法,但更為簡單。若為可套用的狀態,則使用者的回應將儲存於 pref 參數所指定的偏好中。於 callback 參數中所提供的函式,將透過 1 組代表使用者反應的布林值而呼叫之。若使用者的回應為 true,則附加元件才會存取地理位置定位資料。

+ +
function prompt(window, pref, message, callback) {
+    let branch = Components.classes["@mozilla.org/preferences-service;1"]
+                           .getService(Components.interfaces.nsIPrefBranch);
+
+    if (branch.getPrefType(pref) === branch.PREF_STRING) {
+        switch (branch.getCharPref(pref)) {
+        case "always":
+            return callback(true);
+        case "never":
+            return callback(false);
+        }
+    }
+
+    let done = false;
+
+    function remember(value, result) {
+        return function() {
+            done = true;
+            branch.setCharPref(pref, value);
+            callback(result);
+        }
+    }
+
+    let self = window.PopupNotifications.show(
+        window.gBrowser.selectedBrowser,
+        "geolocation",
+        message,
+        "geo-notification-icon",
+        {
+            label: "Share Location",
+            accessKey: "S",
+            callback: function(notification) {
+                done = true;
+                callback(true);
+            }
+        }, [
+            {
+                label: "Always Share",
+                accessKey: "A",
+                callback: remember("always", true)
+            },
+            {
+                label: "Never Share",
+                accessKey: "N",
+                callback: remember("never", false)
+            }
+        ], {
+            eventCallback: function(event) {
+                if (event === "dismissed") {
+                    if (!done) callback(false);
+                    done = true;
+                    window.PopupNotifications.remove(self);
+                }
+            },
+            persistWhileVisible: true
+        });
+}
+
+prompt(window,
+       "extensions.foo-addon.allowGeolocation",
+       "Foo Add-on wants to know your location.",
+       function callback(allowed) { alert(allowed); });
+
+ +

瀏覽器相容性

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
瀏覽器基本支援Geolocation Level 2
Internet ExplorerIE9 RC---
Firefox (Gecko)3.5 (1.9.1)---
Opera10.60---
Safari | Chrome | WebKit5 | 5 | 533---
+ +

Gecko 註記

+ +

Firefox 可透過 Google 的定位服務 (Google Location Services,GLS),根據使用者的 WiFi 資訊而找出使用者的位置。與 Google 之間所交換的資料,包含 WiFi 存取點 (Access Point) 資料、Access token (類似 2 個禮拜的 cookie)、使用者的 IP 位址。若需更多資訊,可參閱 Mozilla 的隱私權政策Google 的隱私權政策。其內將詳述資料的使用方式。

+ +

Firefox 3.6 (Gecko 1.9.2) 新支援了 GPSD (GPS daemon) 服務,適合 Linux 的地理位置定位。

+ +

另請參閱

+ + diff --git a/files/zh-tw/web/api/geolocation/watchposition/index.html b/files/zh-tw/web/api/geolocation/watchposition/index.html new file mode 100644 index 0000000000..fc5109f1f5 --- /dev/null +++ b/files/zh-tw/web/api/geolocation/watchposition/index.html @@ -0,0 +1,143 @@ +--- +title: Geolocation.watchPosition() +slug: Web/API/Geolocation/watchPosition +translation_of: Web/API/Geolocation/watchPosition +--- +

{{ APIref("Geolocation API") }}

+ +

Geolocation.watchPosition() 這個方法是用來註冊一個處理的函式,當使用者的裝置位置更新時,這個函式所傳入的回呼函式(callback function) 就會自動被呼叫。你也可以選擇性的定義錯誤時哪些錯誤回呼函式(error callback function) 需要被呼叫。

+ +

這個函式將回傳一組 ID 編號,此編號搭配 {{domxref("Geolocation.clearWatch()")}} 函式,即可停止更新使用者的位置。

+ +

語法

+ +
id = navigator.geolocation.watchPosition(success[, error[, options]])
+ +

參數

+ +
+
success
+
一個回呼函式(callback function) 會被傳入一個 {{domxref("Position")}} 的物件。
+
error {{optional_inline}}
+
一個選擇性的錯誤回呼函式(callback function),會被傳入一個{{domxref("PositionError")}} 的物件。
+
options {{optional_inline}}
+
一個選擇性 {{domxref("PositionOptions")}} 的物件。
+
+ +

範例

+ +
var id, target, options;
+
+function success(pos) {
+  var crd = pos.coords;
+
+  if (target.latitude === crd.latitude && target.longitude === crd.longitude) {
+    console.log('Congratulations, you reached 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);
+
+ +

備註

+ +

如果你的應用程式是跑在 firefox OS上,請參考 geolocation wake lock,此方法可以讓你的程式在背景或螢幕關上時也能持續收到位置更新。

+ +

規格

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Geolocation', '#watch-position', 'Geolocation.watchPosition()')}}{{Spec2('Geolocation')}}Initial specification.
+ +

瀏覽器的相容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support5{{CompatGeckoDesktop("1.9.1")}}910.60
+ Removed in 15.0
+ Reintroduced in 16.0
5
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown()}}{{CompatUnknown()}}{{CompatGeckoMobile("4")}}{{CompatUnknown()}}10.60{{CompatUnknown()}}
+
+ +

請參考

+ + diff --git a/files/zh-tw/web/api/geolocationcoordinates/accuracy/index.html b/files/zh-tw/web/api/geolocationcoordinates/accuracy/index.html new file mode 100644 index 0000000000..4670394148 --- /dev/null +++ b/files/zh-tw/web/api/geolocationcoordinates/accuracy/index.html @@ -0,0 +1,93 @@ +--- +title: Coordinates.accuracy +slug: Web/API/GeolocationCoordinates/accuracy +translation_of: Web/API/GeolocationCoordinates/accuracy +--- +
{{APIRef("Geolocation API")}}
+ +

Coordinates.accuracy 是個唯讀的正複數用來代表 {{domxref("Coordinates.latitude")}} 和 {{domxref("Coordinates.longitude")}} 的準確度,單位為公尺,並有 95% 可靠度。

+ +

語法

+ +
acc = coordinates.accuracy
+
+ +

規格

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Geolocation', '#accuracy', 'Coordinates.accuracy')}}{{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}}
+
+ +

請參考

+ + diff --git a/files/zh-tw/web/api/geolocationcoordinates/altitude/index.html b/files/zh-tw/web/api/geolocationcoordinates/altitude/index.html new file mode 100644 index 0000000000..a9e2141793 --- /dev/null +++ b/files/zh-tw/web/api/geolocationcoordinates/altitude/index.html @@ -0,0 +1,93 @@ +--- +title: Coordinates.altitude +slug: Web/API/GeolocationCoordinates/altitude +translation_of: Web/API/GeolocationCoordinates/altitude +--- +
{{APIRef("Geolocation API")}}
+ +

Coordinates.altitude 是個唯讀的正複數用來代表距離海平面的高度,單位為公尺。如果無法提供這個值則回傳 null。

+ +

語法

+ +
alt = coordinates.altitude
+
+ +

規格

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Geolocation', '#altitude', 'Coordinates.altitude')}}{{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}}
+
+ +

請參考

+ + diff --git a/files/zh-tw/web/api/geolocationcoordinates/altitudeaccuracy/index.html b/files/zh-tw/web/api/geolocationcoordinates/altitudeaccuracy/index.html new file mode 100644 index 0000000000..e0ad663ba0 --- /dev/null +++ b/files/zh-tw/web/api/geolocationcoordinates/altitudeaccuracy/index.html @@ -0,0 +1,93 @@ +--- +title: Coordinates.altitudeAccuracy +slug: Web/API/GeolocationCoordinates/altitudeAccuracy +translation_of: Web/API/GeolocationCoordinates/altitudeAccuracy +--- +
{{APIRef("Geolocation API")}}
+ +

Coordinates.altitudeAccuracy 是個唯讀的正複數用來代表高度的精準度,單位為公尺,並有 95% 可靠度。如果裝置無法提供這個值則回傳 null。

+ +

語法

+ +
altAcc = coordinates.altitudeAccuracy
+
+ +

規格

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Geolocation', '#altitudeaccuracy', 'Coordinates.altitudeAccuracy')}}{{Spec2('Geolocation')}}Initial specification.
+ +

瀏覽器的相容性

+ +

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

請參考

+ + diff --git a/files/zh-tw/web/api/geolocationcoordinates/heading/index.html b/files/zh-tw/web/api/geolocationcoordinates/heading/index.html new file mode 100644 index 0000000000..be762eb369 --- /dev/null +++ b/files/zh-tw/web/api/geolocationcoordinates/heading/index.html @@ -0,0 +1,93 @@ +--- +title: Coordinates.heading +slug: Web/API/GeolocationCoordinates/heading +translation_of: Web/API/GeolocationCoordinates/heading +--- +
{{APIRef("Geolocation API")}}
+ +

Coordinates.heading 是個唯讀的正複數用來代表裝置前進的方向。這個數值代表你偏離北方多少度,0度代表你向著正北方,照著順時針的方向遞增(90度代表正東方,270度代表正西方)。如果{{domxref("Coordinates.speed")}} 為0度,則此值為 NaN。如果這個裝置無法提供這個值則回傳 null。

+ +

語法

+ +
heading = coordinates.heading
+
+ +

規格

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Geolocation', '#heading', 'Coordinates.heading')}}{{Spec2('Geolocation')}}Initial specification.
+ +

瀏覽器的相容性

+ +

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

請參考

+ + diff --git a/files/zh-tw/web/api/geolocationcoordinates/index.html b/files/zh-tw/web/api/geolocationcoordinates/index.html new file mode 100644 index 0000000000..08be554dff --- /dev/null +++ b/files/zh-tw/web/api/geolocationcoordinates/index.html @@ -0,0 +1,113 @@ +--- +title: Coordinates +slug: Web/API/GeolocationCoordinates +translation_of: Web/API/GeolocationCoordinates +--- +
{{APIRef("Geolocation API")}}
+ +

Coordinates 這個介面用來存取裝置的經緯度,速度以及這些數值的準確度。

+ +

屬性

+ +

Coordinates 這個介面沒有繼承任何屬性

+ +
+
{{domxref("Coordinates.latitude")}} {{readonlyInline}}
+
回傳一個十進位的 double 代表緯度。
+
{{domxref("Coordinates.longitude")}} {{readonlyInline}}
+
回傳一個十進位的 double 代表經度。
+
{{domxref("Coordinates.altitude")}} {{readonlyInline}}
+
回傳一個 double 代表距離海平面的高度,單位為公尺。如果無法提供這個值則回傳 null。
+
{{domxref("Coordinates.accuracy")}} {{readonlyInline}}
+
回傳一個 double 代表經緯度的精準值,單位為公尺。
+
{{domxref("Coordinates.altitudeAccuracy")}} {{readonlyInline}}
+
回傳一個 double 代表高度的精準度,單位為公尺。如果無法提供這個值則回傳 null。
+
{{domxref("Coordinates.heading")}} {{readonlyInline}}
+
回傳一個 double 代表裝置前進的方向,這個數值代表你偏離北方多少度,0度代表你向著正北方,照著順時針的方向遞增(90度代表正東方,270度代表正西方) 。如果速度值為0度,則此值為 NaN。如果無法提供這個值則回傳 null。
+
{{domxref("Coordinates.speed")}} {{readonlyInline}}
+
回傳一個 double 代表速度,單位為公尺/秒。如果無法提供這個值則回傳 null。
+
+ +

方法

+ +

Coordinates 這個介面,沒有實作也沒有繼承自任何的方法。

+ +

規格

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Geolocation', '#coordinates', 'Coordinates')}}{{Spec2('Geolocation')}}Initial specification.
+ +

瀏覽器的相容性

+ +

{{ 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()}}
+
+ +

請參考

+ + diff --git a/files/zh-tw/web/api/geolocationcoordinates/latitude/index.html b/files/zh-tw/web/api/geolocationcoordinates/latitude/index.html new file mode 100644 index 0000000000..18c43451f2 --- /dev/null +++ b/files/zh-tw/web/api/geolocationcoordinates/latitude/index.html @@ -0,0 +1,93 @@ +--- +title: Coordinates.latitude +slug: Web/API/GeolocationCoordinates/latitude +translation_of: Web/API/GeolocationCoordinates/latitude +--- +
{{APIRef("Geolocation API")}}
+ +

Coordinates.latitude 是個唯讀十進位的複數用來代表裝置緯度的位置。

+ +

語法

+ +
lat = coordinates.latitude
+
+ +

規格

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Geolocation', '#lat', 'Coordinates.latitude')}}{{Spec2('Geolocation')}}Initial specification.
+ +

瀏覽器的相容性

+ +

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

請參考

+ + diff --git a/files/zh-tw/web/api/geolocationcoordinates/longitude/index.html b/files/zh-tw/web/api/geolocationcoordinates/longitude/index.html new file mode 100644 index 0000000000..f5625d20c6 --- /dev/null +++ b/files/zh-tw/web/api/geolocationcoordinates/longitude/index.html @@ -0,0 +1,93 @@ +--- +title: Coordinates.longitude +slug: Web/API/GeolocationCoordinates/longitude +translation_of: Web/API/GeolocationCoordinates/longitude +--- +
{{APIRef("Geolocation API")}}
+ +

Coordinates.longitude 是個唯讀十進位的複數用來代表裝置經度的位置。

+ +

語法

+ +
lon = coordinates.longitude
+
+ +

規格

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Geolocation', '#lon', 'Coordinates.longitude')}}{{Spec2('Geolocation')}}Initial specification.
+ +

瀏覽器的相容性

+ +

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

請參考

+ + diff --git a/files/zh-tw/web/api/geolocationcoordinates/speed/index.html b/files/zh-tw/web/api/geolocationcoordinates/speed/index.html new file mode 100644 index 0000000000..74c1940232 --- /dev/null +++ b/files/zh-tw/web/api/geolocationcoordinates/speed/index.html @@ -0,0 +1,93 @@ +--- +title: Coordinates.speed +slug: Web/API/GeolocationCoordinates/speed +translation_of: Web/API/GeolocationCoordinates/speed +--- +
{{APIRef("Geolocation API")}}
+ +

Coordinates.speed 回傳唯讀的正複數代表速度,單位為公尺/秒。 如果裝置無法測量這個值則回傳 null。

+ +

語法

+ +
speed = coordinates.speed
+
+ +

規格

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Geolocation', '#speed', 'Coordinates.speed')}}{{Spec2('Geolocation')}}Initial specification.
+ +

瀏覽器的相容性

+ +

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

請參考

+ + diff --git a/files/zh-tw/web/api/geolocationposition/coords/index.html b/files/zh-tw/web/api/geolocationposition/coords/index.html new file mode 100644 index 0000000000..c6e018c8cc --- /dev/null +++ b/files/zh-tw/web/api/geolocationposition/coords/index.html @@ -0,0 +1,93 @@ +--- +title: Position.coords +slug: Web/API/GeolocationPosition/coords +translation_of: Web/API/GeolocationPosition/coords +--- +
{{APIRef("Geolocation API")}}
+ +

Position.coords 是一個 {{domxref("Coordinates")}} 物件的唯讀屬性,表示地理的特性:回傳的物件中包括位置、地球經緯度、海拔高度和速度,同時也包含著這些值的精準度訊息。

+ +

語法

+ +
coord = position.coords
+
+ +

規格

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Geolocation', '#coords', 'Position.coords')}}{{Spec2('Geolocation')}}Initial specification.
+ +

瀏覽器的相容性

+ +

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

請參考

+ + diff --git a/files/zh-tw/web/api/geolocationposition/index.html b/files/zh-tw/web/api/geolocationposition/index.html new file mode 100644 index 0000000000..ecf342ff49 --- /dev/null +++ b/files/zh-tw/web/api/geolocationposition/index.html @@ -0,0 +1,103 @@ +--- +title: Position +slug: Web/API/GeolocationPosition +translation_of: Web/API/GeolocationPosition +--- +
{{APIRef("Geolocation API")}}
+ +

Position 介面表示在給定時間相關裝置的位置。這個位置用一個 {{domxref("Coordinates")}} 物件表示,包括裝置在地球上的二維位置,以及裝置的海拔高度和速度。

+ +

屬性

+ +

Position 介面沒有繼承任何屬性

+ +
+
{{domxref("Position.coords")}} {{readonlyInline}}
+
回傳一個定義當前位置的 {{domxref("Coordinates")}} 物件。
+
{{domxref("Position.timestamp")}} {{readonlyInline}}
+
回傳一個時間戳 {{domxref("DOMTimeStamp")}} ,這個時間戳表示獲取到位置的時間。
+
+ +

方法

+ +

Position 介面沒有實作或繼承任何方法

+ +

規格

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Geolocation', '#position', 'Position')}}{{Spec2('Geolocation')}}Initial specification.
+ +

瀏覽器的相容性

+ +

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

請參考

+ + diff --git a/files/zh-tw/web/api/geolocationposition/timestamp/index.html b/files/zh-tw/web/api/geolocationposition/timestamp/index.html new file mode 100644 index 0000000000..26c72e5e14 --- /dev/null +++ b/files/zh-tw/web/api/geolocationposition/timestamp/index.html @@ -0,0 +1,93 @@ +--- +title: Position.timestamp +slug: Web/API/GeolocationPosition/timestamp +translation_of: Web/API/GeolocationPosition/timestamp +--- +
{{APIRef("Geolocation API")}}
+ +

Position.timestamp 是一個唯讀的 {{domxref("DOMTimeStamp")}} 物件, 此物件代表建立 {{domxref("Position")}} 物件的日期和時間,精確度為毫秒。

+ +

語法

+ +
coord = position.timestamp
+
+ +

規格

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Geolocation', '#timestamp', 'Position.timestamp')}}{{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}}
+
+ +

請參考

+ + diff --git a/files/zh-tw/web/api/geolocationpositionerror/code/index.html b/files/zh-tw/web/api/geolocationpositionerror/code/index.html new file mode 100644 index 0000000000..e561a780d0 --- /dev/null +++ b/files/zh-tw/web/api/geolocationpositionerror/code/index.html @@ -0,0 +1,120 @@ +--- +title: PositionError.code +slug: Web/API/GeolocationPositionError/code +translation_of: Web/API/GeolocationPositionError/code +--- +
{{APIRef("Geolocation API")}}
+ +

PositionError.code 是一個唯讀無符號整數(unsigned short)表示錯誤碼 。以下列出可能的值:

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
相對應的常數描述
1PERMISSION_DENIED取得地理資訊失敗,因為此頁面沒有獲取地理位置信息的權限。
2POSITION_UNAVAILABLE取得地理資訊失敗,因為至少有一個地理位置信息內的資訊回傳了錯誤。
3TIMEOUT取得地理資訊超過時限,利用 {{domxref("PositionOptions.timeout")}} i來定義取得地理資訊的時限。
+ +

語法

+ +
typeErr = poserr.code
+
+ +

規格

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Geolocation', '#code', 'PositionError.code')}}{{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}}
+
+ +

請參考

+ + diff --git a/files/zh-tw/web/api/geolocationpositionerror/index.html b/files/zh-tw/web/api/geolocationpositionerror/index.html new file mode 100644 index 0000000000..e721bd062c --- /dev/null +++ b/files/zh-tw/web/api/geolocationpositionerror/index.html @@ -0,0 +1,128 @@ +--- +title: PositionError +slug: Web/API/GeolocationPositionError +translation_of: Web/API/GeolocationPositionError +--- +
{{APIRef("Geolocation API")}}
+ +

PositionError 介面表示使用定位設備時發生錯誤的原因。

+ +

屬性

+ +

PositionError 介面沒有繼承任何屬性

+ +
+
{{domxref("PositionError.code")}} {{readonlyInline}}
+
回傳一個無符號整數(unsigned short)來表示錯誤碼。以下列出可能的值: + + + + + + + + + + + + + + + + + + + + + + + +
相對應的常數描述
1PERMISSION_DENIED取得地理資訊失敗,因為此頁面沒有獲取地理位置信息的權限。
2POSITION_UNAVAILABLE取得地理資訊失敗,因為至少有一個地理位置信息內的資訊回傳了錯誤。
3TIMEOUT取得地理資訊超過時限,利用{{domxref("PositionOptions.timeout")}} 來定義取得地理資訊的時限。
+
+
{{domxref("PositionError.message")}} {{readonlyInline}}
+
回傳一個可讀的 {{domxref("DOMString")}} 來描述錯誤的詳細訊息。注意規格中指出此訊息是用來除錯而非直接顯示在使用者介面。
+
+ +

方法

+ +

PositionError 介面沒有實作也沒有繼承任何方法

+ +

規格

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Geolocation', '#positionerror', 'PositionError')}}{{Spec2('Geolocation')}}Initial specification.
+ +

瀏覽器的相容性

+ +

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

請參考

+ + diff --git a/files/zh-tw/web/api/geolocationpositionerror/message/index.html b/files/zh-tw/web/api/geolocationpositionerror/message/index.html new file mode 100644 index 0000000000..839fb18818 --- /dev/null +++ b/files/zh-tw/web/api/geolocationpositionerror/message/index.html @@ -0,0 +1,93 @@ +--- +title: PositionError.message +slug: Web/API/GeolocationPositionError/message +translation_of: Web/API/GeolocationPositionError/message +--- +
{{APIRef("Geolocation API")}}
+ +

PositionError.message 是一個可讀的 {{domxref("DOMString")}} 來描述錯誤的詳細訊息。

+ +

語法

+ +
msg = positionError.message
+
+ +

規格

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Geolocation', '#message', 'PositionError.message')}}{{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}}
+
+ +

請參考

+ + diff --git a/files/zh-tw/web/api/globaleventhandlers/index.html b/files/zh-tw/web/api/globaleventhandlers/index.html new file mode 100644 index 0000000000..492ed0ae93 --- /dev/null +++ b/files/zh-tw/web/api/globaleventhandlers/index.html @@ -0,0 +1,682 @@ +--- +title: GlobalEventHandlers +slug: Web/API/GlobalEventHandlers +translation_of: Web/API/GlobalEventHandlers +--- +
{{ApiRef("HTML DOM")}}
+ +

GlobalEventHandlers(通用事件處理器)在多個介面,如 {{domxref("HTMLElement")}}、{{domxref("Document")}} 和 {{domxref("Window")}} 當中加入了共有的事件處理器屬性,這些介面皆能夠加入除了以下清單外的更多事件處理器。

+ +
+

Note: GlobalEventHandlers is a mixin and not an interface; you can't actually create an object of type GlobalEventHandlers.

+
+ +

屬性

+ +

This interface doesn't include any properties except for the event handlers listed below.

+ +

事件處理器

+ +

These event handlers are defined on the {{domxref("GlobalEventHandlers")}} mixin, and implemented by {{domxref("HTMLElement")}}, {{domxref("Document")}}, {{domxref("Window")}}, as well as by {{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.onanimationcancel")}} {{Non-standard_inline}}
+
An {{domxref("EventHandler")}} called when an {{event("animationcancel")}} event is sent, indicating that a running CSS animation has been canceled.
+
{{domxref("GlobalEventHandlers.onanimationend")}} {{Non-standard_inline}}
+
An {{domxref("EventHandler")}} called when an {{event("animationend")}} event is sent, indicating that a CSS animation has stopped playing.
+
{{domxref("GlobalEventHandlers.onanimationiteration")}} {{Non-standard_inline}}
+
An {{domxref("EventHandler")}} called when an {{event("animationiteration")}} event has been sent, indicating that a CSS animation has begun playing a new iteration of the animation sequence.
+
{{domxref("GlobalEventHandlers.onanimationstart")}} {{Non-standard_inline}}
+
An {{domxref("EventHandler")}} called when an {{event("animationstart")}} event is sent, indicating that a CSS animation has started playing.
+
{{domxref("GlobalEventHandlers.onauxclick")}} {{Non-standard_inline}}
+
An {{domxref("EventHandler")}} called when an {{event("auxclick")}} event is sent, indicating that a non-primary button has been pressed on an input device (e.g. a middle mouse button).
+
{{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.ongotpointercapture")}}
+
+

Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("gotpointercapture")}} event type 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.onloadend")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("loadend")}} event is raised (when progress has stopped on the loading of a resource.)
+
{{domxref("GlobalEventHandlers.onloadstart")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("loadstart")}} event is raised (when progress has begun on the loading of a resource.)
+
{{domxref("GlobalEventHandlers.onlostpointercapture")}}
+
+

Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("lostpointercapture")}} event type 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.onselectstart")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("selectionchange")}} event is raised, i.e. when the user starts to make a new text selection on a web page.
+
{{domxref("GlobalEventHandlers.onselectionchange")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("selectionchange")}} event is raised, i.e. when the text selected on a web page changes.
+
{{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.ontransitioncancel")}}
+
An {{domxref("EventHandler")}} called when a {{event("transitioncancel")}} event is sent, indicating that a CSS transition has been cancelled.
+
{{domxref("GlobalEventHandlers.ontransitionend")}}
+
An {{domxref("EventHandler")}} called when a {{event("transitionend")}} event is sent, indicating that a CSS transition has finished playing.
+
{{domxref("GlobalEventHandlers.onwaiting")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("waiting")}} event is raised.
+
+
+ +

方法

+ +

This interface defines no methods.

+ +

規範

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

瀏覽器相容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureFirefox (Gecko)ChromeEdgeInternet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{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)}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
onsuspend{{CompatGeckoDesktop(1.9.2)}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
ondrag, ondragend, ondragenter, ondragleave, ondragover, ondragstart, ondrop{{CompatGeckoDesktop(1.9.1)}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
onmouseenter, onmouseleave{{CompatGeckoDesktop(10)}}{{CompatChrome(30.0)}}{{CompatUnknown}}5.517{{CompatUnknown}}
ondragexit{{CompatNo}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
oncancel{{CompatNo}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
onclose{{CompatNo}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
oncuechange{{CompatNo}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
onmousewheel{{CompatNo}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
onsort {{experimental_inline}}{{CompatNo}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
onmozfullscreenchange, onmozfullscreenerror {{non-standard_inline}}{{CompatVersionUnknown}}{{CompatVersionUnknown}} {{property_prefix("-webkit")}}
+ {{CompatVersionUnknown}} (unprefixed)
{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
onpointerlockchange, onpointerlockerror{{CompatGeckoDesktop(10)}}[1]{{CompatVersionUnknown}}[2] {{property_prefix("-webkit")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
onpointercancel, onpointerdown, onpointerup, onpointermove, onpointerout, onpointerover, onpointerenter, onpointerleave{{CompatVersionUnknown}}[3]{{CompatChrome(55.0)}}{{CompatVersionUnknown}}10{{CompatUnknown}}{{CompatUnknown}}
onselectionchange{{CompatGeckoDesktop(43)}}[4]{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
ontouchend, ontouchcancel, ontouchmove, ontouchstart{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
animationstart, animationend, animationcancel, animationiteration{{CompatGeckoDesktop(51)}}{{CompatVersionUnknown}} {{property_prefix("-webkit")}}
+ {{CompatVersionUnknown}} (unprefixed)
{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
ongotpointercapture, onlostpointercapture{{CompatUnknown}}{{CompatChrome(57.0)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOpera(44)}}{{CompatUnknown}}
onauxclick{{CompatGeckoDesktop(53)}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewEdgeFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
ondrag, ondragend, ondragenter, ondragleave, ondragover, ondragstart, ondrop{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(1.9.1)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
oncanplay, oncanplaythrough, ondurationchange, onemptied, onended, onloadeddata, onloadedmetadata, onloadstart, onpause, onplay, onplaying, onprogress, onratechange, onseeked, onseeking, onstalled, ontimeupdate, onvolumechange, onwaiting{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(1.9.1)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
onmouseenter, onmouseleave{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(10)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
onsuspend{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(1.9.2)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
ondragexit{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatNo}}
oncancel{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
onclose{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
oncuechange{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
onmousewheel{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
onsort{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatNo}}
onmozfullscreenchange, onmozfullscreenerror {{non-standard_inline}}{{CompatVersionUnknown}} {{property_prefix("-webkit")}}
+ {{CompatVersionUnknown}} (unprefixed)
{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}} {{property_prefix("-webkit")}}
+ {{CompatVersionUnknown}} (unprefixed)
onpointerlockchange, onpointerlockerror{{CompatNo}}{{CompatUnknown}}{{CompatGeckoMobile(10)}}[1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatNo}}
onpointercancel, onpointerdown, onpointerup, onpointermove, onpointerout, onpointerover, onpointerenter, onpointerleave{{CompatChrome(55.0)}}{{CompatUnknown}}{{CompatVersionUnknown}}[3]{{CompatNo}}10{{CompatNo}}{{CompatNo}}{{CompatChrome(55.0)}}
onselectionchange{{CompatNo}}{{CompatUnknown}}{{CompatGeckoMobile(43)}}[4]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatNo}}
ontouchend, ontouchcancel, ontouchmove, ontouchstart{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
animationstart, animationend, animationcancel, animationiteration{{CompatVersionUnknown}} {{property_prefix("-webkit")}}
+ {{CompatVersionUnknown}} (unprefixed)
{{CompatUnknown}}{{CompatGeckoMobile(51)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}} {{property_prefix("-webkit")}}
+ {{CompatVersionUnknown}} (unprefixed)
ongotpointercapture, onlostpointercapture{{CompatChrome(57.0)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatOperaMobile(44)}}{{CompatUnknown}}{{CompatChrome(57.0)}}
onauxclick{{CompatVersionUnknown}}{{CompatNo}}{{CompatGeckoMobile(53)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}
+
+ +

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

+ +

參見

+ + diff --git a/files/zh-tw/web/api/globaleventhandlers/onclick/index.html b/files/zh-tw/web/api/globaleventhandlers/onclick/index.html new file mode 100644 index 0000000000..d5a1ac1845 --- /dev/null +++ b/files/zh-tw/web/api/globaleventhandlers/onclick/index.html @@ -0,0 +1,144 @@ +--- +title: GlobalEventHandlers.onclick +slug: Web/API/GlobalEventHandlers/onclick +tags: + - API + - HTML DOM + - Property + - Reference +translation_of: Web/API/GlobalEventHandlers/onclick +--- +
+
{{ ApiRef("HTML DOM") }}
+
+ +
 
+ +

onclick 屬性回傳當前元件 click 事件處理器的程式碼(event handler code)。

+ +
注意: 當使用 click 事件觸發動作時,同時考慮將此動作加到 keydown 事件中,讓沒使用滑鼠或使用觸控螢幕的使用者也可以進行此動作。
+ +

語法

+ +
element.onclick = functionRef;
+
+ +

此處的 functionRef 為一個函式-通常是函式的名字或是函式表示式(function expression) 見 "JavaScript Guide:Functions" 來了解更多。

+ +

傳入事件處理函式(event handler function)的唯一引數為 {{domxref("MouseEvent")}} 物件。在這函式中,this 為觸發此事件的元件。

+ +

範例

+ +
<!DOCTYPE html>
+<html lang="en">
+  <head>
+    <meta charset="UTF-8" />
+    <title>onclick event example</title>
+    <script>
+      function initElement() {
+        var p = document.getElementById("foo");
+        // NOTE: showAlert(); or showAlert(param); will NOT work here.
+        // Must be a reference to a function name, not a function call.
+        p.onclick = showAlert;
+      };
+
+      function showAlert(event) {
+        alert("onclick Event detected!");
+      }
+    </script>
+    <style>
+      #foo {
+        border: solid blue 2px;
+      }
+    </style>
+  </head>
+  <body onload="initElement();">
+    <span id="foo">My Event Element</span>
+    <p>click on the above element.</p>
+  </body>
+</html>
+
+ +

你也可以使用如下的匿名函式:

+ +
p.onclick = function(event) { alert("moot!"); };
+
+ +

備註

+ +

使用者點擊元件時會觸發 click 事件。click 事件發生在 mousedown 及 mouseup 事件之後。

+ +

這個屬性同一時間中只能指定一個 click 處理器(handler)。你也許會比較想使用 {{domxref("EventTarget.addEventListener()")}},因為它有更多的彈性而且是 DOM 事件規範的一部份。

+ +

規範

+ + + + + + + + + + + + + + +
規範狀態備註
{{SpecName('HTML WHATWG','webappapis.html#handler-onclick','onclick')}}{{Spec2('HTML WHATWG')}} 
+ +

瀏覽器相容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
diff --git a/files/zh-tw/web/api/globaleventhandlers/onclose/index.html b/files/zh-tw/web/api/globaleventhandlers/onclose/index.html new file mode 100644 index 0000000000..abe97bcd4c --- /dev/null +++ b/files/zh-tw/web/api/globaleventhandlers/onclose/index.html @@ -0,0 +1,102 @@ +--- +title: GlobalEventHandlers.onclose +slug: Web/API/GlobalEventHandlers/onclose +tags: + - API + - HTML DOM + - Property + - Reference +translation_of: Web/API/GlobalEventHandlers/onclose +--- +
{{ApiRef("HTML DOM")}}
+ +

送至視窗的 close event 的處理器(handler)。(不支援 Firefox 2 及 Safari)

+ +

語法

+ +
window.onclose = funcRef;
+
+ +

參數

+ + + +

範例

+ +
window.onclose = resetThatServerThing;
+
+ +

規範

+ + + + + + + + + + + + + + +
規範狀態備註
{{SpecName('HTML WHATWG','webappapis.html#handler-onclose','onclose')}}{{Spec2('HTML WHATWG')}} 
+ +

瀏覽器相容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatNo}}
+
diff --git a/files/zh-tw/web/api/history/index.html b/files/zh-tw/web/api/history/index.html new file mode 100644 index 0000000000..b4a1d7603e --- /dev/null +++ b/files/zh-tw/web/api/history/index.html @@ -0,0 +1,183 @@ +--- +title: History +slug: Web/API/History +translation_of: Web/API/History +--- +
{{ APIRef("HTML DOM") }}
+ +

History 介面允許操控瀏覽器的 session history 紀錄,為當前面頁所在分頁中訪問、或於當前面頁中透過頁面框架(frame)所載入的頁面。

+ +

屬性

+ +

The History interface doesn't inherit any property.

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

方法

+ +

The History interface doesn't inherit any methods.

+ +
+
{{domxref("History.back()")}}
+
回到 session history 紀錄中的前一頁,等同於使用者按下瀏覽器的上一頁按鈕。相當於 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()")}}
+
回到 session history 紀錄中的下一頁,等同於使用者按下瀏覽器的下一頁按鈕。相當於 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()")}}
+
自 session history 紀錄中載入一個頁面,利用該頁面相對於目前頁面的所在位置,例如 -1 為前一頁或 1 為下一頁。若指定了一個超出範圍的值(舉例來說,在 session history 沒有先前訪頁面的情況下指定 -1),此方法將會是靜默(不會產生錯誤)且沒有任何效果的。不帶參數或是傳入 0 呼叫 go() 會重新載入目前頁面。Internet Explorer 也可以傳入字串來前往一個於瀏覽歷史列表中指定的頁面。
+
{{domxref("History.pushState()")}} {{ gecko_minversion_inline("2.0") }}
+
插入給定的資料與指定的標題(title)以及選擇性的 URL 至 session history 堆疊(stack)中。給定的資料將被 DOM 視為不透明的(opaque);可以指定任何可被序列化的 JavaScript 物件。請注意 Firefox 目前會忽略標題(title)參數;更多資訊請參閱操控瀏覽器歷史紀錄
+
{{domxref("History.replaceState()")}} {{ gecko_minversion_inline("2.0") }}
+
以指定的資料、標題(title)及可選的 URL 來更新歷史紀錄堆疊(history stack)中近期的項目。給定的資料將被 DOM 視為不透明的(opaque);可以指定任何可被序列化的 JavaScript 物件。請注意 Firefox 目前會忽略標題(title)參數;更多資訊請參閱操控瀏覽器歷史紀錄
+
+ +

規範

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

瀏覽器相容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
pushState and replaceState{{CompatChrome(5.0)}}{{CompatVersionUnknown}}4.0 [1]1011.55
scrollRestoration{{CompatChrome(46.0)}}{{CompatNo}}{{CompatGeckoDesktop("46.0")}}{{CompatNo}}33{{CompatVersionUnknown}}[2]
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
pushState and replaceState2.2{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}10{{CompatVersionUnknown}}4.3{{CompatVersionUnknown}}
scrollRestoration{{CompatNo}}{{CompatChrome(46.0)}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}[2]{{CompatChrome(46.0)}}
+
+ +

[1] In Firefox 2 through 5, the passed object is serialized using JSON. Starting in Firefox 6, the object is serialized using the structured clone algorithm. This allows a wider variety of objects to be safely passed.

+ +

[2] WebKit bug 147782

+ +

參見

+ + diff --git a/files/zh-tw/web/api/history_api/index.html b/files/zh-tw/web/api/history_api/index.html new file mode 100644 index 0000000000..2554fe6801 --- /dev/null +++ b/files/zh-tw/web/api/history_api/index.html @@ -0,0 +1,255 @@ +--- +title: 操控瀏覽器歷史紀錄 +slug: Web/API/History_API +tags: + - DOM + - HTML5 + - History +translation_of: Web/API/History_API +--- +

DOM {{ domxref("window") }} 物件透過 {{ domxref("window.history", "history") }} 物件,提供了進入瀏覽歷史的方式。他透過一些方便的屬性與方法,讓你可以在歷史紀錄中往上一步或往下一步移動,並且讓你——從 HTML5 開始——能操作歷史紀錄堆疊(history stack)的內容。

+ +

在歷史紀錄中移動

+ +

往前往後歷史紀錄可以用 back(), forward(), 和 go() 的方法。

+ +

往前往後

+ +

要在歷史紀錄中往上一步移動,可以:

+ +
window.history.back();
+
+ +

這完全等同於用戶在瀏覽器上點選「上一頁」按鈕。

+ +

同樣的,你也可以往下一步移動(等同於用戶點擊往後一頁的按鈕):

+ +
window.history.forward();
+
+ +

移動到特定的歷史紀錄

+ +

你可以用 go() 方法來從頁面的 session history 紀錄中載入特定紀錄,以目前頁面的相對位置而定(目前的頁面想當然爾是 index 0)。

+ +

往前一頁(等同於呼叫 back()):

+ +
window.history.go(-1);
+
+ +

往後一頁(等同於呼叫 forward()):

+ +
window.history.go(1);
+
+ +

同樣的你也可以傳入 2,讓頁面直往後兩頁,依此類推。

+ +

你可以查看 length 這個屬性來取得目前瀏覽歷史的總數我:

+ +
var numberOfEntries = window.history.length;
+
+ +
備註:Internet Explorer 支援在 go() 中以 URL 的值作為參數;這不在標準中,Gecko 也不支援。
+ +

加入和修改歷史紀錄

+ +

{{ gecko_minversion_header("2") }}

+ +

HTML5 加入了 history.pushState()history.replaceState() 方法,讓你可以加入或修改歷史紀錄。這些方法都可以跟 {{ domxref("window.onpopstate") }} 事件一同應用。

+ +

使用 history.pushState()後,會改變 XMLHttpRequest 時 HTTP 標頭中 referrer 的值。referrer 會是創造 XMLHttpRequest 物件時的當前視窗文件(this)的 URL。

+ +

pushState() 方法範例

+ +

假設 http://mozilla.org/foo.html 執行了下面的 JavaScript:

+ +
var stateObj = { foo: "bar" };
+history.pushState(stateObj, "page 2", "bar.html");
+
+ +

這會讓網址列顯示 http://mozilla.org/bar.html,但不會讓瀏覽器去載入 bar.html,甚或去檢查 bar.html 存在與否。

+ +

假設現在使用者瀏覽到 http://google.com,然後點擊上一頁鈕。這時網址列會顯示 http://mozilla.org/bar.html,頁面會獲得 popstate 的事件(state object 會包含一份 stateObj 的副件)。頁面長得跟 foo.html 很像,但是可能在 popstate 事件執行中被修改。

+ +

如果我再點一次上一頁鈕, 網址會改變成為 http://mozilla.org/foo.html,且文件會得到另外一個 popstate 事件,此次會包含一個 null state object。同樣的,回上頁鈕不會改變文件的內容,只是文件可能會在 popstate 事件中被手動更新。

+ +

pushState() 方法

+ +

pushState() 取用三個參數:一個 state 物件、title(目前忽略)與 URL(可選用)。我們來看看三個參數的細節之處:

+ + + +
備註:在 Gecko 2.0 {{ geckoRelease("2.0") }} 到 Gecko 5.0 {{ geckoRelease("5.0") }},是採用 JSON 來序列化這個傳送的物件。從 Gecko 6.0 {{ geckoRelease("6.0") }} 開始,這個物件是以 the structured clone algorithm 序列化。這會允許更多種不同的物件可以被安全的傳送。
+ +

從某種意義上,呼叫 pushState() 與設定 window.location = "#foo" 是類似的,兩個都會去建立和啟用另一個和目前文件有關的歷史紀錄。但是 pushState() 有一些優勢:

+ + + +

注意 pushState() 永遠不會造成一個 hashchange 事件被觸發,即使新的 URL 和舊的 URL 的不同處只有 hash 的部份也不會。

+ +

In a XUL document, it creates the specified XUL element.

+ +

In other documents, it creates an element with a null namespace URI.

+ +

replaceState() 方法

+ +

history.replaceState() 的執行就像 history.pushState() ,除了 replaceState() 是修改目前的歷史紀錄而不是創造一個新的。

+ +

replaceState() 很實用的時機是當你要更新目前歷史紀錄的 state object 或是URL來反應一些使用者的動作時。

+ +
備註:在 Gecko 2.0 {{ geckoRelease("2.0") }} 到 Gecko 5.0 {{ geckoRelease("5.0") }},是採用 JSON 來序列化這個傳送的物件。從 Gecko 6.0 {{ geckoRelease("6.0") }} 開始, 這個物件是以 the structured clone algorithm 序列化。這會允許更多種不同的物件可以被安全的傳送。
+ +

replaceState() 方法範例

+ +

Suppose http://mozilla.org/foo.html executes the following JavaScript:

+ +
var stateObj = { foo: "bar" };
+history.pushState(stateObj, "page 2", "bar.html");
+
+ +

The explanation of these two lines above can be found at "Example of pushState() method" section. Then suppose http://mozilla.org/bar.html executes the following JavaScript:

+ +
history.replaceState(stateObj, "page 3", "bar2.html");
+
+ +

This will cause the URL bar to display http://mozilla.org/bar2.html, but won't cause the browser to load bar2.html or even check that bar2.html exists.

+ +

Suppose now that the user now navigates to http://www.microsoft.com, then clicks back. At this point, the URL bar will display http://mozilla.org/bar2.html. If the user now clicks back again, the URL bar will display http://mozilla.org/foo.html, and totaly bypass bar.html.

+ +

popstate 事件

+ +

每次 active 的歷史紀錄被更動的時候,一個 popstate 事件會被發送到目前的 window。如果被啟用的歷史紀錄是由於呼叫 pushState 建立的或是呼叫 replaceState 所影響的,這個 popstate 事件的 state 屬性會含有一個歷史紀錄的 state object 的副本。

+ +

使用範例參閱 {{ domxref("window.onpopstate") }}。

+ +

讀取目前的 state

+ +

當你讀取頁面的時候,可能會有 non-null state 的物件。這會發生在,例如說,如果設定一個 state 物件(用 pushState() 或是 replaceState()),然後使用者重新啟動他的瀏覽器。當重新讀取你的頁面的時候,頁面會得到一個 onload 事件,但是沒有 popstate 事件。然而,如果你讀取了 history.state 屬性,你會得到像是 popstate 被觸發時,你會得到的 state object 。

+ +

像這樣使用 history.state 屬性,你可以讀取目前的歷史紀錄的狀態而不需要等待一個 popstate 事件:

+ +
var currentState = history.state;
+
+ +

範例

+ +

完整的 AJAX 網站範例 ,請參閱:Ajax navigation example

+ +

規範

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "browsers.html#history", "History")}}{{Spec2('HTML WHATWG')}}No change from {{SpecName("HTML5 W3C")}}.
{{SpecName('HTML5 W3C', "browsers.html#history", "History")}}{{Spec2('HTML5 W3C')}}Initial definition.
+ +

瀏覽器相容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
replaceState, pushState5{{CompatVersionUnknown}}{{ CompatGeckoDesktop("2.0") }}1011.505.0
history.state18{{CompatVersionUnknown}}{{ CompatGeckoDesktop("2.0") }}1011.506.0
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
replaceState, pushState{{ CompatUnknown() }}{{CompatVersionUnknown}}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
history.state{{ CompatUnknown() }}{{CompatVersionUnknown}}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

參見

+ + + +

{{ languages( { "ja": "ja/DOM/Manipulating_the_browser_history"} ) }}

diff --git a/files/zh-tw/web/api/html_drag_and_drop_api/drag_operations/index.html b/files/zh-tw/web/api/html_drag_and_drop_api/drag_operations/index.html new file mode 100644 index 0000000000..c609d6f4d4 --- /dev/null +++ b/files/zh-tw/web/api/html_drag_and_drop_api/drag_operations/index.html @@ -0,0 +1,336 @@ +--- +title: 拖曳操作 +slug: Web/API/HTML_Drag_and_Drop_API/Drag_operations +translation_of: Web/API/HTML_Drag_and_Drop_API/Drag_operations +--- +

{{DefaultAPISidebar("HTML Drag and Drop API")}}

+ +

本文會一一說明拖曳各步驟的作業。

+ +

The drag operations described in this document use the {{domxref("DataTransfer")}} interface. This document does not use the {{domxref("DataTransferItem")}} interface nor the {{domxref("DataTransferItemList")}} interface.

+ +

Draggable 屬性

+ +

網頁中有些預設的拖曳行為,例如文字選擇、圖片或超連結,當拖曳圖片或超連結時,圖片或超連結的 URL 會被當作拖曳作業中所攜帶的資料,而其他類型元素則必須另外處理才能拖曳,試試看選擇網頁某一部分,然後按住滑鼠鍵來進行拖曳,依據OS不同,或許會有一些跟著滑鼠移動的效果,但這僅僅只是預設效果行為,實際上沒有任何資料跟著被拖曳。

+ +

In HTML, apart from the default behavior for images, links, and selections, no other elements are draggable by default. In XUL, all elements are draggable.

+ +

除了文字選擇、圖片或超連結之外,沒有元素預設是可拖曳的。所以要讓一個元素可以拖曳,有幾件事必須要做:

+ + + +

以下是一段簡單的範例。

+ +
<div draggable="true" ondragstart="event.dataTransfer.setData('text/plain', 'This text may be dragged')">
+  This text <strong>may</strong> be dragged.
+</div>
+
+ +

draggable 為 true後,該 DIV 元素便可以拖曳,反之,倘若 draggable 為 false 或無設定則不可拖曳,只有其中下含的文字可以被選擇。draggable 屬性適用於任何元素,一般來說預設為false,除了圖片和連結預設為 true,所以說如果想要阻止圖片和連結被拖曳,則可以設定draggable 為 false。

+ +

請注意,一旦元素被定為可拖曳之後,其下內含的文字或其他元素便無法像平常一樣用滑鼠選擇,使用者之能夠改用鍵盤或按住 Alt 鍵搭配滑鼠進行選擇。

+ +

至於 XUL 元素則是預設皆可拖曳。

+ +
<button label="Drag Me" ondragstart="event.dataTransfer.setData('text/plain', 'Drag Me Button');">
+
+ +

開始拖曳

+ +

下方範例在dragstart註冊一個事件處理器。

+ +
<div draggable="true" ondragstart="event.dataTransfer.setData('text/plain', 'This text may be dragged')">
+  This text <strong>may</strong> be dragged.
+</div>
+
+ +

當拖曳作業開始,dragstart 事件會觸發,然後我們可以在事件處理器中準備好我們所要攜帶的資料、想要的拖曳回饋效果,不過基本上其實只需要準備資料就好,因為預設拖曳回饋效果已經足以應付大多數的狀況,此外,我們也可以改在上一層父元素註冊事件處理器,因為拖曳事件會上向傳遞 ( Bubble up ) 。

+ +

拖曳資料

+ +

所有的拖曳事件物件都有一個 dataTransfer 屬性,這個屬性是用來攜帶資料。

+ +

當拖曳時,資料必須和被拖曳目標作連結,比如說拖曳文字框中反白選擇的文字,那麼文字本身便是連結資料,同理,拖曳連結時URL便是連結資料。

+ +

資料包含兩個部分,一是資料型態(或格式)、二是資料值。所謂資料型態是用文字描述資料型態(如text/plain代表文字資料),而資料值則是文字,要加入拖資料需要提供資料的型態和內容值;有了資料後,我們可以在dragenter或dragover事件處理器中,透過檢查資料型態來決定是否可以接受後續的放置操作,比如說只接受連結類資料的拖目標區(drop target),會檢查資料型態是否為text/uri-list

+ +

資料型態符合MIME型態,如text/plainimage/jpeg等等,而我們自己也可以自定義其他型態,最常使用的型態請見推薦拖曳資料型態

+ +

一趟拖曳作業中可以攜帶多個多種型態的資料,所以我們可以自定義自己的型態同時,還提供其他資料給不認得自定義資料型態的其他拖曳目標區使用。通常最通用的資料會是文字類型資料。

+ +

呼叫setData方法,傳入資料型態和資料,這樣就可以攜帶想要的資料了:

+ +
event.dataTransfer.setData("text/plain", "Text to drag");
+
+ +

上例資料是”Text to drag”文字,型態是text/plain。

+ +

呼叫多次setData我們就可以攜帶多種資料。

+ +
var dt = event.dataTransfer;
+dt.setData("application/x-bookmark", bookmarkString);
+dt.setData("text/uri-list", "http://www.mozilla.org");
+dt.setData("text/plain", "http://www.mozilla.org");
+
+ +

這裡加入了三種資料,第一種是自定義的”application/x-bookmark”,雖然有更豐富的內容可使用,但只有我們自己認識,而另外我們又為其他網站或應用加入了兩種比較常見的資料,”text/uri-list”以及”text/plain”。

+ +

如果對同一種資料型態加入兩次資料,則新加資料會取代舊資料。

+ +

呼叫clearData會清除資料。

+ +
event.dataTransfer.clearData("text/uri-list");
+
+ +

如果呼叫clearData時有傳入資料型態,則只會清除該型態資料,如果沒有傳入任何型態,則所有資料皆會被清除。

+ +

設定拖曳圖片

+ +

當拖曳進行中,以拖曳元素為基礎,一個半透明的圖片會自動產生出來,並且跟著滑鼠移動。如果想要,我們也可以呼叫setDragImage()來指定我們自己的拖曳使用圖片。

+ +
event.dataTransfer.setDragImage(image, xOffset, yOffset);
+
+ +

setDragImage需要三個參數,一是圖片來源(通常是圖片元素,但也可以是canvas元素或其他元素),拖曳使用圖片會依照圖片來源在螢幕上所顯示的樣子產生;二和三是圖片相對於滑鼠指標的位置位移量。

+ +

不過也是能夠使用文件外部的圖片或canvas元素,當需要透過canvas元素產生客製圖片時,這個技巧很有用,如下範例所示:

+ +
function dragWithCustomImage(event) {
+  var canvas = document.createElementNS("http://www.w3.org/1999/xhtml","canvas");
+  canvas.width = canvas.height = 50;
+
+  var ctx = canvas.getContext("2d");
+  ctx.lineWidth = 4;
+  ctx.moveTo(0, 0);
+  ctx.lineTo(50, 50);
+  ctx.moveTo(0, 50);
+  ctx.lineTo(50, 0);
+  ctx.stroke();
+
+  var dt = event.dataTransfer;
+  dt.setData('text/plain', 'Data to Drag');
+  dt.setDragImage(canvas, 25, 25);
+}
+
+ +

上面我們的canvas是50 x 50px大小,然後我們位移一半25讓圖片落在滑鼠指標中央。 

+ +

{{h2_gecko_minversion("使用XUL panel元素作為拖曳圖片", "9.0")}}

+ +

在Gecko上開發,比如說外掛或Mozllia應用程式,Gecko9.0{{geckoRelease("9.0")}}支援使用{{XULElem("panel")}}元素作為拖曳圖片,簡單將XUL panel元素傳入setDragImage方法即可。

+ +

試想下面這個 {{XULElem("panel")}}元素:

+ +
<panel id="panel" style="opacity: 0.6">
+  <description id="pb">Drag Me</description>
+</panel>
+
+<vbox align="start" style="border: 1px solid black;" ondragstart="startDrag(event)">
+  <description>Drag Me</description>
+</vbox>
+
+ +

當使用者拖曳{{XULElem("vbox")}} 元素時,startDrag函數會被呼叫。

+ +
function startDrag(event) {
+  event.dataTransfer.setData("text/plain", "<strong>Body</strong>");
+  event.dataTransfer.setDragImage(document.getElementById("panel"), 20, 20);
+}
+
+ +

我們用HTML格式的"<strong>Body</strong>"作為資料,然後用pnael元素作為圖片。

+ +

拖曳效果

+ +

拖曳作業有好機種;copy作業代表被拖曳資料會被複製一份到拖曳目標區,move作業代表移動被拖曳的資料,link作業代表拖曳來源區和拖曳目標區有某種關係。

+ +

在dragstart事件中可以設定effectAllowed屬性,指定拖曳源頭允許的作業。

+ +
event.dataTransfer.effectAllowed = "copy";
+
+ +

上面只有copy被允許,但還有其他種類:

+ +

     只能移動或連結。

+ +
+
none
+
不允許任何作業。
+
copy
+
只能複製。
+
move
+
只能移動。
+
link
+
只有連結。
+
copyMove
+
只能複製或移動。
+
copyLink
+
只能複製或連結。
+
linkMove
+
all
+
複製、移動或連結皆可。
+
+ +

effectAllowed 屬性預設所有作業都接受,如all值。

+ +

在dragenter或dragover事件中,我們可以藉由檢查effectAllowed來知道那些作業是被允許的,另外,另一個相關聯的dropEffect屬性應該要是effectAllowed的其中一個作業,但是dropEffect不接受多重作業,只可以是none, copy, move和link。

+ +

dropEffect屬性會在在dragenter以及dragover事件中初始化為使用者想要執行的作業效果,使用者能夠透過按鍵(依平台不同,通常是Shift或Ctrl鍵),在複製、移動、連接作業之間切換,同時滑鼠指標也會跟著相應變換,例如複製作業的滑鼠旁會多出一個+的符號。

+ +

effectAllowed和dropEffect屬性可以在dragenter或dragover事件中更改,更改effectAllowed屬性能讓拖曳作業只能在支援被允許作業類型的拖曳目標上執行,好比說effectAllowed為copyMove的作業就會阻止使用者進行link類型的作業。

+ +

我們也可以更改dropEffect來強迫使用者執行某項作業,而且應該要是effectAllowed所列舉的作業。

+ +
event.dataTransfer.effectAllowed = "copyMove";
+event.dataTransfer.dropEffect = "copy";
+
+ +

上面的範例中copy就是會被執行的作業效果。

+ +

若effectAllowed或dropEffect為none,那麼沒有放置作業可以被執行。

+ +

指定拖曳目標

+ +

dragenter和dragover事件就是用來指定拖曳目標區,也就是放置資料的目標區,絕大多數的元素預設的事件都不准放置資料。

+ +

所以想要放置資料到元素上,就必須取消預設事件行為。取消預設事件行為能夠藉由回傳false或呼叫event.preventDefault方法。

+ +
<div ondragover="return false">
+<div ondragover="event.preventDefault()">
+
+ +

通常我們只有在適當的時機點才需要呼叫event.preventDefault方法、取消預設事件行為,比如說被拖曳進來的是連結。所以檢查被拖曳進來的物件,當符合條件後再來取消預設事件行為。

+ +

藉由檢查拖曳資料型態來決定是否允許放置,是最常見的作法。dataTransfer物件的types屬性是一個拖曳資料型態的列表,其中順序按照資料被加入之先後排序。

+ +
function doDragOver(event)
+{
+  var isLink = event.dataTransfer.types.contains("text/uri-list");
+  if (isLink)
+    event.preventDefault();
+}
+
+ +

上面我們呼叫contains方法檢察text/uri-list是否存在拖曳資料型態的列表之內,有的話才取消預設行為、准許放置作業,否則,不取消預設行為、不准許放置作業。

+ +

檢查拖曳資料型態後,我們也可以依此更動effectAllowed和dropEffect屬性,只不過,如果沒有取消預設行為,更動並不會有甚麼影響。

+ +

Updates to DataTransfer.types

+ +

Note that the latest spec now dictates that {{domxref("DataTransfer.types")}} should return a frozen array of {{domxref("DOMString")}}s rather than a {{domxref("DOMStringList")}} (this is supported in Firefox 52 and above).

+ +

As a result, the contains method no longer works on the property; the includes method should be used instead to check if a specific type of data is provided, using code like the following:

+ +
if ([...event.dataTransfer.types].includes('text/html')) {
+  // Do something
+}
+ +

You could always use some feature detection to determine which method is supported on types, and run code as appropriate.

+ +

放置回饋

+ +

有好幾種方法回饋使用者,告訴使用者甚麼元素可以接受放置作業,最簡單的是滑鼠會指標會自動變換樣式(視平台而定)。

+ +

滑鼠指標提示雖然夠用了,不過有時我們還是會想做其他UI上的樣式變化。-moz-drag-over的CSS pseudo-class便可以應用在拖曳目標元素上。

+ +
.droparea:-moz-drag-over {
+  border: 1px solid black;
+}
+
+ +

當目標元素的dragenter預設事件有被取消時,這個pseudo-class就會啟動,目標UI會套用1px的黑色border,請注意dragover並不會檢查這項設定。

+ +

其他比如說插入圖片等,在dragenter事件內執行更多更複雜的樣式變化也是可以的。

+ +

倘若想要做出圖片更著滑鼠在拖曳目標區上面移動的效果,那麼可以在dragover事件內來取得的clientXclientY的滑鼠座標資訊。

+ +

最後,應該要在dragleave事件內復原之前所做樣式變更,dragleave事件不需要取消預設事件行為、永遠都會觸發,即使拖曳被取消了;至於使用-moz-drag-over的CSS方法的話,樣式復原會自動執行,不用擔心。

+ +

執行放置作業

+ +

當使用者在拖曳目標區上放開滑鼠時,drop事件就會觸發。當drop事件發生,我們需要取出被丟入的資料,然後處理之。

+ +

要取出被丟入的資料,那就要呼叫dataTransfer物件的getData方法。getData方法接受資料型態的參數,它會回傳setData所存入的對應資料型態的資料,倘若沒有對應型態資料,那空字串就會被回傳。

+ +
function onDrop(event)
+{
+  var data = event.dataTransfer.getData("text/plain");
+  event.target.textContent = data;
+  event.preventDefault();
+} 
+ +

上面的範例會取出文字資料,假設拖曳目標區是文字區域,例如p或div元素,那麼資料就會被當作文字內容,插入目標元素之中。

+ +

網頁之中,如果我們已經處理過放置資料,那應該要呼叫{preventDefault}方法防止瀏覽器再次處理資料,比如說,Firefox預設是會開啟拖入的連結,但我們可以取消這項預設行為來避免開啟連結。

+ +

當然也可以取得其他種類資料來使用,比如說連結資料,text/uri-list

+ +
function doDrop(event)
+{
+  var links = event.dataTransfer.getData("text/uri-list").split("\n");
+  for each (var link in links) {
+    if (link.indexOf("#") == 0)
+      continue;
+
+    var newlink = document.createElement("a");
+    newlink.href = link;
+    newlink.textContent = link;
+    event.target.appendChild(newlink);
+  }
+  event.preventDefault();
+}
+
+ +

上面的範例取得連結資料,然後生成連結元素、加入頁面。從text/uri-list字面上不難猜出這種資料是一行行的URL,所以我們呼叫split方法拆開一行行的URL,再將URL一個一個加入頁面。請注意我們有避開開頭為”#”字元的註解。

+ +

更簡單的作法是採用特別URL型態。URL型態是一個特殊簡寫用途形態,它不會出現在{types}屬性中,但它可以方便的取得第一個連結,如下:

+ +
var link = event.dataTransfer.getData("URL");
+
+ +

這個作法能夠省去檢查註解和一個一個掃過URL,但只會得到第一個URL。

+ +

下面的例子會從多個支援的資料型態中,找出支援的資料。

+ +
function doDrop(event)
+{
+  var types = event.dataTransfer.types;
+  var supportedTypes = ["application/x-moz-file", "text/uri-list", "text/plain"];
+  types = supportedTypes.filter(function (value) types.contains(value));
+  if (types.length)
+    var data = event.dataTransfer.getData(types[0]);
+  event.preventDefault();
+}
+ +

完成拖曳

+ +

拖曳作業完成後,不論成功或取消於否,被拖曳元素的dragend事件都會觸發,如果想要判別作業是否完成,可以檢查dropEffect屬性,若是dropEffect為none,代表拖曳作業被取消,否則dropEffect的值代表所完成的作業類型。

+ +

有一個Gecko專屬的mozUserCancelled屬性,當使用者按ESC鍵取消拖曳後,這個屬性會為true,但若是因其他理由被取消或成功,則為false

+ +

拖曳作業的放置可以發生在同一個視窗或其他應用程式,而且dragend事件還是會觸發,不過事件中的screenXscreenY屬性會是放置發生點的資訊。

+ +

當dragend事件結束傳遞後,拖曳作業也完成了。

+ +

[1] 在Gecko,如果被拖曳元素在拖曳作業還在進行中移動或刪除,那麼dragend事件就不會觸發。bug 460801

+ +
+ + +
 
+ +
 
+
+ +

參見

+ + diff --git a/files/zh-tw/web/api/html_drag_and_drop_api/index.html b/files/zh-tw/web/api/html_drag_and_drop_api/index.html new file mode 100644 index 0000000000..ac7be3f0b0 --- /dev/null +++ b/files/zh-tw/web/api/html_drag_and_drop_api/index.html @@ -0,0 +1,249 @@ +--- +title: HTML 拖放 API +slug: Web/API/HTML_Drag_and_Drop_API +translation_of: Web/API/HTML_Drag_and_Drop_API +--- +

{{DefaultAPISidebar("HTML Drag and Drop API")}}

+ +

HTML 拖放介面能讓網頁應用程式於 Firefox 及其他瀏覽器中使用拖放功能。舉例來說,使用者可以利用此功能以滑鼠選擇可拖曳(draggable)元素,拖曳至一個可放置(droppable)元素上,並放開滑鼠按鍵來放置此元素。在拖曳操作時,一個半透明的可拖曳(draggable)元素會跟隨著滑鼠游標。

+ +

對於網站、擴充套件以及 XUL 應用程式來說,你可以自定義能成為可拖曳(draggable)的元素類型、可拖曳(draggable)元素產生的回鐀類型,以及可放置(droppable)的元素。

+ +

此文件為 HTML 拖放的概述,包含了相關介面的說明、在應用程式中加入拖放支援的基本步驟,以及相關介面使用簡介。

+ +

拖曳事件

+ +

HTML 拖放操作基於 {{domxref("Event","DOM 事件模型")}}並且使用繼承自{{domxref("MouseEvent","滑鼠事件")}}的{{domxref("DragEvent","拖曳事件")}}介面。一個典型的拖曳操作開始於使用者利用滑鼠選取了一個可拖曳(draggable)元素、移動滑鼠至一個可放置(droppable)元素並放開滑鼠按鍵。在操作的過程中,會觸發多種類型的事件,且一些事件類型可能會被觸發多次(如 {{event("drag")}} 及 {{event("dragover")}} 事件類型)。

+ +

所有的拖曳事件類型都有相關的通用事件處理器(global event handler)。每一種拖曳事件類型及拖曳通用事件處理器屬性都有說明此事件的參考文件。以下的表格提供了每一種事件的簡要說明,以及參考文件的連結。

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
事件事件處理器屬性說明
{{event('drag')}}{{domxref('GlobalEventHandlers.ondrag','ondrag')}}於一個元素或文字選取區塊被拖曳時觸發。
{{event('dragend')}}{{domxref('GlobalEventHandlers.ondragend','ondragend')}}於拖曳操作結束時觸發(如放開滑鼠按鍵或按下鍵盤的 escape 鍵)。(請參考結束拖曳。)
{{event('dragenter')}}{{domxref('GlobalEventHandlers.ondragenter','ondragenter')}}於一個元素或文字選取區塊被拖曳移動進入一個有效的放置目標時觸發。(請參考指定拖曳目標。)
{{event('dragexit')}}{{domxref('GlobalEventHandlers.ondragexit','ondragexit')}}當一個元素不再是被選取中的拖曳元素時觸發。
{{event('dragleave')}}{{domxref('GlobalEventHandlers.ondragleave','ondragleave')}}於一個元素或文字選取區塊被拖曳移動離開一個有效的放置目標時觸發。
{{event('dragover')}}{{domxref('GlobalEventHandlers.ondragover','ondragover')}}於一個元素或文字選取區塊被拖曳移動經過一個有效的放置目標時觸發(每幾百毫秒觸發一次)。
{{event('dragstart')}}{{domxref('GlobalEventHandlers.ondragstart','ondragstart')}}於使用者開始拖曳一個元素或文字選取區塊時觸發。(請參考開始拖曳。)
{{event('drop')}}{{domxref('GlobalEventHandlers.ondrop','ondrop')}}於一個元素或文字選取區塊被放置至一個有效的放置目標時觸發。(請參考執行放置。)
+ +

注意:dragstartdragend 事件,在把檔案從作業系統拖放到瀏覽器時,並不會觸發。

+ +

介面

+ +

HTML 拖放介面有 {{domxref("DragEvent")}}、{{domxref("DataTransfer")}}、{{domxref("DataTransferItem")}} 以及 {{domxref("DataTransferItemList")}}。

+ +

{{domxref("DragEvent")}} 介面擁有一個建構式及一個屬性-{{domxref("DragEvent.dataTransfer","dataTransfer")}} 屬性為一個 {{domxref("DataTransfer")}} 物件。{{domxref("DataTransfer")}} 物件包含了拖放事件的狀態,如正在進行的拖放事件類型(例如 copymove)、拖放中的資料(一或多個項目)以及每一個拖放項目(drag item)的檔案類型(MIME type)。{{domxref("DataTransfer")}} 物件也擁有加入及移除拖放資料項目的方法。{{domxref("DragEvent")}} 與 {{domxref("DataTransfer")}} 介面應該是唯一須要加至應用程式中的 HTML 拖放功能。另外,請留意 Firefox 支援了一些 {{anch("Gecko specific interfaces","Gecko-specific 擴充")}}予 {{domxref("DataTransfer")}} 物件使用,雖然這些擴充只能在 Firefox 上作用。

+ +

每個 {{domxref("DataTransfer")}} 物件都包含了 {{domxref("DataTransfer.items","items")}} 屬性。此屬性乃 {{domxref("DataTransferItem")}} 物件的 {{domxref("DataTransferItemList","list")}}。而每個 {{domxref("DataTransferItem")}} 物件,則代表著一個拖放單元,每個拖放單元則擁有代表該資料種類的 {{domxref("DataTransferItem.kind","kind")}} 屬性(stringfile)、還有表示該單元檔案類型(如 MIME)的{{domxref("DataTransferItem.type","type")}} 屬性。另外,{{domxref("DataTransferItem")}} 物件能取得拖放單元的資料。

+ +

{{domxref("DataTransferItemList")}} 物件為 {{domxref("DataTransferItem")}} 的列表。該物件列表擁有以下方法:給列表增加拖放單元、從列表刪除拖放單元、還有清除列表內所有的拖放單元。

+ +

{{domxref("DataTransfer")}} 與 {{domxref("DataTransferItem")}} 介面的最大不同,就是前者使用同步的 {{domxref("DataTransfer.getData","getData()")}} 方法訪問拖放單元的資料;後者則使用非同步的 {{domxref("DataTransferItem.getAsString","getAsString()")}} 方法訪問。

+ +

注意:{{domxref("DragEvent")}} 與 {{domxref("DataTransfer")}} 介面受廣泛的桌面瀏覽器支援。但只有少數瀏覽器支援 {{domxref("DataTransferItem")}} 與 {{domxref("DataTransferItemList")}} 介面。請參見 {{anch("Interoperability")}} 以取得有關拖放功能互通性的資訊。

+ +

Gecko-specific interfaces

+ +

Mozilla and Firefox support some features not in the standard drag and drop model. These are convenience functions to facilitate dragging multiple items and dragging non-string data (such as files). For more information, see Dragging and Dropping Multiple Items. Additionally, see the {{domxref("DataTransfer")}} reference page for all of the Gecko-specific properties and Gecko-specific methods.

+ +

基本用法

+ +

This section provides a summary of the basic steps to add drag and drop functionality to an application. Each section includes a description of the step, a short code example, and links to additional information.

+ +

Identify what is draggable

+ +

To make an element draggable requires adding the {{htmlattrxref("draggable")}} attribute plus the {{domxref("GlobalEventHandlers.ondragstart","ondragstart")}} global event handler, as shown in the following code sample

+ +
function dragstart_handler(ev) {
+ console.log("dragStart");
+ // Add the target element's id to the data transfer object
+ ev.dataTransfer.setData("text/plain", ev.target.id);
+}
+
+<body>
+ <p id="p1" draggable="true" ondragstart="dragstart_handler(event);">This element is draggable.</p>
+</body>
+
+ +

See the draggable attribute reference and the Drag operations guide for more information.

+ +

Define the drag's data

+ +

The application is free to include any number of data items in a drag operation. Each data item is a {{domxref("DOMString","string")}} of a particular type, typically a MIME type such as text/html.

+ +

Each {{domxref("DragEvent","drag event")}} has a {{domxref("DragEvent.dataTransfer","dataTransfer")}} property that holds the event's data. This property (which is a {{domxref("DataTransfer")}} object) also has methods to manage drag data. The {{domxref("DataTransfer.setData","setData()")}} method is used to add an item to the drag data, as shown in the following example.

+ +
function dragstart_handler(ev) {
+  // Add the drag data
+  ev.dataTransfer.setData("text/plain", ev.target.id);
+  ev.dataTransfer.setData("text/html", "<p>Example paragraph</p>");
+  ev.dataTransfer.setData("text/uri-list", "http://developer.mozilla.org");
+}
+
+ +

For a list of common data types used for drag and drop (such as text, HTML, links, and files), see Recommended Drag Types and for more information about drag data, see Drag Data.

+ +

Define the drag image

+ +

By default, the browser supplies an image that appears beside the mouse pointer during a drag operation. However, an application may define a custom image by using the {{domxref("DataTransfer.setDragImage","setDragImage()")}} method as shown in the following example.

+ +
function dragstart_handler(ev) {
+  // Create an image and then use it for the drag image.
+  // NOTE: change "example.gif" to an existing image or the image
+  // will not be created and the default drag image will be used.
+  var img = new Image();
+  img.src = 'example.gif';
+  ev.dataTransfer.setDragImage(img, 10, 10);
+}
+
+ +

To learn more about drag feedback images, see Setting the Drag Feedback Image.

+ +

Define the drag effect

+ +

The {{domxref("DataTransfer.dropEffect","dropEffect")}} property is used to control the feedback (typically visual) the user is given during a drag and drop operation. It affects which cursor the browser displays while dragging. For example, when the user hovers over a target drop element, the browser's cursor may indicate the type of operation that will occur.

+ +

Three effects may be defined:

+ +

copy indicates that the data being dragged will be copied from its present location to the drop location.

+ +

move indicates that the data being dragged will be moved

+ +

link indicates that some form of relationship or connection will be created between the source and drop locations.

+ +

During the drag operation, the drag effects may be modified to indicate that certain effects are allowed at certain locations. If allowed, a drop may occur at that location.

+ +

The following example shows how to use this property.

+ +
function dragstart_handler(ev) {
+  // Set the drag effect to copy
+  ev.dataTransfer.dropEffect = "copy";
+}
+
+ +

See Drag Effects for more details.

+ +

Define a drop zone

+ +

By default, the browser prevents anything from happening when dropping something onto the HTML element. To change that behavior so that an element becomes a drop zone or is droppable, the element must have both {{domxref("GlobalEventHandlers.ondragover","ondragover")}} and {{domxref("GlobalEventHandlers.ondrop","ondrop")}} event handler attributes. The following example shows how to use those attributes and includes basic event handlers for each attribute.

+ +
function dragover_handler(ev) {
+ ev.preventDefault();
+ // Set the dropEffect to move
+ ev.dataTransfer.dropEffect = "move"
+}
+function drop_handler(ev) {
+ ev.preventDefault();
+ // Get the id of the target and add the moved element to the target's DOM
+ var data = ev.dataTransfer.getData("text");
+ ev.target.appendChild(document.getElementById(data));
+}
+<body>
+ <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">Drop Zone</div>
+</body>
+
+ +

Note each handler calls {{domxref("Event.preventDefault","preventDefault()")}} to prevent additional event processing for this prevent (such as touch events or pointer events).

+ +

For more information, see Specifying Drop Targets.

+ +

Handle the drop effect

+ +

The handler for the {{event("drop")}} event is free to process the drag data in an application specific way. Typically, an application will use the {{domxref("DataTransfer.getData","getData()")}} method to retrieve drag items and process them accordingly. Additionally, application semantics may differ depending on the value of the {{domxref("DataTransfer.dropEffect","dropEffect")}} and/or the state of modifier keys.

+ +

The following example shows a drop handler getting the source element's id from the drag data and then using the id to move the source element to the drop element.

+ +
function dragstart_handler(ev) {
+ // Add the target element's id to the data transfer object
+ ev.dataTransfer.setData("text/plain", ev.target.id);
+ ev.dropEffect = "move";
+}
+function dragover_handler(ev) {
+ ev.preventDefault();
+ // Set the dropEffect to move
+ ev.dataTransfer.dropEffect = "move"
+}
+function drop_handler(ev) {
+ ev.preventDefault();
+ // Get the id of the target and add the moved element to the target's DOM
+ var data = ev.dataTransfer.getData("text");
+ ev.target.appendChild(document.getElementById(data));
+}
+<body>
+ <p id="p1" draggable="true" ondragstart="dragstart_handler(event);">This element is draggable.</p>
+ <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">Drop Zone</div>
+</body>
+
+ +

For more information, see Performing a Drop.

+ +

Drag end

+ +

At the end of a drag operation, the {{event("dragend")}} event fires at the source element - the element that was the target of the drag start. This event fires whether the drag completed or was canceled. The {{event("dragend")}} event handler can check the value of the {{domxref("DataTransfer.dropEffect","dropEffect")}} property to determine if the drag operation succeeded or not.

+ +

For more information about handling the end of a drag operation, see Finishing a Drag.

+ +

Interoperability

+ +

As can be seen in the DataTransferItem interface's Browser Compatibility table, drag-and-drop interoperability is relatively broad among desktop browsers (except the {{domxref("DataTransferItem")}} and {{domxref("DataTransferItemList")}} interfaces have less support). This data also indicates drag and drop support among mobile browsers is very low.

+ +

Examples and demos

+ + + +

參見

+ + diff --git a/files/zh-tw/web/api/htmlcanvaselement/index.html b/files/zh-tw/web/api/htmlcanvaselement/index.html new file mode 100644 index 0000000000..fffa314976 --- /dev/null +++ b/files/zh-tw/web/api/htmlcanvaselement/index.html @@ -0,0 +1,262 @@ +--- +title: HTMLCanvasElement +slug: Web/API/HTMLCanvasElement +tags: + - API + - Canvas + - HTML DOM + - Interface + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/API/HTMLCanvasElement +--- +
+
{{APIRef("Canvas API")}}
+
+ +

HTMLCanvasElement 介面提供控制 canvas 元素的屬性和方法. HTMLCanvasElement 介面也繼承了 {{domxref("HTMLElement")}} 介面的屬性和方法.

+ +

{{InheritanceDiagram}}

+ +

屬性

+ +

從父代繼承的屬性,{{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.
+
+ +

方法

+ +

從父代繼承的方法, {{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.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.
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
規範狀態
{{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.
+ +

瀏覽器相容性

+ +
{{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() {{experimental_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() {{experimental_inline}}
{{CompatNo}}{{CompatNo}}{{CompatUnknown}}{{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/zh-tw/web/api/htmlcanvaselement/todataurl/index.html b/files/zh-tw/web/api/htmlcanvaselement/todataurl/index.html new file mode 100644 index 0000000000..7a87309580 --- /dev/null +++ b/files/zh-tw/web/api/htmlcanvaselement/todataurl/index.html @@ -0,0 +1,201 @@ +--- +title: HTMLCanvasElement.toDataURL() +slug: Web/API/HTMLCanvasElement/toDataURL +tags: + - API + - Canvas +translation_of: Web/API/HTMLCanvasElement/toDataURL +--- +
+
+
{{APIRef("Canvas API")}}
+
+
+ +

HTMLCanvasElement.toDataURL() 方法回傳含有圖像和參數設置特定格式的 data URIs (預設 PNG). 回傳的圖像解析度為 96 dpi.

+ + + +

表達式

+ +
canvas.toDataURL(type, encoderOptions);
+
+ +

參數

+ +
+
type {{optional_inline}}
+
圖像格式的 {{domxref("DOMString")}}. 預設為 image/png.
+
encoderOptions {{optional_inline}}
+
表示 image/jpeg 或是 image/webp 的圖像品質, 為0 到 1 之間的 {{jsxref("Number")}}.
+ 如果值不在上述範圍中, 將會使用預設值. 其他的會忽略.
+
+ +

回傳值

+ +

包含 data URI 的 {{domxref("DOMString")}}.

+ +

範例

+ +

創建 {{HTMLElement("canvas")}} 元素:

+ +
<canvas id="canvas" width="5" height="5"></canvas>
+
+ +

可以使用下面的方式獲取 data-URL:

+ +
var canvas = document.getElementById("canvas");
+var dataURL = canvas.toDataURL();
+console.log(dataURL);
+// "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNby
+// blAAAADElEQVQImWNgoBMAAABpAAFEI8ARAAAAAElFTkSuQmCC"
+
+ +

設置圖像的品質

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

範例: 動態改變圖像

+ +

為了動態改變圖像, 可以與滑鼠事件一起使用 (gray-scale versus color in this example):

+ +

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

規範

+ + + + + + + + + + + + + + + + + + + + + + + + +
規範狀態
{{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.
+ +

瀏覽器相容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatChrome(4) }}{{ CompatGeckoDesktop("1.9.2") }}{{ CompatIE(9) }}{{ CompatOpera(9) }}{{ CompatSafari(4.0) }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatAndroid(3.2) }}{{ CompatAndroid(18) }}{{ CompatGeckoMobile("1.9.2") }}{{ CompatVersionUnknown() }}{{ CompatOpera(19) }}{{ CompatSafari(3.0) }}
+
+ +

參見

+ + diff --git a/files/zh-tw/web/api/htmlcollection/index.html b/files/zh-tw/web/api/htmlcollection/index.html new file mode 100644 index 0000000000..dac516a65b --- /dev/null +++ b/files/zh-tw/web/api/htmlcollection/index.html @@ -0,0 +1,95 @@ +--- +title: HTMLCollection +slug: Web/API/HTMLCollection +translation_of: Web/API/HTMLCollection +--- +

{{APIRef("HTML DOM")}}

+ +

HTMLCollection 介面表示了一種成員為 {{domxref("Element")}} 物件的通用集合(如 arguments 一般的類陣列,成員順序同元素在文件中的順序),並提供了可用來選取集合成員的方法與屬性。

+ +
Note: This interface is called HTMLCollection for historical reasons (before DOM4, collections implementing this interface could only have HTML elements as their items).
+ +

HTMLCollection 物件對 HTML DOM 而言具有即時性(live),如果底層的文件(document 物件)發生改變,HTMLCollection 物件會自動更新至最新的狀態。

+ +

屬性

+ +
+
{{domxref("HTMLCollection.length")}} {{readonlyInline}}
+
Returns the number of items in the collection.
+
+ +

方法

+ +
+
{{domxref("HTMLCollection.item()")}}
+
Returns the specific node at the given zero-based index into the list. Returns null if the index is out of range.
+
{{domxref("HTMLCollection.namedItem()")}}
+
Returns the specific node whose ID or, as a fallback, name matches the string specified by name. Matching by name is only done as a last resort, only in HTML, and only if the referenced element supports the name attribute. Returns null if no node exists by the given name.
+
+ +

Usage in JavaScript

+ +

HTMLCollection also exposes its members directly as properties by both name and index. HTML IDs may contain : and . as valid characters, which would necessitate using bracket notation for property access. Currently HTMLCollections does not recognize purely numeric IDs, which would cause conflict with the array-style access, though HTML5 does permit these.

+ +

For example, assuming there is one <form> element in the document and its id is "myForm":

+ +
var elem1, elem2;
+
+// document.forms is an HTMLCollection
+
+elem1 = document.forms[0];
+elem2 = document.forms.item(0);
+
+alert(elem1 === elem2); // shows: "true"
+
+elem1 = document.forms.myForm;
+elem2 = document.forms.namedItem("myForm");
+
+alert(elem1 === elem2); // shows: "true"
+
+elem1 = document.forms["named.item.with.periods"];
+ +

瀏覽器相容性

+ +

Different browsers behave differently when there are more than one elements matching the string used as an index (or namedItem's argument). Firefox 8 behaves as specified in DOM 2 and DOM4, returning the first matching element. WebKit browsers and Internet Explorer in this case return another HTMLCollection and Opera returns a {{domxref("NodeList")}} of all matching elements.

+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#htmlcollection', 'HTMLCollection')}}{{ Spec2('DOM WHATWG') }} 
{{SpecName('DOM4', '#htmlcollection', 'HTMLCollection')}}{{ Spec2('DOM4') }} 
{{SpecName('DOM2 HTML', 'html.html#ID-75708506', 'HTMLCollection')}}{{ Spec2('DOM2 HTML') }} 
{{SpecName('DOM1', 'level-one-html.html#ID-75708506', 'HTMLCollection')}}{{ Spec2('DOM1') }}Initial definition.
+ +

參見

+ + diff --git a/files/zh-tw/web/api/htmldataelement/index.html b/files/zh-tw/web/api/htmldataelement/index.html new file mode 100644 index 0000000000..56e15b834d --- /dev/null +++ b/files/zh-tw/web/api/htmldataelement/index.html @@ -0,0 +1,59 @@ +--- +title: HTMLDataElement +slug: Web/API/HTMLDataElement +translation_of: Web/API/HTMLDataElement +--- +
{{APIRef("HTML DOM")}}
+ +

The HTMLDataElement interface provides special properties (beyond the regular {{domxref("HTMLElement")}} interface it also has available to it by inheritance) for manipulating {{HTMLElement("data")}} elements.

+ +

{{InheritanceDiagram(600, 120)}}

+ +

屬性

+ +

從它的父繼承屬性, {{domxref("HTMLElement")}}.

+ +
+
{{domxref("HTMLDataElement.value")}}
+
Is a {{domxref("DOMString")}} reflecting the {{htmlattrxref("value", "data")}} HTML attribute, containing a machine-readable form of the element's value.
+
+ +

方法

+ +

無具體的方法; 從它的父繼承, {{domxref("HTMLElement")}}.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "#htmldataelement", "HTMLDataElement")}}{{Spec2('HTML WHATWG')}} 
{{SpecName('HTML5 W3C', 'text-level-semantics.html#the-data-element', 'HTMLDataElement')}}{{Spec2('HTML5 W3C')}} 
+ +

Browser compatibility

+ +
+ + +

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

+
+ +

See also

+ + diff --git a/files/zh-tw/web/api/htmldocument/index.html b/files/zh-tw/web/api/htmldocument/index.html new file mode 100644 index 0000000000..7317d54508 --- /dev/null +++ b/files/zh-tw/web/api/htmldocument/index.html @@ -0,0 +1,16 @@ +--- +title: HTMLDocument +slug: Web/API/HTMLDocument +translation_of: Web/API/HTMLDocument +--- +

{{ APIRef("HTML DOM") }}

+ +

HTMLDocument 是一個關於 {{domxref("Document_Object_Model", "DOM")}} 的抽象介面,提供了 {{domxref("Document")}} 定義之外的 XML 文件屬性及方法,以用來操作 HTML。

+ +

window.document 為 HTMLDocument 的物件實體,HTMLDocument 所有屬性與方法的說明已包含在 Document 頁面。由於現在的 HTMLDocument 是透過了綁定轉型(binding-specific casting)的方式來運作,所以 HTMLDocument 已不再是繼承 Document

+ +

規範

+ + diff --git a/files/zh-tw/web/api/htmlelement/click/index.html b/files/zh-tw/web/api/htmlelement/click/index.html new file mode 100644 index 0000000000..123206ca2f --- /dev/null +++ b/files/zh-tw/web/api/htmlelement/click/index.html @@ -0,0 +1,115 @@ +--- +title: HTMLElement.click() +slug: Web/API/HTMLElement/click +translation_of: Web/API/HTMLElement/click +--- +
+
{{ APIRef("HTML DOM") }}
+
+ +

HTMLElement.click() 方法可以模擬滑鼠點擊一個元素。

+ +

click() 被使用在支援的元素(例如任一 {{HTMLElement("input")}} 元素),便會觸發該元素的點擊事件。事件會冒泡至 document tree(或 event chain)的上層元素,並觸發它們的點擊事件。其中的例外是:click() 方法不會讓 {{HTMLElement("a")}} 元素和接收到真實滑鼠點擊一樣進行頁面跳轉。

+ +

語法

+ +
elt.click()
+ +

規範

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM2 HTML', 'html.html#ID-2651361')}}{{Spec2('DOM2 HTML')}}Initial definition
+ +

瀏覽器相容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support20[3]{{CompatVersionUnknown}}5[1]{{CompatVersionUnknown}}{{CompatVersionUnknown}}[2]6[3]
input@file (limited){{CompatVersionUnknown}}{{CompatVersionUnknown}}4{{CompatVersionUnknown}}12.10{{CompatVersionUnknown}}
input@file (full){{CompatVersionUnknown}}{{CompatVersionUnknown}}4{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Prior to Gecko 5.0 {{geckoRelease("5.0")}}, Gecko would not implement the click() method on other elements that might be expected to respond to mouse clicks, such as links ({{HTMLElement("a")}} elements), nor would it necessarily fire the click event of other elements.

+ +

[2] In Presto-based versions of Opera, the click() method will be silently ignored if made on an {{HTMLElement("input")}} with its type attribute set to file and its CSS {{cssxref('display')}} property set to none.

+ +

[3] Older versions had HTMLInputElement.click(), and HTMLButtonElement.click() only.

diff --git a/files/zh-tw/web/api/htmlelement/dataset/index.html b/files/zh-tw/web/api/htmlelement/dataset/index.html new file mode 100644 index 0000000000..690f8e1189 --- /dev/null +++ b/files/zh-tw/web/api/htmlelement/dataset/index.html @@ -0,0 +1,167 @@ +--- +title: HTMLElement.dataset +slug: Web/API/HTMLElement/dataset +translation_of: Web/API/HTMLOrForeignElement/dataset +--- +

{{ APIRef("HTML DOM") }}

+ +

HTMLElement.dataset 允許在讀取與寫入模式時使用HTML或DOM裡,所有設置在元件上的自定義資料屬性(data-*)。他是一個DOMStringMap,每個項目表示一個不同的資料屬性。須注意的是,資料集(dataset)可以被讀取,但不能直接被修改。所有修改必須經由其眾多"屬性"才行,也就是資料屬性。另外,雖然HTML data- 屬性與它相關的 DOM dataset. 名稱不同,但是他們總是有相似之處: 

+ + + +

除了以下的資訊之外,你也可以在 Using data attributes.此篇文章找到使用HTML資料屬性的用法。

+ +

名稱變換

+ +

 

+ +

dash-style 到 camelCase: 將自訂義的資料屬性名稱變換至{{ domxref("DOMStringMap") }}各項目的key值,需根據以下規則:

+ + + +

camelCase 到 dash-style: 與上述相反,將key值轉為資料屬性名稱,需根據以下規則:

+ + + +

上面所提的限制是為了確保兩個轉換方法互為相反。

+ +

舉例來說,資料屬性名稱 data-abc-def 之對應key值為abcDef

+ +

 

+ +

存取數值

+ + + +

語法

+ + + +

範例

+ +
<div id="user" data-id="1234567890" data-user="johndoe" data-date-of-birth>John Doe</div>
+
+let el = document.querySelector('#user');
+
+// el.id == 'user'
+// el.dataset.id === '1234567890'
+// el.dataset.user === 'johndoe'
+// el.dataset.dateOfBirth === ''
+
+el.dataset.dateOfBirth = '1960-10-03'; // 設定 DOB.
+
+// 'someDataAttr' in el.dataset === false
+el.dataset.someDataAttr = 'mydata';
+// 'someDataAttr' in el.dataset === true
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + +
規範狀態備註
{{SpecName('HTML WHATWG', "dom.html#dom-dataset", "HTMLElement.dataset")}}{{Spec2('HTML WHATWG')}}No change from latest snapshot, {{SpecName('HTML5.1')}}
{{SpecName('HTML5.1', "dom.html#dom-dataset", "HTMLElement.dataset")}}{{Spec2('HTML5.1')}}Snapshot of {{SpecName('HTML WHATWG')}}, no change from {{SpecName('HTML5 W3C')}}
{{SpecName('HTML5 W3C', "dom.html#dom-dataset", "HTMLElement.dataset")}}{{Spec2('HTML5 W3C')}}Snapshot of  {{SpecName('HTML WHATWG')}}, initial definition.
+ +

瀏覽器相容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
功能ChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
基本支援8{{CompatVersionUnknown}}{{ CompatGeckoDesktop("6.0") }}1111.106
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
功能AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
基本支援{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile(6)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

參見

+ + diff --git a/files/zh-tw/web/api/htmlelement/index.html b/files/zh-tw/web/api/htmlelement/index.html new file mode 100644 index 0000000000..f0b3eb55e0 --- /dev/null +++ b/files/zh-tw/web/api/htmlelement/index.html @@ -0,0 +1,447 @@ +--- +title: HTMLElement +slug: Web/API/HTMLElement +translation_of: Web/API/HTMLElement +--- +
+
{{ APIRef("HTML DOM") }}
+
+ +
 
+ +

HTMLElement 介面表示了所有的 HTML 元素。部分元素直接實作了此介面,其它則是實作繼承自 HTMLElement 的子介面。

+ +

{{InheritanceDiagram}}

+ +

屬性

+ +

Inherits properties from its parent, {{domxref("Element")}}, and implements those from {{domxref("GlobalEventHandlers")}} and {{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 a {{domxref("HTMLMenuElement")}} representing the contextual menu associated with the element. It may be null.
+
{{domxref("HTMLElement.dataset")}} {{readonlyInline}}
+
Returns a {{domxref("DOMStringMap")}} with which script can read and write the element's 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")}} representing the item scope.
+
{{domxref("HTMLElement.itemType")}} {{readonlyInline}}{{experimental_inline}}
+
Returns a {{domxref("DOMSettableTokenList")}}…
+
{{domxref("HTMLElement.itemId")}} {{experimental_inline}}
+
Is a {{domxref("DOMString")}} representing the item ID.
+
{{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 a {{jsxref("Object")}} representing the item value.
+
{{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 a {{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 a {{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 doesn't have an effect on all of them.
+
{{domxref("HTMLElement.style")}}
+
Is a {{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")}} representing the translation.
+
+ +

事件處理器

+ +

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

方法

+ +

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}}
+
Runs the spell checker on the element's contents.
+
+ +

規範

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

瀏覽器相容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureFirefox (Gecko)ChromeEdgeInternet ExplorerOperaSafari
Basic support{{CompatGeckoDesktop("1.0")}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
{{domxref("HTMLElement.accessKey", "accessKey")}}{{CompatGeckoDesktop("5.0")}}17.0{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}6.0
{{domxref("HTMLElement.accessKeyLabel", "accessKeyLabel")}}{{CompatGeckoDesktop("8.0")}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatNo}}{{WebkitBug(72715)}}
{{domxref("HTMLElement.blur()", "blur()")}}{{CompatGeckoDesktop("5.0")}}{{CompatUnknown}}{{CompatVersionUnknown}}9{{CompatUnknown}}{{CompatUnknown}}
{{domxref("HTMLElement.click()", "click()")}}{{CompatGeckoDesktop("5.0")}}{{CompatUnknown}}9{{CompatVersionUnknown}}9{{CompatUnknown}}6.0
{{domxref("HTMLElement.dataset", "dataset")}}{{CompatGeckoDesktop("6.0")}}8{{CompatVersionUnknown}}1111.105.1
{{domxref("HTMLElement.focus()", "focus()")}}{{CompatGeckoDesktop("5.0")}}{{CompatUnknown}}{{CompatVersionUnknown}}9{{CompatUnknown}}{{CompatUnknown}}
{{domxref("HTMLElement.contentEditable", "contentEditable")}}{{CompatGeckoDesktop("1.9")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}5.59{{CompatVersionUnknown}}
{{domxref("HTMLElement.spellcheck", "spellcheck")}}{{CompatGeckoDesktop("1.8.1")}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
{{domxref("HTMLElement.style", "style")}}{{CompatVersionUnknown}} (returns a {{domxref("CSS2Properties")}}, rather than a {{domxref("CSSStyleDeclaration")}}){{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
{{domxref("HTMLElement.forceSpellCheck", "forceSpellCheck()")}} {{experimental_inline}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
{{domxref("HTMLElement.draggable", "draggable")}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}12.0{{CompatUnknown}}
{{domxref("HTMLElement.dropzone", "dropzone")}}{{CompatNo}}{{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}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}
{{domxref("HTMLElement.translate", "translate")}} {{experimental_inline}}{{CompatNo}}{{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}}{{CompatNo}}11.60
+ (Removed in Opera 15)
{{CompatNo}}
{{domxref("HTMLElement.properties", "properties")}} {{experimental_inline}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatNo}}{{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}}{{CompatNo}}{{CompatUnknown}}{{CompatVersionUnknown}}
{{domxref("HTMLElement.oncopy")}}, {{domxref("HTMLElement.oncut")}}, and {{domxref("HTMLElement.onpaste")}} {{Non-standard_inline}}{{CompatGeckoDesktop("1.9")}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureFirefox Mobile (Gecko)AndroidEdgeIE MobileOpera MobileSafari Mobile
Basic support +

{{CompatGeckoMobile("1.0")}}

+
{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
{{domxref("HTMLElement.accessKey", "accessKey")}}{{CompatGeckoMobile("5.0")}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
{{domxref("HTMLElement.accessKeyLabel", "accessKeyLabel")}}{{CompatGeckoMobile("8.0")}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
{{domxref("HTMLElement.blur()", "blur()")}}{{CompatGeckoMobile("5.0")}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
{{domxref("HTMLElement.click()", "click()")}}{{CompatGeckoMobile("5.0")}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
{{domxref("HTMLElement.dataset", "dataset")}}{{CompatGeckoMobile("6.0")}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
{{domxref("HTMLElement.focus()", "focus()")}}{{CompatGeckoMobile("5.0")}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
{{domxref("HTMLElement.oncopy")}}, {{domxref("HTMLElement.oncut")}}, and {{domxref("HTMLElement.onpaste")}} {{Non-standard_inline}}{{CompatGeckoMobile("1.9")}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

參見

+ + diff --git a/files/zh-tw/web/api/htmlelement/lang/index.html b/files/zh-tw/web/api/htmlelement/lang/index.html new file mode 100644 index 0000000000..ff546e3ca9 --- /dev/null +++ b/files/zh-tw/web/api/htmlelement/lang/index.html @@ -0,0 +1,59 @@ +--- +title: HTMLElement.lang +slug: Web/API/HTMLElement/lang +tags: + - API + - HTML DOM + - HTMLElement + - NeedsBrowserCompatibility + - NeedsUpdate + - Property + - Reference +translation_of: Web/API/HTMLElement/lang +--- +
{{ APIRef("HTML DOM") }}
+ +

HTMLElement.lang 屬性({{Glossary("property")}})可以讀取或設定一個表示元素之語系的標籤屬性({{Glossary("attribute")}})值。

+ +

HTMLElement.lang 屬性所回傳的語系代碼定義於網際網路工程任務小組(IETF)的 Tags for Identifying Languages (BCP47) 文件中。常見的例子如 "en" 代表英語、"ja" 代表日語、"es" 代表西班牙語等等。此標籤屬性的預設值為 unknown。請留意,雖然此標籤屬性於個別層級的元素上是有效的,但大部分都設定於文件的根元素。

+ +

HTMLElement.lang 屬性只對 lang 標籤屬性有作用,而不是 xml:lang

+ +

語法

+ +
var languageUsed = elementNodeReference.lang; // Get the value of lang
+elementNodeReference.lang = NewLanguage; // Set new value for lang
+
+ +

languageUsed is a string variable that gets the language in which the text of the current element is written. NewLanguage is a string variable with its value setting the language in which the text of the current element is written.

+ +

範例

+ +
// 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";
+}
+ +

規範

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM2 HTML', 'html.html#ID-59132807', 'lang')}}{{Spec2('DOM2 HTML')}} 
+ +

 

diff --git a/files/zh-tw/web/api/htmlelement/style/index.html b/files/zh-tw/web/api/htmlelement/style/index.html new file mode 100644 index 0000000000..e9e6d1171a --- /dev/null +++ b/files/zh-tw/web/api/htmlelement/style/index.html @@ -0,0 +1,79 @@ +--- +title: HTMLElement.style +slug: Web/API/HTMLElement/style +translation_of: Web/API/ElementCSSInlineStyle/style +--- +
{{ APIRef("HTML DOM") }}
+ +

The HTMLElement.style property is used to get as well as set the inline style of an element. While getting, it returns a CSSStyleDeclaration object that contains a list of all styles properties for that element with values assigned for the attributes that are defined in the element's inline style attribute. See the CSS Properties Reference for a list of the CSS properties accessible via style.The style property has the same (and highest) priority in the CSS cascade as an inline style declaration set via the style attribute.

+ +

設定 styles

+ +

Styles can be set by assigning a string directly to the style property (as in elt.style = "color: blue;") or by assigning values to the properties of style. For adding specific styles to an element without altering other style values, it is preferred to use the individual properties of style (as in elt.style.color = '...' ) as using elt.style.cssText = '...' or elt.setAttribute('style', '...') sets the complete inline style for the element by overriding the existing inline styles. Note that the property names are in camel-case and not kebab-case while setting the style using elt.style.<property> (i.e. elt.style.fontSize, not elt.style.font-size)

+ +

範例

+ +
// Set multiple styles in a single statement
+elt.style.cssText = "color: blue; border: 1px solid black";
+// OR
+elt.setAttribute("style", "color:red; border: 1px solid blue;");
+
+
+elt.style.color = "blue";  // Set specific style while leaving other inline style values untouched
+
+ +

取得樣式資訊

+ +

The style property is not useful for completely learning about the styles applied on the element, since it represents only the CSS declarations set in the element's inline style attribute, not those that come from style rules elsewhere, such as style rules in the {{HTMLElement("head")}} section, or external style sheets. To get the values of all CSS properties for an element you should use {{domxref("window.getComputedStyle()")}} instead.

+ +

The following code snippet demonstrates the difference between the values obtained using the element's style property and that obtained using the computedStyle() method:

+ +
<!DOCTYPE HTML>
+<html>
+ <body style="font-weight:bold;">
+
+    <div style="color:red" id="myElement">..</div>
+
+ </body>
+</html>
+
+ +
var element = document.getElementById("myElement");
+var out = "";
+var elementStyle = element.style;
+var computedStyle = window.getComputedStyle(element, null);
+
+for (prop in elementStyle) {
+  if (elementStyle.hasOwnProperty(prop)) {
+    out += "  " + prop + " = '" + elementStyle[prop] + "' > '" + computedStyle[prop] + "'\n";
+  }
+}
+console.log(out)
+
+ +

The output would be something like:

+ +
...
+fontWeight = '' > 'bold'
+color = 'red' > 'rgb(255, 0, 0)'
+...
+ +

Note the presence of the value "bold" for font-weight in the computed style and the absence of it in the element's style property

+ +

規範

+ +

DOM Level 2 Style: ElementCSSInlineStyle.style

+ +

瀏覽器相容性

+ +
+

Note: Starting in {{Gecko("2.0")}}, you can set SVG properties' values using the same shorthand syntax. For example:

+ +
element.style.fill = 'lime';
+
+ +

參見

+ + diff --git a/files/zh-tw/web/api/htmlformelement/index.html b/files/zh-tw/web/api/htmlformelement/index.html new file mode 100644 index 0000000000..614eebbad2 --- /dev/null +++ b/files/zh-tw/web/api/htmlformelement/index.html @@ -0,0 +1,245 @@ +--- +title: HTMLFormElement +slug: Web/API/HTMLFormElement +translation_of: Web/API/HTMLFormElement +--- +
{{APIRef("HTML DOM")}}
+ +

HTMLFormElement 介面提供了建立及修改 {{HTMLElement("form")}} 元素的方法。
+ document.forms - returns an array of HTMLFormElement objects referencing all forms on the page.
+ document.forms[index] - returns an HTMLFormElement object referencing the form at the specified index.
+ document.forms['id'] - returns an HTMLFormElement object referencing the form with the specified id.
+ document.forms['name'] - returns an HTMLFormElement object referencing the form with the specified name.

+ +

{{InheritanceDiagram(600,120)}}

+ +

屬性

+ +

This interface also inherits properties from its parent, {{domxref("HTMLElement")}}.

+ +
+
{{domxref("HTMLFormElement.elements")}}{{ReadOnlyInline}}
+
A {{domxref("HTMLFormControlsCollection")}} holding all form controls belonging to this form element.
+
{{domxref("HTMLFormElement.length")}}{{ReadOnlyInline}}
+
A long reflecting the number of controls in the form.
+
{{domxref("HTMLFormElement.name")}}
+
A {{domxref("DOMString")}} reflecting the value of the form's {{ htmlattrxref("name", "form") }} HTML attribute, containing the name of the form.
+
{{domxref("HTMLFormElement.method")}}
+
A {{domxref("DOMString")}} reflecting the value of the form's {{ htmlattrxref("method", "form") }} HTML attribute, indicating the HTTP method used to submit the form. Only specified values can be set.
+
{{domxref("HTMLFormElement.target")}}
+
A {{domxref("DOMString")}} reflecting the value of the form's {{ htmlattrxref("target", "form") }} HTML attribute, indicating where to display the results received from submitting the form.
+
{{domxref("HTMLFormElement.action")}}
+
A {{domxref("DOMString")}} reflecting the value of the form's {{ htmlattrxref("action", "form") }} HTML attribute, containing the URI of a program that processes the information submitted by the form.
+
{{domxref("HTMLFormElement.encoding")}} or {{domxref("HTMLFormElement.enctype")}}
+
A {{domxref("DOMString")}} reflecting the value of the form's {{ htmlattrxref("enctype", "form") }} HTML attribute, indicating the type of content that is used to transmit the form to the server. Only specified values can be set. The two methods are synonyms.
+
{{domxref("HTMLFormElement.acceptCharset")}}
+
A {{domxref("DOMString")}} reflecting the value of the form's {{ htmlattrxref("accept-charset", "form") }} HTML attribute, representing the character encoding that the server accepts.
+
{{domxref("HTMLFormElement.autocomplete")}}
+
A {{domxref("DOMString")}} reflecting the value of the form's {{ htmlattrxref("autocomplete", "form") }} HTML attribute, indicating whether the controls in this form can have their values automatically populated by the browser.
+
{{domxref("HTMLFormElement.noValidate")}}
+
A {{jsxref("Boolean")}} reflecting the value of the form's {{ htmlattrxref("novalidate", "form") }} HTML attribute, indicating whether the form should not be validated.
+
+ +

方法

+ +

This interface also inherits methods from its parent, {{domxref("HTMLElement")}}.

+ +
+
{{domxref("HTMLFormElement.submit()")}}
+
Submits the form to the server.
+
{{domxref("HTMLFormElement.reset()")}}
+
Resets the form to its initial state.
+
{{domxref("HTMLFormElement.checkValidity()")}}
+
Returns true if the element's child controls are subject to constraint validation and satisfy those contraints; returns false if some controls do not satisfy their constraints. Fires an event named {{event("invalid")}} at any control that does not satisfy its constraints; such controls are considered invalid if the event is not canceled. It is up to the programmer to decide how to respond to false.
+
{{domxref("HTMLFormElement.reportValidity()")}}
+
Returns true if the element's child controls satisfy their validation constraints. When false is returned, cancelable {{Event("invalid")}} events are fired for each invalid child and validation problems are reported to the user.
+
{{domxref("HTMLFormElement.requestAutocomplete()")}}
+
Triggers a native browser interface to assist the user in completing the fields which have an autofill field name value that is not off or on. The form will receive an event once the user has finished with the interface, the event will either be {{event("autocomplete")}} when the fields have been filled or {{event("autocompleteerror")}} when there was a problem.
+
+ +

範例

+ +

Create a new form element, modify its attributes and submit it:

+ +
var f = document.createElement("form");// Create a form
+document.body.appendChild(f);          // Add it to the document body
+f.action = "/cgi-bin/some.cgi";        // Add action and method attributes
+f.method = "POST"
+f.submit();                            // Call the form's submit method
+
+ +

Extract information from a form element and set some of its attributes:

+ +
<form name="formA" id="formA" action="/cgi-bin/test" method="POST">
+ <p>Click "Info" for form details; "Set" to change settings.</p>
+ <p>
+  <input type="button" value="info" onclick="getFormInfo();">
+  <input type="button" value="set"  onclick="setFormInfo(this.form);">
+  <input type="reset" value="reset"><br>
+  <textarea id="tex" style="height:15em; width:20em"></textarea>
+ </p>
+</form>
+
+<script type="text/javascript">
+  function getFormInfo(){
+    var info;
+    var f = document.forms["formA"]; //Get a reference to the form via id.
+    info = "elements: " + f.elements     + "\n"
+         + "length: "   + f.length       + "\n"
+         + "name: "     + f.name         + "\n"
+         + "charset: "  + f.acceptCharset+ "\n"
+         + "action: "   + f.action       + "\n"
+         + "enctype: "  + f.enctype      + "\n"
+         + "encoding: " + f.encoding     + "\n"
+         + "method: "   + f.method       + "\n"
+         + "target: "   + f.target;
+    document.forms["formA"].elements['tex'].value = info;
+  }
+  function setFormInfo(f){ //Argument is a reference to the form.
+    f.method = "GET";
+    f.action = "/cgi-bin/evil_executable.cgi";
+    f.name   = "totally_new";
+  }
+</script>
+
+ +

Submit a form in a popup window:

+ +
<!doctype html>
+<html>
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
+<title>MDN Example</title>
+<script type="text/javascript">
+function popupSend (oFormElement) {
+  if (oFormElement.method && oFormElement.method.toLowerCase() !== "get") {
+    console.error("This script supports the GET method only.");
+    return;
+  }
+  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);
+    }
+  }
+  open(oFormElement.action.replace(/(?:\?.*)?$/, sSearch.replace(/^&/, "?")), "submit-" + (oFormElement.name || Math.floor(Math.random() * 1e6)), "resizable=yes,scrollbars=yes,status=yes");
+}
+</script>
+
+</head>
+
+<body>
+
+<form name="yourForm" action="test.php" method="get" onsubmit="popupSend(this); return false;">
+  <p>First name: <input type="text" name="firstname" /><br />
+  Last name: <input type="text" name="lastname" /><br />
+  Password: <input type="password" name="pwd" /><br />
+  <input type="radio" name="sex" value="male" /> Male <input type="radio" name="sex" value="female" /> Female</p>
+  <p><input type="checkbox" name="vehicle" value="Bike" />I have a bike<br />
+  <input type="checkbox" name="vehicle" value="Car" />I have a car</p>
+  <p><input type="submit" value="Submit" /></p>
+</form>
+
+</body>
+</html>
+ +

使用 XMLHttpRequest 提交表單及上傳檔案

+ +

If you want to know how to serialize and submit a form using the {{domxref("XMLHttpRequest")}} API, please read this paragraph.

+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "forms.html#the-form-element", "HTMLFormElement")}}{{Spec2('HTML WHATWG')}}The following method has been added: requestAutocomplete().
{{SpecName('HTML5 W3C', "forms.html#the-form-element", "HTMLFormElement")}}{{Spec2('HTML5 W3C')}}The elements properties returns an {{domxref("HTMLFormControlsCollection")}} instead of a raw {{domxref("HTMLCollection")}}. This is mainly a technical change. The following method has been added: checkValidity(). The following properties have been added: autocomplete, noValidate, and encoding.
{{SpecName('DOM2 HTML', 'html.html#ID-40002357', 'HTMLFormElement')}}{{Spec2('DOM2 HTML')}}No change
{{SpecName('DOM1', 'level-one-html.html#ID-40002357', 'HTMLFormElement')}}{{Spec2('DOM1')}}Initial definition
+ +

瀏覽器相容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop(1.0)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile(1.0)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

參見

+ + diff --git a/files/zh-tw/web/api/htmlformelement/submit_event/index.html b/files/zh-tw/web/api/htmlformelement/submit_event/index.html new file mode 100644 index 0000000000..6c5b030f7c --- /dev/null +++ b/files/zh-tw/web/api/htmlformelement/submit_event/index.html @@ -0,0 +1,60 @@ +--- +title: submit +slug: Web/API/HTMLFormElement/submit_event +translation_of: Web/API/HTMLFormElement/submit_event +--- +

submit 事件會在表單送出時觸發。

+ +

要注意的是,submit 事件只會form element 上觸發, button 或是 submit input 則不會觸發。(送出的是「表單」,而非「按鈕」)

+ +

基本資料

+ +
+
定義規範
+
HTML5
+
Interface
+
{{domxref("Event")}}
+
Bubbles
+
是 
+ 雖說在規範上這是個不 bubble 的事件
+
Cancelable
+
+
Target
+
Element
+
默認行動
+
修改(傳送表單內容至伺服器)。
+
+ +

屬性

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
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}}{{jsxref("Boolean")}}Whether the event normally bubbles or not.
cancelable {{readonlyInline}}{{jsxref("Boolean")}}Whether the event is cancellable or not.
diff --git a/files/zh-tw/web/api/htmlimageelement/index.html b/files/zh-tw/web/api/htmlimageelement/index.html new file mode 100644 index 0000000000..0bf5e96953 --- /dev/null +++ b/files/zh-tw/web/api/htmlimageelement/index.html @@ -0,0 +1,408 @@ +--- +title: HTMLImageElement +slug: Web/API/HTMLImageElement +translation_of: Web/API/HTMLImageElement +--- +
{{APIRef("HTML DOM")}}
+ +

HTMLImageElement 介面提供了特殊的屬性及方法以用來操作 {{HTMLElement("img")}} 元素的畫面佈局與外觀呈現。

+ +

{{InheritanceDiagram(600,120)}}

+ +

屬性

+ +

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

+ +
+
{{domxref("HTMLImageElement.align")}} {{obsolete_inline}}
+
Is a {{domxref("DOMString")}} indicating the alignment of the image with respect to the surrounding context.
+
{{domxref("HTMLImageElement.alt")}}
+
Is a {{domxref("DOMString")}} that reflects the {{htmlattrxref("alt", "img")}} HTML attribute,  thus indicating fallback context for the image.
+
{{domxref("HTMLImageElement.border")}} {{obsolete_inline}}
+
Is a {{domxref("DOMString")}} that is responsible for the width of the border surrounding the image. This is now deprecated and the CSS {{cssxref("border")}} property should be used instead.
+
{{domxref("HTMLImageElement.complete")}} {{readonlyInline}}
+
Returns a {{domxref("Boolean")}} that is true if the browser has finished fetching the image, whether successful or not. It also shows true, if the image has no {{domxref("HTMLImageElement.src", "src")}} value.
+
{{domxref("HTMLImageElement.crossOrigin")}}
+
Is a {{domxref("DOMString")}} representing the CORS setting for this image element. See CORS settings attributes for further details.
+
{{domxref("HTMLImageElement.currentSrc")}} {{readonlyInline}}{{experimental_inline}}
+
Returns a {{domxref("DOMString")}} representing the URL to the currently displayed image (which may change, for example in response to media queries).
+
{{domxref("HTMLImageElement.height")}}
+
一個反映了 HTML img 元素之 {{htmlattrxref("height", "img")}} 屬性的無符號(unsigned)整數,表示圖片經渲染後的高度(CSS pixels)。
+
{{domxref("HTMLImageElement.hspace")}} {{obsolete_inline}}
+
Is a long representing the space on either side of the image.
+
{{domxref("HTMLImageElement.isMap")}}
+
Is a {{domxref("Boolean")}} that reflects the {{htmlattrxref("ismap", "img")}} HTML attribute, indicating that the image is part of a server-side image map.
+
{{domxref("HTMLImageElement.longDesc")}} {{obsolete_inline}}
+
Is a {{domxref("DOMString")}} representing the URI of a long description of the image.
+
{{domxref("HTMLImageElement.lowSrc")}} {{obsolete_inline}}
+
Is a {{domxref("DOMString")}} that refers to a low-quality (but faster to load) copy of the image.
+
{{domxref("HTMLImageElement.name")}} {{obsolete_inline}}
+
Is a {{domxref("DOMString")}} representing the name of the element.
+
{{domxref("HTMLImageElement.naturalHeight")}} {{readonlyInline}}
+
回傳一個代表圖片固有高度(CSS pixels)的無符號(unsigned)整數,如果無法取得則回傳 0
+
{{domxref("HTMLImageElement.naturalWidth")}} {{readonlyInline}}
+
回傳一個代表圖片固有寬度(CSS pixels)的無符號(unsigned)整數,如果無法取得則回傳 0
+
{{domxref("HTMLImageElement.referrerPolicy")}} {{experimental_inline}}
+
Is a {{domxref("DOMString")}} that reflects the {{htmlattrxref("referrerpolicy", "img")}} HTML attribute indicating which referrer to use in order to fetch the image.
+
{{domxref("HTMLImageElement.src")}}
+
Is a {{domxref("DOMString")}} that reflects the {{htmlattrxref("src", "img")}} HTML attribute, containing the full URL of the image including base URI.
+
{{domxref("HTMLImageElement.sizes")}} {{experimental_inline}}
+
Is a {{domxref("DOMString")}} reflecting the {{htmlattrxref("sizes", "img")}} HTML attribute.
+
{{domxref("HTMLImageElement.srcset")}} {{experimental_inline}}
+
Is a {{domxref("DOMString")}} reflecting the {{htmlattrxref("srcset", "img")}} HTML attribute, containing a list of candidate images, separated by a comma (',', U+002C COMMA). A candidate image is a URL followed by a 'w' with the width of the images, or an 'x' followed by the pixel density.
+
{{domxref("HTMLImageElement.useMap")}}
+
Is a {{domxref("DOMString")}} that reflects the {{htmlattrxref("usemap", "img")}} HTML attribute, containing a partial URL of a map element.
+
{{domxref("HTMLImageElement.vspace")}} {{obsolete_inline}}
+
Is a long representing the space above and below the image.
+
{{domxref("HTMLImageElement.width")}}
+
一個反映了 HTML img 元素之 {{htmlattrxref("width", "img")}} 屬性的無符號(unsigned)整數,表示圖片經渲染後的寬度(CSS pixels)。
+
{{domxref("HTMLImageElement.x")}} {{readonlyInline}}{{experimental_inline}}
+
Returns a long representing the horizontal offset from the nearest layer. This property mimics an old Netscape 4 behavior.
+
{{domxref("HTMLImageElement.y")}} {{readonlyInline}} {{experimental_inline}}
+
Returns a long representing the vertical offset from the nearest layer. This property is also similar to behavior of an old Netscape 4.
+
+ +

方法

+ +

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

+ +
+
{{domxref("HTMLImageElement.Image()", "Image()")}}
+
The Image() constructor, taking two optional unsigned long, which are the width and the height of the resource, creates an instance of HTMLImageElement , not inserted in a DOM tree.
+
+ +

Errors

+ +

If an error occurs while trying to load or render the image, and an {{htmlattrxref("onerror")}} event handler has been configured to handle the {{event("error")}} event, that event handler will get called. This can happen in a number of situations, including:

+ + + +

範例

+ +
var img1 = new Image(); // HTML5 Constructor
+img1.src = 'image1.png';
+img1.alt = 'alt';
+document.body.appendChild(img1);
+
+var img2 = document.createElement('img'); // use DOM HTMLImageElement
+img2.src = 'image2.jpg';
+img2.alt = 'alt text';
+document.body.appendChild(img2);
+
+// using first image in the document
+alert(document.images[0].src);
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Referrer Policy', '#referrer-policy-delivery-referrer-attribute', 'referrer attribute')}}{{Spec2('Referrer Policy')}}Added the referrerPolicy property.
{{SpecName("CSSOM View", "#excensions-to-the-htmlimageelement-interface", "Extensions to HTMLImageElement")}}{{Spec2('CSSOM View')}}Added the x and y properties.
{{SpecName('HTML WHATWG', "embedded-content.html#the-img-element", "HTMLImageElement")}}{{Spec2('HTML WHATWG')}}The following properties have been added: srcset, currentSrc and sizes.
{{SpecName('HTML5 W3C', "embedded-content-0.html#the-img-element", "HTMLImageElement")}}{{Spec2('HTML5 W3C')}}A constructor (with 2 optional parameters) has been added.
+ The following properties are now obsolete: name, border, align, hspace, vspace, and longdesc.
+ The following properties are now unsigned long, instead of long: height, and width.
+ The following properties have been added: crossorigin, naturalWidth, naturalHeight, and complete.
{{SpecName('DOM2 HTML', 'html.html#ID-17701901', 'HTMLImgElement')}}{{Spec2('DOM2 HTML')}}The lowSrc property has been removed.
+ The following properties are now long, instead of DOMString: height, width, hspace, and vspace.
{{SpecName('DOM1', 'level-one-html.html#ID-17701901', 'HTMLImgElement')}}{{Spec2('DOM1')}}Initial definition.
+ +

瀏覽器相容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop(1.0)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
lowSrc{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
naturalWidth, naturalHeight{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}9{{CompatVersionUnknown}}{{CompatVersionUnknown}}
crossorigin{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}9{{CompatVersionUnknown}}{{CompatVersionUnknown}}
complete{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}5[4]{{CompatVersionUnknown}}{{CompatVersionUnknown}}
srcset {{experimental_inline}}{{CompatChrome(34)}}{{CompatVersionUnknown}}{{CompatGeckoDesktop(32)}}[2]{{CompatNo}}21{{CompatSafari(7.1)}}
currentSrc {{experimental_inline}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop(32)}}[2]{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}
sizes {{experimental_inline}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop(33)}}[3]{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}
x and y{{CompatVersionUnknown}}{{CompatVersionUnknown}}14[1]{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
referrerPolicy {{experimental_inline}}{{CompatChrome(51)}}{{CompatNo}}{{CompatGeckoDesktop(50)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
onerror event handler{{CompatNo}}{{CompatUnknown}}{{CompatGeckoDesktop(51)}}[5]{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile(1.0)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
lowSrc{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
naturalWidth, naturalHeight{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}9{{CompatUnknown}}{{CompatVersionUnknown}}
crossorigin{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
complete{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
srcset {{experimental_inline}}{{CompatChrome(34)}}{{CompatChrome(34)}}{{CompatVersionUnknown}}{{CompatGeckoMobile(32)}}[2]{{CompatNo}}{{CompatNo}}iOS 8
currentSrc {{experimental_inline}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile(32)}}[2]{{CompatNo}}{{CompatNo}}{{CompatNo}}
sizes {{experimental_inline}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile(33)}}[3]{{CompatNo}}{{CompatNo}}{{CompatNo}}
x and y{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}14[1]{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
referrerPolicy {{experimental_inline}}{{CompatChrome(51)}}{{CompatChrome(51)}}{{CompatNo}}{{CompatGeckoMobile(50)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
onerror event handler{{CompatNo}}{{CompatNo}}{{CompatUnknown}}{{CompatGeckoMobile(51)}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

[1] Though, these x and y properties were removed in Gecko 7.0 {{geckoRelease("7.0")}} but later, they were restored in Gecko 14.0 {{geckoRelease("14.0")}} for compatibility reasons.

+ +

[2] This feature is behind the dom.image.srcset.enabled preference, defaulting to false.

+ +

[3] This feature is behind the dom.image.picture.enabled preference, defaulting to false.

+ +

[4] IE reports false for broken images.

+ +

[5] May also be supported in earlier versions.

+ +

See also

+ + diff --git a/files/zh-tw/web/api/htmlinputelement/index.html b/files/zh-tw/web/api/htmlinputelement/index.html new file mode 100644 index 0000000000..f2b9c9c6ef --- /dev/null +++ b/files/zh-tw/web/api/htmlinputelement/index.html @@ -0,0 +1,592 @@ +--- +title: HTMLInputElement +slug: Web/API/HTMLInputElement +translation_of: Web/API/HTMLInputElement +--- +
{{ APIRef("HTML DOM") }}
+ +

HTMLInputElement 介面提供了特殊的屬性及方法以操作 input 元素的顯示與佈局。

+ +

{{InheritanceDiagram(600,120)}}

+ +

屬性

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Properties related to the parent form
form {{readonlyInline}}{{domxref("HTMLFormElement")}} object:  Returns a reference to the parent form element.
formActionstring: Returns / Sets the element's {{ htmlattrxref("formaction", "input") }} attribute, containing the URI of a program that processes information submitted by the element. This overrides the {{ htmlattrxref("action", "form") }} attribute of the parent form.
formEncTypestring: Returns / Sets the element's {{ htmlattrxref("formenctype", "input") }} attribute, containing the type of content that is used to submit the form to the server. This overrides the {{ htmlattrxref("enctype", "form") }} attribute of the parent form.
formMethodstring: Returns / Sets the element's {{ htmlattrxref("formmethod", "input") }} attribute, containing the HTTP method that the browser uses to submit the form. This overrides the {{ htmlattrxref("method", "form") }} attribute of the parent form.
formNoValidateboolean: Returns / Sets the element's {{ htmlattrxref("formnovalidate", "input") }} attribute, indicating that the form is not to be validated when it is submitted. This overrides the {{ htmlattrxref("novalidate", "form") }} attribute of the parent form.
formTargetstring: Returns / Sets the element's {{ htmlattrxref("formtarget", "input") }} attribute, containing a name or keyword indicating where to display the response that is received after submitting the form. This overrides the {{ htmlattrxref("target", "form") }} attribute of the parent form.
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Properties that apply to any type of input element that is not hidden
namestring: Returns / Sets the element's {{ htmlattrxref("name", "input") }} attribute, containing a name that identifies the element when submitting the form.
typestring: Returns / Sets the element's {{ htmlattrxref("type", "input") }} attribute, indicating the type of control to display. See {{ htmlattrxref("type", "input") }} attribute of {{ HTMLElement("input") }} for possible values.
disabledboolean: Returns / Sets the element's {{ htmlattrxref("disabled", "input") }} 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") }} 
autofocusboolean: Returns / Sets the element's {{ htmlattrxref("autofocus", "input") }} 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).
requiredboolean: Returns / Sets the element's {{ htmlattrxref("required", "input") }} attribute, indicating that the user must fill in a value before submitting a form.
valuestring: Returns / Sets the current value of the control. +

Note: If the user enters a value different from the value expected, this may return an empty string.

+
validity {{readonlyInline}}{{domxref("ValidityState")}} object: Returns the validity state that this element is in.
validationMessage {{readonlyInline}}string: Returns 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.
willValidate {{readonlyInline}}{{jsxref("Boolean")}}: Indicates whether the element is a candidate for constraint validation. It is false if any conditions bar it from constraint validation.
+ + + + + + + + + + + + + + + + + +
Properties that apply only to elements of type "checkbox" or "radio"
checked boolean: Returns / Sets the current state of the element when {{htmlattrxref("type","input")}} is checkbox or radio.
defaultCheckedboolean: Returns / Sets the default state of a radio button or checkbox as originally specified in HTML that created this object.
indeterminateboolean: indicates that the checkbox is neither on nor off.
+ + + + + + + + + + + + + + + + + + + + + +
Properties that apply only to elements of type "image"
altstring: Returns / Sets the element's {{ htmlattrxref("alt", "input") }} attribute, containing alternative text to use when {{htmlattrxref("type","input")}} is image.
heightstring: Returns / Sets the element's {{ htmlattrxref("height", "input") }} attribute, which defines the height of the image displayed for the button, if the value of {{htmlattrxref("type","input")}} is image.
srcstring: Returns / Sets the element's {{ htmlattrxref("src", "input") }} 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.
widthstring: Returns / Sets the document's {{ htmlattrxref("width", "input") }} attribute, which defines the width of the image displayed for the button, if the value of {{htmlattrxref("type","input")}} is image.
+ + + + + + + + + + + + + + + + + + + + + +
Properties that apply only to elements of type "file"
acceptstring: Returns / Sets the element's {{ htmlattrxref("accept", "input") }} attribute, containing comma-separated list of file types accepted by the server when {{htmlattrxref("type","input")}} is file.
allowdirs {{non-standard_inline}}boolean: Part of the non-standard Directory Upload API; indicates whether or not to allow directories and files both to be selected in the file list. Implemented only in Firefox and is hidden behind a preference.
{{domxref("HTMLInputElement.webkitdirectory", "webkitdirectory")}} {{Non-standard_inline}}boolean: Returns the {{htmlattrxref("webkitdirectory", "input")}} attribute; if true, the file system picker interface only accepts directories instead of files.
{{domxref("HTMLInputElement.webkitEntries", "webkitEntries")}} {{Non-standard_inline}}Array of {{domxref("FileSystemEntry")}} objects describing the currently-selected files or directories.
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Properties that apply only to text/number-containing or elements
autocompletestring: Returns / Sets the element's {{htmlattrxref("autocomplete", "input")}} 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:
+ "on": the browser can autocomplete the value using previously stored value
+ "off": the user must explicity enter a value
maxLengthlong: Returns / Sets the element's {{ htmlattrxref("maxlength", "input") }} attribute, containing the maximum length of characters (in Unicode code points) that the value can have. (If you set this to a negative number, an exception will be thrown.)
sizeunsigned long: Returns / Sets the element's {{ htmlattrxref("size", "input") }} 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. Applies only when {{htmlattrxref("type","input")}} is set to text, search, tel, url, email, or password; otherwise it is ignored.
patternstring: Returns / Sets the element's {{ htmlattrxref("pattern", "input") }} attribute, containing a regular expression that the control's value is checked against.  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.
placeholderstring: Returns / Sets the element's {{ htmlattrxref("placeholder", "input") }} 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.
readOnlyboolean: Returns / Sets the element's {{ htmlattrxref("readonly", "input") }} 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.
minstring: Returns / Sets the element's {{ htmlattrxref("min", "input") }} 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.
maxstring: Returns / Sets the element's {{ htmlattrxref("max", "input") }} attribute, containing the maximum (numeric or date-time) value for this item, which must not be less than its minimum (min attribute) value.
selectionStartunsigned long: Returns / Sets the beginning index of the selected text. When nothing is selected, this returns the position of the text input cursor (caret) inside of the {{HTMLElement("input")}} element.
selectionEndunsigned long: Returns / Sets the end index of the selected text. When there's no selection, this returns the offset of the character immediately following the current text input cursor position.
selectionDirectionstring: Returns / Sets the direction in which selection occurred. Possible values are:
+ "forward" if selection was performed in the start-to-end direction of the current locale,
+ "backward" for the opposite direction,
+ "none" if the direction is unknown."
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Properties not yet categorized
defaultValuestring: Returns / Sets the default value as originally specified in the HTML that created this object.
dirNamestring: Returns / Sets the directionality of the element.
accessKeystring: Returns a string containing a single character that switches input focus to the control when pressed.
list {{readonlyInline}}{{domxref("HTMLElement")}} object: Returns the element pointed by the {{ htmlattrxref("list", "input") }} attribute. The property may be null if no HTML element found in the same tree.
multipleboolean: Returns / Sets the element's {{ htmlattrxref("multiple", "input") }} attribute, indicating whether more than one value is possible (e.g., multiple files).
files {{readonlyInline}}{{domxref("FileList")}} array: Returns the list of selected files.
labels {{readonlyInline}}{{domxref("NodeList")}} array: Returns a list of {{ HTMLElement("label") }} elements that are labels for this element.
stepstring: Returns / Sets the element's {{ htmlattrxref("step", "input") }} 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.
valueAsDate{{jsxref("Date")}} object: Returns / Sets the value of the element, interpreted as a date, or null if conversion is not possible.
valueAsNumberdouble: Returns the value of the element, interpreted as one of the following, in order: +
    +
  • a time value
  • +
  • a number
  • +
  • NaN if conversion is impossible
  • +
+
autocapitalize {{experimental_inline}}string: defines the capitalization behavior for user input. Valid values are none, off, characters, words, or sentences.
+ +
+
{{domxref("HTMLInputElement.align")}} {{obsolete_inline}}
+
string: represents the alignment of the element. Use CSS instead.
+
{{domxref("HTMLInputElement.useMap")}} {{ obsolete_inline }}
+
string: represents a client-side image map.
+
+ +

方法

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
focus()Focus on the input element; keystrokes will subsequently go to this element.
blur()Removes focus from input; keystrokes will subsequently go nowhere.
select()Selects the input text in the element, and focuses it so the user can subsequently replace the whole entry.
click()Simulates a click on the element.
setSelectionRange()Selects 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()Selects 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.
setCustomValidity()Sets 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.
checkValidity()Returns a {{jsxref("Boolean")}} that is 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.
+ +
+
{{domxref("HTMLInputElement.stepDown()")}}
+
Decrements 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")}}. 
  • +
+
+
{{domxref("HTMLInputElement.stepUp()")}}
+
Increments 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")}}.
  • +
+
+
{{domxref("HTMLInputElement.mozSetFileArray()")}}{{non-standard_inline}}
+
Sets the files selected on the input to the given array of {{domxref("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.
+
{{domxref("HTMLInputElement.mozGetFileNameArray()")}}
+
Returns an array of all the file names from the input.
+
{{domxref("HTMLInputElement.mozSetFileNameArray()")}}
+
Sets the filenames for the files selected on the input.  Not for use in frame scripts, because it accesses the file system.
+
+
    +
+
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "forms.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.
+ +

瀏覽器相容性

+ +

{{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)}}10{{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)}}
+ +

 

+
+ +

參見

+ + diff --git a/files/zh-tw/web/api/htmlmediaelement/index.html b/files/zh-tw/web/api/htmlmediaelement/index.html new file mode 100644 index 0000000000..68d1122e81 --- /dev/null +++ b/files/zh-tw/web/api/htmlmediaelement/index.html @@ -0,0 +1,243 @@ +--- +title: HTMLMediaElement +slug: Web/API/HTMLMediaElement +translation_of: Web/API/HTMLMediaElement +--- +

{{APIRef("HTML DOM")}}

+ +

The HTMLMediaElement interface adds to {{domxref("HTMLElement")}} the properties and methods needed to support basic media-related capabilities that are common to audio and video. The {{domxref("HTMLVideoElement")}} and {{domxref("HTMLAudioElement")}} elements both inherit this interface.

+ +

{{InheritanceDiagram(600, 120)}}

+ +

屬性

+ +

這個介面從{{domxref("HTMLElement")}}、{{domxref("Element")}}、{{domxref("Node")}},和{{domxref("EventTarget")}}繼承了屬性

+ +
+
{{domxref("HTMLMediaElement.audioTracks")}}
+
{{domxref("AudioTrackList")}} 會列出包含在該媒體元素內部的{{domxref("AudioTrack")}}物件。
+
{{domxref("HTMLMediaElement.autoplay")}}
+
是一個布林值,表達了HTML中是否有{{htmlattrxref("autoplay", "video")}}屬性;意即;表明是否只要在媒體可以播放且不中斷的時候,能夠自動播放。 +
在網站上自動播放音訊(或是有音訊的影片),可能是惱人的使用者體驗;因此,應該盡可能地避免。如果你必須要有自動播放的功能,你應該讓它是可選擇的(讓使用者特地去啟動)。 However, this can be useful when creating media elements whose source will be set at a later time, under user control.
+
+
{{domxref("HTMLMediaElement.buffered")}} {{readonlyinline}}
+
回傳一個{{domxref("TimeRanges")}}物件,表示媒體當下buffered屬性被瀏覽器存取時的緩存(如果有的話)區間。
+
{{domxref("HTMLMediaElement.controller")}}
+
Is a {{domxref("MediaController")}} object that represents the media controller assigned to the element, or null if none is assigned.
+
{{domxref("HTMLMediaElement.controls")}}
+
Is a {{jsxref('Boolean')}} that reflects the {{htmlattrxref("controls", "video")}} HTML attribute, indicating whether user interface items for controlling the resource should be displayed.
+
{{domxref("HTMLMediaElement.controlsList")}} {{readonlyinline}}
+
Returns a {{domxref("DOMTokenList")}} that helps the user agent select what controls to show on the media element whenever the user agent shows its own set of controls. The DOMTokenList takes one or more of three possible values: nodownload, nofullscreen, and noremoteplayback.
+
{{domxref("HTMLMediaElement.crossOrigin")}}
+
Is a {{domxref("DOMString")}} indicating the CORS setting for this media element.
+
{{domxref("HTMLMediaElement.currentSrc")}} {{readonlyinline}}
+
Returns a {{domxref("DOMString")}} with the absolute URL of the chosen media resource.
+
{{domxref("HTMLMediaElement.currentTime")}}
+
Is a double indicating the current playback time in seconds. Setting this value seeks the media to the new time.
+
{{domxref("HTMLMediaElement.defaultMuted")}}
+
Is a {{jsxref('Boolean')}} that reflects the {{htmlattrxref("muted", "video")}} HTML attribute, which indicates whether the media element's audio output should be muted by default.
+
{{domxref("HTMLMediaElement.defaultPlaybackRate")}}
+
Is a double indicating the default playback rate for the media.
+
{{domxref("HTMLMediaElement.disableRemotePlayback")}}
+
Is a {{jsxref('Boolean')}} that sets or returns the remote playback state, indicating whether the media element is allowed to have a remote playback UI.
+
{{domxref("HTMLMediaElement.duration")}} {{readonlyinline}}
+
Returns a double indicating the length of the media in seconds, or 0 if no media data is available.
+
{{domxref("HTMLMediaElement.ended")}} {{readonlyinline}}
+
Returns a {{jsxref('Boolean')}} that indicates whether the media element has finished playing.
+
{{domxref("HTMLMediaElement.error")}} {{readonlyinline}}
+
Returns a {{domxref("MediaError")}} object for the most recent error, or null if there has not been an error.
+
{{domxref("HTMLMediaElement.loop")}}
+
Is a {{jsxref('Boolean')}} that reflects the {{htmlattrxref("loop", "video")}} HTML attribute, which indicates whether the media element should start over when it reaches the end.
+
{{domxref("HTMLMediaElement.mediaGroup")}}
+
Is a {{domxref("DOMString")}} that reflects the {{ htmlattrxref("mediagroup", "video")}} HTML attribute, which indicates the name of the group of elements it belongs to. A group of media elements shares a common {{domxref('MediaController')}}.
+
{{domxref("HTMLMediaElement.mediaKeys")}} {{readonlyinline}} {{experimental_inline}}
+
Returns a {{domxref("MediaKeys")}} object or null. MediaKeys is a set of keys that an associated HTMLMediaElement can use for decryption of media data during playback.
+
{{domxref("HTMLMediaElement.mozAudioCaptured")}} {{readonlyinline}} {{non-standard_inline}}
+
Returns a {{jsxref('Boolean')}}. Related to audio stream capture.
+
{{domxref("HTMLMediaElement.mozFragmentEnd")}} {{non-standard_inline}}
+
Is a double that provides access to the fragment end time if the media element has a fragment URI for currentSrc, otherwise it is equal to the media duration.
+
{{domxref("HTMLMediaElement.mozFrameBufferLength")}} {{non-standard_inline}} {{deprecated_inline}}
+
+

Is a unsigned long that indicates the number of samples that will be returned in the framebuffer of each MozAudioAvailable event. This number is a total for all channels, and by default is set to be the number of channels * 1024 (e.g., 2 channels * 1024 samples = 2048 total).

+ +

The mozFrameBufferLength property can be set to a new value for lower latency, larger amounts of data, etc. The size given must be a number between 512 and 16384. Using any other size results in an exception being thrown. The best time to set a new length is after the loadedmetadata event fires, when the audio info is known, but before the audio has started or MozAudioAvailable events have begun firing.

+
+
{{domxref("HTMLMediaElement.mozSampleRate")}} {{readonlyinline}} {{non-standard_inline}} {{deprecated_inline}}
+
Returns a double representing the number of samples per second that will be played. For example, 44100 samples per second is the sample rate used by CD audio.
+
{{domxref("HTMLMediaElement.muted")}}
+
Is a {{jsxref('Boolean')}} that determines whether audio is muted. true if the audio is muted and false otherwise.
+
{{domxref("HTMLMediaElement.networkState")}} {{readonlyinline}}
+
Returns a unsigned short (enumeration) indicating the current state of fetching the media over the network.
+
{{domxref("HTMLMediaElement.paused")}} {{readonlyinline}}
+
Returns a {{jsxref('Boolean')}} that indicates whether the media element is paused.
+
{{domxref("HTMLMediaElement.playbackRate")}}
+
Is a double that indicates the rate at which the media is being played back. 
+
{{domxref("HTMLMediaElement.played")}} {{readonlyinline}}
+
Returns a {{domxref('TimeRanges')}} object that contains the ranges of the media source that the browser has played, if any.
+
{{domxref("HTMLMediaElement.preload")}}
+
Is a {{domxref("DOMString")}} that reflects the {{htmlattrxref("preload", "video")}} HTML attribute, indicating what data should be preloaded, if any. Possible values are: none, metadata, auto.
+
{{domxref("HTMLMediaElement.preservesPitch")}} {{non-standard_inline}}
+
Is a {{jsxref('Boolean')}} that determines if the pitch of the sound will be preserved. If set to false, the pitch will adjust to the speed of the audio. This is implemented with prefixes in Firefox (mozPreservesPitch) and WebKit (webkitPreservesPitch).
+
{{domxref("HTMLMediaElement.readyState")}} {{readonlyinline}}
+
Returns a unsigned short (enumeration) indicating the readiness state of the media.
+
{{domxref("HTMLMediaElement.seekable")}} {{readonlyinline}}
+
Returns a {{domxref('TimeRanges')}} object that contains the time ranges that the user is able to seek to, if any.
+
{{domxref("HTMLMediaElement.seeking")}} {{readonlyinline}}
+
Returns a {{jsxref('Boolean')}} that indicates whether the media is in the process of seeking to a new position.
+
{{domxref("HTMLMediaElement.sinkId")}} {{readonlyinline}} {{experimental_inline}}
+
Returns a {{domxref("DOMString")}} that is the unique ID of the audio device delivering output, or an empty string if it is using the user agent default. This ID should be one of the MediaDeviceInfo.deviceid values returned from {{domxref("MediaDevices.enumerateDevices()")}}, id-multimedia, or id-communications.
+
{{domxref("HTMLMediaElement.src")}}
+
Is a {{domxref("DOMString")}} that reflects the {{htmlattrxref("src", "video")}} HTML attribute, which contains the URL of a media resource to use.
+
{{domxref("HTMLMediaElement.srcObject")}}
+
Is a {{domxref('MediaStream')}} representing the media to play or that has played in the current HTMLMediaElement, or null if not assigned.
+
{{domxref("HTMLMediaElement.textTracks")}} {{readonlyinline}}
+
Returns the list of {{domxref("TextTrack")}} objects contained in the element.
+
{{domxref("HTMLMediaElement.videoTracks")}} {{readonlyinline}}
+
Returns the list of {{domxref("VideoTrack")}} objects contained in the element. +
+

Gecko supports only single track playback, and the parsing of tracks' metadata is only available for media with the Ogg container format.

+
+
+
{{domxref("HTMLMediaElement.volume")}}
+
Is a double indicating the audio volume, from 0.0 (silent) to 1.0 (loudest).
+
+ +

Event handlers

+ +
+
 
+
{{domxref("HTMLMediaElement.onencrypted")}}
+
Sets the {{domxref('EventHandler')}} called when the media is encrypted.
+
{{domxref("HTMLMediaElement.onwaitingforkey")}}
+
Sets the {{domxref('EventHandler')}} called when playback is blocked while waiting for an encryption key.
+
+ +

Obsolete attributes

+ +

These attributes are obsolete and should not be used, even if a browser still supports them.

+ +

 

+ +
+
{{domxref("HTMLMediaElement.initialTime")}} {{readonlyinline}} {{non-standard_inline}} {{obsolete_inline}}
+
Returns a double that indicates the initial playback position in seconds.
+
{{domxref("HTMLMediaElement.mozChannels")}} {{readonlyinline}} {{non-standard_inline}} {{deprecated_inline}}
+
Returns a double representing the number of channels in the audio resource (e.g., 2 for stereo).
+
+ +

Obsolete event handlers

+ +

 

+ +
+
{{domxref("HTMLMediaElement.onmozinterruptbegin")}} {{non-standard_inline}} {{obsolete_inline}}
+
Sets the {{domxref("EventHandler")}} called when the media element is interrupted because of the Audio Channel manager. This was Firefox-specific, having been implemented for Firefox OS, and was removed in Firefox 55.
+
{{domxref("HTMLMediaElement.onmozinterruptend")}} {{non-standard_inline}} {{obsolete_inline}}
+
Sets the {{domxref('EventHandler')}} called when the interruption is concluded. This was Firefox-specific, having been implemented for Firefox OS, and was removed in Firefox 55.
+
+ +

 

+ +

 

+ +

Methods

+ +

This interface also inherits methods from its ancestors {{domxref("HTMLElement")}}, {{domxref('Element')}}, {{domxref('Node')}}, and {{domxref('EventTarget')}}.

+ +
+
{{domxref("HTMLMediaElement.addTextTrack()")}}
+
Adds a text track (such as a track for subtitles) to a media element.
+
{{domxref("HTMLMediaElement.captureStream()")}} {{experimental_inline}}
+
Returns {{domxref("MediaStream")}}, captures a stream of the media content.
+
{{domxref("HTMLMediaElement.canPlayType()")}}
+
Determines whether the specified media type can be played back.
+
{{domxref("HTMLMediaElement.fastSeek()")}}
+
Directly seeks to the given time.
+
{{domxref("HTMLMediaElement.load()")}}
+
Resets the media element and restarts the media resource. Any pending events are discarded. How much media data is fetched is still affected by the preload attribute. This method can be useful for releasing resources after any src attribute and source element descendants have been removed. Otherwise, it is usually unnecessary to use this method, unless required to rescan source element children after dynamic changes.
+
{{domxref("HTMLMediaElement.mozCaptureStream()")}} {{non-standard_inline}}
+
[enter description]
+
{{domxref("HTMLMediaElement.mozCaptureStreamUntilEnded()")}} {{non-standard_inline}}
+
[enter description]
+
{{domxref("HTMLMediaElement.mozGetMetadata()")}} {{non-standard_inline}}
+
Returns {{jsxref('Object')}}, which contains properties that represent metadata from the playing media resource as {key: value} pairs. A separate copy of the data is returned each time the method is called. This method must be called after the loadedmetadata event fires.
+
{{domxref("HTMLMediaElement.pause()")}}
+
Pauses the media playback.
+
{{domxref("HTMLMediaElement.play()")}}
+
Begins playback of the media.
+
{{domxref("HTMLMediaElement.seekToNextFrame()")}} {{non-standard_inline}} {{experimental_inline}}
+
Seeks to the next frame in the media. This non-standard, experimental method makes it possible to manually drive reading and rendering of media at a custom speed, or to move through the media frame-by-frame to perform filtering or other operations.
+
{{domxref("HTMLMediaElement.setMediaKeys()")}} {{experimental_inline}}
+
Returns {{jsxref("Promise")}}. Sets the {{domxref("MediaKeys")}} keys to use when decrypting media during playback.
+
{{domxref("HTMLMediaElement.setSinkId()")}} {{experimental_inline}}
+
Sets the ID of the audio device to use for output and returns a {{jsxref("Promise")}}. This only works when the application is authorized to use the specified device.
+
+ +

Obsolete methods

+ +

These methods are obsolete and should not be used, even if a browser still supports them.

+ +

 

+ +
+
{{domxref("HTMLMediaElement.mozLoadFrom()")}} {{non-standard_inline}} {{deprecated_inline}}
+
This method, available only in Mozilla's implementation, loads data from another media element. This works similarly to load() except that instead of running the normal resource selection algorithm, the source is simply set to the other element's currentSrc. This is optimized so this element gets access to all of the other element's cached and buffered data; in fact, the two elements share downloaded data, so data downloaded by either element is available to both.
+
+ +

 

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "the-video-element.html#htmlmediaelement", "HTMLMediaElement")}}{{Spec2('HTML WHATWG')}}No change from {{SpecName('HTML5 W3C')}}
{{SpecName('HTML5 W3C', "embedded-content-0.html#htmlmediaelement", "HTMLMediaElement")}}{{Spec2('HTML5 W3C')}}Initial definition.
{{SpecName('EME', '#introduction', 'Encrypted Media Extensions')}}{{Spec2('EME')}}Adds {{domxref("MediaKeys")}}, {{domxref("MediaEncryptedEvent")}}, {{domxref("setMediaKeys")}}, {{domxref("onencrypted")}}, and {{domxref("onwaitingforkey")}}.
{{SpecName('Media Capture','#htmlmediaelement-extensions','HTMLMediaElement')}}{{Spec2('Media Capture')}}Adds sinkId and setSinkId(), and captureStream().
+ +

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/zh-tw/web/api/htmlmediaelement/ratechange_event/index.html b/files/zh-tw/web/api/htmlmediaelement/ratechange_event/index.html new file mode 100644 index 0000000000..e4c6a3d743 --- /dev/null +++ b/files/zh-tw/web/api/htmlmediaelement/ratechange_event/index.html @@ -0,0 +1,82 @@ +--- +title: 'HTMLMediaElement: ratechange' +slug: Web/API/HTMLMediaElement/ratechange_event +tags: + - 播放速度 速度 速率 +translation_of: Web/API/HTMLMediaElement/ratechange_event +--- +

ratechange 事件將在播放速度改變時被觸發

+ +

基本資訊

+ +
+
規格
+
HTML5 Media
+
介面
+
事件
+
是否冒泡
+
+
是否可取消
+
+
目標
+
元素
+
預設行為
+
+
+ +

屬性

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
屬性類型描述
target {{readonlyInline}}{{domxref("EventTarget")}}事件目標(DOM樹中最頂層的目標)
type {{readonlyInline}}{{domxref("DOMString")}}事件類型
bubbles {{readonlyInline}}{{jsxref("Boolean")}}事件是否觸發冒泡
cancelable {{readonlyInline}}{{jsxref("Boolean")}}事件是否可取消
+ +

相關事件

+ + diff --git a/files/zh-tw/web/api/htmlmediaelement/readystate/index.html b/files/zh-tw/web/api/htmlmediaelement/readystate/index.html new file mode 100644 index 0000000000..14df7bb4e0 --- /dev/null +++ b/files/zh-tw/web/api/htmlmediaelement/readystate/index.html @@ -0,0 +1,110 @@ +--- +title: HTMLMediaElement.readyState +slug: Web/API/HTMLMediaElement/readyState +translation_of: Web/API/HTMLMediaElement/readyState +--- +
{{APIRef("HTML DOM")}}
+ +
HTMLMediaElement.readyState 屬性回傳目前媒體的就緒狀態。
+ +

語法

+ +
var readyState = audioOrVideo.readyState;
+ +

+ +

一個 unsigned short,可能的值有:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
常數描述
HAVE_NOTHING0沒有可用的媒體資源。
HAVE_METADATA1已經取得足夠的媒體資源並已初始化元資料。繼續取得媒體資源不會導致例外。
HAVE_CURRENT_DATA2媒體資料已經足夠播放目前的時間,但沒有足夠的資料再播放一幀。
HAVE_FUTURE_DATA3資料已經足夠播放目前的時間,而且有至少一點點資料可以播放未來的時間(換句話說,可能只多了一到兩幀)。
HAVE_ENOUGH_DATA4資料足夠,且下載率夠高。媒體可以播放到結束而不被中斷。
+ +

範例

+ +

下面這個例子會監聽 `example` 這個元素,並檢查是否已載入足夠的媒體資源。如果是的話,它會繼續播放。

+ +
<audio id="example" preload="auto">
+ <source src="sound.ogg" type="audio/ogg" />
+</audio>
+
+
+ +
var obj = document.getElementById('example');
+
+obj.addEventListener('loadeddata', function() {
+
+  if(obj.readyState >= 2) {
+    obj.play();
+  }
+
+});
+
+ +

 

+ +

標準

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "the-video-element.html#htmlmediaelement", "HTMLMediaElement.readyState")}}{{Spec2('HTML WHATWG')}}No change from {{SpecName('HTML5 W3C')}}
{{SpecName('HTML5 W3C', "embedded-content-0.html#htmlmediaelement", "HTMLMediaElement.readyState")}}{{Spec2('HTML5 W3C')}}Initial definition.
+ +

瀏覽器相容性

+ + + +

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

+ +

也參考看看

+ + diff --git a/files/zh-tw/web/api/htmlselectelement/checkvalidity/index.html b/files/zh-tw/web/api/htmlselectelement/checkvalidity/index.html new file mode 100644 index 0000000000..8ded860ac4 --- /dev/null +++ b/files/zh-tw/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") }}
+ +

HTMLSelectElement.checkValidity() 方法會檢查元素是否有任何的檢核、驗證條件,並且檢查是否滿足這些條件。如果元素沒有通過這些檢核,瀏覽器會於該元素上觸發一個可取消的 {{event("invalid")}} 事件,並回傳 false

+ +

語法

+ +
var result = selectElt.checkValidity();
+ +

規範

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{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')}}
+ +

瀏覽器相容性

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

參見

+ + diff --git a/files/zh-tw/web/api/htmlselectelement/index.html b/files/zh-tw/web/api/htmlselectelement/index.html new file mode 100644 index 0000000000..0110568dd6 --- /dev/null +++ b/files/zh-tw/web/api/htmlselectelement/index.html @@ -0,0 +1,283 @@ +--- +title: HTMLSelectElement +slug: Web/API/HTMLSelectElement +translation_of: Web/API/HTMLSelectElement +--- +
{{APIRef("HTML DOM")}}
+ +

HTMLSelectElement 介面代表了 {{HTMLElement("select")}} HTML 元素。此介面也自 {{domxref("HTMLElement")}} 介面繼承了所有 HTML 元素的屬性及方法。

+ +

{{InheritanceDiagram(600, 120)}}

+ +

屬性

+ +

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

範例

+ +

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.

+ +

規範

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

瀏覽器相容性

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

+ +

參見

+ + diff --git a/files/zh-tw/web/api/htmlselectelement/setcustomvalidity/index.html b/files/zh-tw/web/api/htmlselectelement/setcustomvalidity/index.html new file mode 100644 index 0000000000..54e47edf3c --- /dev/null +++ b/files/zh-tw/web/api/htmlselectelement/setcustomvalidity/index.html @@ -0,0 +1,50 @@ +--- +title: HTMLSelectElement.setCustomValidity() +slug: Web/API/HTMLSelectElement/setCustomValidity +translation_of: Web/API/HTMLSelectElement/setCustomValidity +--- +
{{ APIRef("HTML DOM") }}
+ +

HTMLSelectElement.setCustomValidity() 方法可為指定的元素設定自定義檢核訊息。使用空字串表示元素沒有發生違反自定檢核條件的錯誤。

+ +

語法

+ +
selectElt.setCustomValidity(string);
+ +

參數

+ + + +

規範

+ + + + + + + + + + + + + + + + + + + +
規範狀態意見
{{SpecName('HTML WHATWG', '#dom-cva-setcustomvalidity', 'HTMLSelectElement.setCustomValidity()')}}{{Spec2('HTML WHATWG')}}No change since the latest snapshot, {{SpecName('HTML5 W3C')}}.
{{SpecName('HTML5 W3C', 'forms.html#dom-cva-setcustomvalidity', 'HTMLSelectElement.setCustomValidity()')}}{{Spec2('HTML5 W3C')}}Initial definition, snapshot of {{SpecName('HTML WHATWG')}}
+ +

瀏覽器相容性

+ +

{{Compat("api.HTMLSelectElement.setCustomValidity")}}

+ +

參見

+ + diff --git a/files/zh-tw/web/api/idbdatabase/index.html b/files/zh-tw/web/api/idbdatabase/index.html new file mode 100644 index 0000000000..843eac92f5 --- /dev/null +++ b/files/zh-tw/web/api/idbdatabase/index.html @@ -0,0 +1,219 @@ +--- +title: IDBDatabase +slug: Web/API/IDBDatabase +translation_of: Web/API/IDBDatabase +--- +

{{APIRef("IndexedDB")}}

+ +
+

The IDBDatabase interface of the IndexedDB API provides a connection to a database; you can use an IDBDatabase object to open a transaction on your database then create, manipulate, and delete objects (data) in that database. The interface provides the only way to get and manage versions of the database.

+ +

{{AvailableInWorkers}}

+
+ +
+

Note: Everything you do in IndexedDB always happens in the context of a transaction, representing interactions with data in the database. All objects in IndexedDB — including object stores, indexes, and cursors — are tied to a particular transaction. Thus, you cannot execute commands, access data, or open anything outside of a transaction.

+
+ +
+

Note: Note that as of Firefox 40, IndexedDB transactions have relaxed durability guarantees to increase performance (see {{Bug("1112702")}}.) Previously in a readwrite transaction {{domxref("IDBTransaction.oncomplete")}} was fired only when all data was guaranteed to have been flushed to disk. In Firefox 40+ the 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 complete 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. If you must 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")}}.

+
+ +

Methods

+ +

Inherits from: EventTarget

+ +
+
{{domxref("IDBDatabase.close()")}}
+
Returns immediately and closes the connection to a database in a separate thread.
+
{{domxref("IDBDatabase.createObjectStore()")}}
+
Creates and returns a new object store or index.
+
{{domxref("IDBDatabase.deleteObjectStore()")}}
+
Destroys the object store with the given name in the connected database, along with any indexes that reference it.
+
{{domxref("IDBDatabase.transaction()")}}
+
Immediately returns a transaction object ({{domxref("IDBTransaction")}}) containing the {{domxref("IDBTransaction.objectStore")}} method, which you can use to access your object store. Runs in a separate thread.
+
+ +

屬性

+ +
+
{{domxref("IDBDatabase.name")}} {{readonlyInline}}
+
A {{ domxref("DOMString") }} that contains the name of the connected database.
+
{{domxref("IDBDatabase.version")}} {{readonlyInline}}
+
A 64-bit integer that contains the version of the connected database. When a database is first created, this attribute is an empty string.
+
{{domxref("IDBDatabase.objectStoreNames")}} {{readonlyInline}}
+
A {{ domxref("DOMStringList") }} that contains a list of the names of the object stores currently in the connected database.
+
+ +

Event handlers

+ +
+
{{domxref("IDBDatabase.onabort")}}
+
Fires when access of the database is aborted.
+
{{domxref("IDBDatabase.onerror")}}
+
Fires when access to the database fails.
+
{{domxref("IDBDatabase.onversionchange")}}
+
+

Fires when a database structure change ({{domxref("IDBOpenDBRequest.onupgradeneeded")}} event or {{domxref("IDBFactory.deleteDatabase")}} was requested elsewhere (most probably in another window/tab on the same computer). This is different from the version change transaction (see {{domxref("IDBVersionChangeEvent")}}), but it is related.

+
+
+ +

範例

+ +

In the following code snippet, we open a database asynchronously ({{domxref("IDBFactory")}}), handle success and error cases, and create a new object store in the case that an upgrade is needed ({{ domxref("IDBdatabase") }}). For a complete working example, see our To-do Notifications app (view example live.)

+ +
// Let us open our database
+  var DBOpenRequest = window.indexedDB.open("toDoList", 4);
+
+  // these two event handlers act on the IDBDatabase object, when the database is 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
+    db = DBOpenRequest.result;
+
+    // Run the displayData() function to populate the task list with all the to-do list data already in the IDB
+    displayData();
+  };
+
+  // This event handles the event whereby a new version of the database needs to be created
+  // Either one has not been created before, or a new version number has been submitted via the
+  // window.indexedDB.open line above
+
+  DBOpenRequest.onupgradeneeded = function(event) {
+    var db = event.target.result;
+
+    db.onerror = function(event) {
+      note.innerHTML += '<li>Error loading database.</li>';
+    };
+
+    // Create an objectStore for this database using IDBDatabase.createObjectStore
+
+    var objectStore = db.createObjectStore("toDoList", { keyPath: "taskTitle" });
+
+    // define what data items the objectStore will contain
+
+    objectStore.createIndex("hours", "hours", { unique: false });
+    objectStore.createIndex("minutes", "minutes", { unique: false });
+    objectStore.createIndex("day", "day", { unique: false });
+    objectStore.createIndex("month", "month", { unique: false });
+    objectStore.createIndex("year", "year", { unique: false });
+
+    objectStore.createIndex("notified", "notified", { unique: false });
+
+    note.innerHTML += '<li>Object store created.</li>';
+  };
+ +

This next line opens up a transaction on the Database, then opens an object store that we can then manipulate the data inside of.

+ +
    var objectStore = db.transaction('toDoList').objectStore('toDoList'); 
+ +

規範

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('IndexedDB', '#idl-def-IDBDatabase', 'IDBDatabase')}}{{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}}
+
+ +
+

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

+
+ +

閱讀更多

+ + + +

 

diff --git a/files/zh-tw/web/api/index.html b/files/zh-tw/web/api/index.html new file mode 100644 index 0000000000..982a2aa3c0 --- /dev/null +++ b/files/zh-tw/web/api/index.html @@ -0,0 +1,15 @@ +--- +title: Web APIs +slug: Web/API +tags: + - API + - DOM + - JavaScript + - Reference +translation_of: Web/API +--- +

當你使用 JavaScript 為網站寫程式碼時,有很多很棒的 API 可以使用。

+ +

以下清單列出所有能夠用在你開發網路程式或網站時的介面(即是物件的類型)。

+ +
{{APIListAlpha}}
diff --git a/files/zh-tw/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html b/files/zh-tw/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html new file mode 100644 index 0000000000..a57486e7b2 --- /dev/null +++ b/files/zh-tw/web/api/indexeddb_api/basic_concepts_behind_indexeddb/index.html @@ -0,0 +1,209 @@ +--- +title: IndexedDB基礎概念 +slug: Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB +translation_of: Web/API/IndexedDB_API/Basic_Concepts_Behind_IndexedDB +--- +

IndexedDB 用來儲存資料到使用者的瀏覽器,所以我們的網頁應用程式不論在線上或線下都可以運作。IndexedDB 對需要儲存大量資料上 (如儲存 DVD 出租型錄) 的應用和不用一直存取網路的應用 (如郵件客戶端瀏覽、代辦事項、記事本等) 來說十分好用。

+ +

關於本文

+ +

本文介紹 IndexedDB 重要概念和專有名詞,旨在提供 IndexedDB 全貌和關鍵概念,如要了解更多 IndexedDB 專有名詞,請參照定義部分。

+ +

想了解如何使用相關 API,請參照使用 IndexedDB;相關參考資料請參照 IndexedDB 一文,該文介紹了 IndexedDB 使用物件型態以及同步和非同步 API 。

+ +

IndexedDB 概要

+ +

IndexedDB 讓我們透過資料鍵 (key) 儲存、取回物件。所有對資料庫的變更都發生在交易操作;如同大部分網頁儲存方案,IndexedDB 遵守同源政策,也就是說我們只能存取同網域下的資料。

+ +

API 有分非同步同步,非同步 API 適用於大部分情況,包括 Web Worker,而同步 API 應該只用在 Web Worker 內。目前主流瀏覽器尚不支援同步 API,不過即使同步 API 存在,大部分的情況還是以非同步 API 使用為主。

+ +

W3C 在 2011/11/18 宣布 WebSQL 已棄用,請用 IndexedDB 作為替代方案。IndexedDB 和 WebSQL 雖然都是儲存方案,但功能並不相同,IndexedDB 是索引資料表資料庫,而 WebSQL 是關聯式資料庫系統。

+ +

概念總覽

+ +

請將你在其他類型資料庫上的預期從 IndexedDB 上拋開,然後謹記以下重要概念:

+ + + +

定義

+ +

以下是 IndexedDB API 專有名詞定義與解說。

+ +

Database

+ +
+
資料庫
+
資訊集中存放之處,由一或數個物件存檔 (Object store) 組成,每一個資料庫必須具有: +
    +
  • 名稱。用以辨識資料庫所屬來源,在生命週期間固定不變,可以任意字串 (甚至空白字串) 。
  • +
  • +

    目前版本。當資料庫創建後,如未指定,它的版本是整數1。每一個資料庫同一時間只能有一個版本。

    +
  • +
+
+
物件存檔 (object store)
+
+

資料存放於資料庫的機制;物件存檔持有紀錄,也就是資料鍵和資料值的成對紀錄。記錄在物件存檔中依資料鍵 (keys)大小由小到大排列。

+ +

每一個物件存檔都具備獨特名稱,物件存檔能夠選擇性地持有 key generator 和 key path;若有 key path 便會採用 in-line keys,否則便採用 out-of-line keys

+ +

更多物件存檔細節,請參照 IDBObjectStore 或 IDBObjectStoreSync

+
+
版本 (version)
+
當資料庫創建後,如未指定,它的版本是整數 1;每一個資料庫同一時間只能有一個版本,唯一變更版本的方法是開啟比目前更大的版本,變更版本將啟動 versionchange 交易並且觸發 upgradeneeded 事件,upgradeneeded 事件處理器也是唯一可以變更資料庫結構之處。
+
注意: 本處解說涵蓋近期大部分規範,舊版瀏覽器支援現在已經廢棄的 IDBDatabase.setVersion() 方法。
+
 
+
database connection
+
開啟資料庫的作業,一個資料庫同一時間可以擁有多個連線。
+
交易 (transaction)
+
+

在特定資料庫上進行資料存取和資料修改的一連串作業,這便是我們和資料庫的互動,事實上,任何讀取或變更資料庫資料都會發生在交易之中。

+ +

只要寫入交易間沒有重疊範疇 (scopes),一個資料庫連結可以同時擁有多個進行中交易。交易範疇在交易創建當下決定,交易範疇定義了與交易互動的物件存檔以及將交易期間不可變更部分,例如說,有一個資料庫連結正在進行寫入交易,這項寫入交易涵蓋 flyingMonkey 物件存檔,我們可以進行第二項有關 unicornCentaur 與 unicornPegasus 物件存檔的交易。至於讀取交易則不受交易範疇重疊限制。

+ +

交易的生命應該不可過長,所以瀏覽器可以終止交易時間過長的交易,好讓長時間被鎖定的資料得以解除鎖定;交易可以中止,中止後交易所造成的變更都會被復原;交易的中止不必要等到交易開始或進行中。

+ +

交易有三種模式: readwrite, readonly 和 versionchange,只能透過 versionchange 交易創建、刪除物件存檔與索引。

+ +

由於交易是相當重要的觀念,尤其是交易和版本間的關係,請參照 IDBTransaction 以了解更多交易相
+ 關細節,另外關於同步API,請參照IDBTransactionSync

+
+
請求 (request)
+
每一個讀寫作業都是一個請求。
+
索引 (index)
+
+

一個用來查詢其他物件存檔內紀錄的特殊物件存檔,被查詢的物件存檔我們稱為參照物件存檔 (referenced object store) 。索引是資料鍵和值的成對紀錄,其中值就是參照物件存檔內的記錄的資料鍵;當參照物件存檔有紀錄新增、變更或刪除時索引內的紀錄也會相應自動產生,索引內的紀錄只能指向參照物件存檔內的一筆紀錄,但可以有多筆索引紀錄參照同一個物件存檔。物件存檔變更同時,所有的相關索引也會自動相應更新。

+ +

除此之外,我們也可以透過資料鍵 (key) 來查詢物件存檔中的紀錄。

+ +

了解如何使用索引請參照使用 IndexedDB,要知道更多索引細節請參照 IDBKeyRange 和 IDBIndex 。

+
+
+ +

資料鍵 (Key) 和資料值 (Value)

+ +
+
資料鍵 (key)
+
+

資料存放在物件存檔中。物件存檔有三種方式產生資料鍵: 資料鍵產生器 (key generator)、資料鍵路徑 (key path) 以及指定值。資料鍵的資料型態 (data type) 必須要是能夠進行大小排序;物件存檔中的每一筆紀錄都要有一支獨特的對應資料鍵,不能和同一個物件存檔中其他紀錄的資料鍵相同。

+ +

資料鍵可以是: string, date, float和 array (陣列);對於 array,資料鍵範圍可以是空值到無限,還可以在 array 中包含另一個 array,至於以字串或整數作資料鍵則無特殊規定。

+ +

除此之外,我們也可以透過索引 (index) 來查詢物件存檔中的紀錄。

+
+
資料鍵產生器 (key generator)
+
自動生成有大小順序關係的資料鍵的機制;因為資料鍵是必要的,所以如果沒有資料鍵或想省去給定資料鍵的步驟,那就需要用產生器自動產生資料鍵。
+
in-line key
+
當物件存檔有資料鍵路徑時稱為有使用 in-line key。
+
out-of-line key
+
當物件存檔沒有資料鍵路徑時稱為使用 out-of--line key。
+
資料鍵路徑 (key path)
+
定義瀏覽器應該如何從物件存檔資料值或索引中提取資料鍵。以下為有效的資料鍵路徑: 一個空字串、一個 Javascript 辨識名稱 (JavaScript identifier) 或數個由”.”(ASCII字元第46字碼) 分隔的 Javascript 辨識名稱。路徑不可含有空白字元。
+
資料值 (value)
+
+

每筆紀錄都有資料值,資料值可以是任意Javascript所能表達的項目,包括boolean, number, string, date, object, array, regexp, undefined 以及 null。

+ +

儲存物件或陣列裡的屬性和值也可以是任意Javascript所能表達的項目。

+ +

可以儲存 Blobs 和檔案,請參照 W3C 規範

+
+
+ +

範圍和範疇

+ +
+
範疇
+
交易影響到的物件和索引。讀取交易間的範疇可以互相重疊、同時進行,然後寫入交易範疇則不可,如果同時開啟多項交易範疇相同的寫入交易的話,那麼這些交易會排入佇列 (queue),一個接著一個完成後執行。
+
指標 (Cursor)
+
在一定資料鍵範圍以內往覆 (iterate) 資料的機制。指標指向了一個物件存檔或索引,它會在一定範圍內,由小到大或由大到小循著紀錄的資料鍵移動,詳細資訊請參照 IDBCursor 或 IDBCursorSync 。
+
資料鍵範圍
+
+

某種資料型態的一段連續區間,這個區間將作為資料鍵的上下限,我們透過資料鍵或資料鍵範圍取出物件存檔和索引值;藉由上下限我們可以做到存取資料鍵介於 x 和 y 之間的資料,詳細請參考 IDBKeyRange 。

+
+
+ +

限制

+ +

IndexedDB 設計上足以滿足大部分客戶端儲存需求,不過,以下情況並不適用 IndexedDB :

+ + + +

除此之外,請小心瀏覽器可能會清空資料庫,例如:

+ + + +

瀏覽器確切的狀況和功能範疇未來會變更,但基本上瀏覽器還是會盡可能保存資料。

+ +

下一步

+ +

現在我們已經了解 IndexedDB 的整體概念,接下來請到 “使用 IndexedDB” 看看如何實際使用 IndexedDB。

+ +

延伸閱讀

+ +

標準規範

+ + + +

參照

+ + + +

相關教學

+ + + +

相關文章

+ + diff --git a/files/zh-tw/web/api/indexeddb_api/index.html b/files/zh-tw/web/api/indexeddb_api/index.html new file mode 100644 index 0000000000..91f2fc812d --- /dev/null +++ b/files/zh-tw/web/api/indexeddb_api/index.html @@ -0,0 +1,148 @@ +--- +title: IndexedDB +slug: Web/API/IndexedDB_API +tags: + - Database + - IndexedDB + - bug-840092 +translation_of: Web/API/IndexedDB_API +--- +
{{SeeCompatTable}}
+ +

IndexedDB 為用戶端的儲存用 API,可用於大量的結構化資料,並透過索引功能而高效率搜尋資料。DOM Storage 適合儲存較少量的資料;IndexedDB 則適合大量結構化資料的儲存方案。

+ +

本篇文章僅為 API 物件的入門技術說明。若需進一步了解,則請參閱 IndexedDB 基本概念。更多細節則可參閱使用 IndexedDB

+ +

IndexedDB 提供不同 APIs 用於同步與非同步的存取作業。同步 API 僅能用於Web Workers 之中,但尚未有瀏覽器支援同步API。非同步 API 則用於 Web Workers 內外均可,但 Firefox 目前尚未建構。

+ +

非同步 API

+ +

非同步API不會阻塞呼叫它的執行緒。若要非同步存取資料庫,可於 window 物件的 indexedDB 屬性上呼叫 open()。此函式將回傳 IDBRequest 物件 (IDBOpenDBRequest),開始非同步存取資料庫;呼叫端程式利用IDBRequest物件上的事件來進行非同步溝通。

+ +
+

注意:在舊版瀏覽器 (Gecko 16 版之前的 indexedDB 屬性;Chrome 中的 webkitIndexedDB;IE 10 中的 msIndexedDB) 中的 indexedDB 物件,均具備前綴屬性。

+
+ + + +

以下API在早期規範中有定義,但現已移除。這邊列出僅供參考:

+ + + +

除了非同步API,也有應用在WebWorkers內的同步API,但請注意目前還沒有瀏覽器支援同步API。這裡也提供 API 的同步版本

+ +

儲存限制

+ +

單一資料庫項目的容量/大小並沒有任何限制,但是各個 IndexedDB資料庫的容量就有限制。此限制,還有使用者介面的斷言 (Assert) 方式,又將因瀏覽器而有所不同:

+ + + +

範例

+ +

Web 上的 IndexedDB 使用範例,是由 Marco Castelluccio 所提供。Marco 是 IndexedDB Mozilla DevDerby 的優勝者,而該得獎 Demo 為 eLibri,屬於函式庫與 eBook 閱讀器的 App。

+ +

瀏覽器相容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Asynchronous API +

24.0
+ 11.0 {{property_prefix("webkit")}}

+
+

{{CompatGeckoDesktop("16.0")}}
+ {{CompatGeckoDesktop("2.0")}} {{property_prefix("moz")}}

+
10 {{property_prefix("ms")}}{{CompatNo}}{{CompatNo}}
Synchronous API
+ (used with WebWorkers)
{{CompatNo}}{{CompatNo}}
+ See {{bug(701634)}}
{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Asynchronous API{{CompatNo}}{{CompatGeckoDesktop("6.0")}} {{property_prefix("moz")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

瀏覽器相容性表格則請參閱:When Can I Use IndexedDB

+ +

另可透過 IndexedDB Polyfill,在支援 WebSQL 的瀏覽器上使用 IndexedDB。

+ +

另可參閱

+ + diff --git a/files/zh-tw/web/api/indexeddb_api/using_indexeddb/index.html b/files/zh-tw/web/api/indexeddb_api/using_indexeddb/index.html new file mode 100644 index 0000000000..5bddd965b4 --- /dev/null +++ b/files/zh-tw/web/api/indexeddb_api/using_indexeddb/index.html @@ -0,0 +1,1085 @@ +--- +title: 使用IndexedDB +slug: Web/API/IndexedDB_API/Using_IndexedDB +translation_of: Web/API/IndexedDB_API/Using_IndexedDB +--- +

IndexedDB提供了在瀏覽器上儲存保留資料的功能,藉由它,不論是線上或線下我們的應用都可以進行資料存取。

+

關於本文

+

本文會帶領各位操作非同步IndexedDB的API,如果不知道甚麼是IndexedDB,請先看看"IndexedDB基本礎念"

+

基本操作步驟

+

操作IndexedDB的基本步驟建議如下:

+
    +
  1. 開啟資料庫和交易(transaction)。
  2. +
  3. 建立物件存檔(object store)
  4. +
  5. 發出資料庫操作請求,例如新增或取得資料。
  6. +
  7. +
    + 聆聽對應DOM事件等待操作完成。
    +
  8. +
  9. +
    + 從result物件上取得結果進行其他工作。
    +
  10. +
+

好了,知道了上述概念後,我們可以來實際做些甚麼。

+

建立和結構資料庫

+

由於IndexedDB的標準仍在演進,所以目前一些實作還需要加上瀏覽器前綴標示(如Gecko基礎瀏覽器的前綴標示為moz,WebKit基礎瀏覽器的前綴標示為webkit),瀏覽器的實作也可能會有所差異,不過一旦共識標準達成,無瀏覽器前綴標示實作將出現。其實,Internet Explorer 10, Firefox 16, Chrome 24已經有了無瀏覽器前綴標示實作。

+

操作實驗性質的IndexedDB

+

如果需要試驗瀏覽器的前綴標示,可以如下:

+
// 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*)
+

請注意瀏覽器前綴標示的實作可能不完整、有些問題或仍然遵守舊版標準,因此不建議在正式版程式碼中使用。與其宣稱支援又有問題,倒不如直接不支援。

+
if (!window.indexedDB) {
+    window.alert("Your browser doesn't support a stable version of IndexedDB. Such and such feature will not be available.");
+}
+
+

開啟資料庫

+

開頭如下:

+
// Let us open our database
+var request = window.indexedDB.open("MyTestDatabase", 3);
+
+

注意到了嗎,開啟資料庫必須要進行請求。

+

開啟請求並不會立刻開啟資料庫或交易,呼叫open()方法會回傳一個IDBOpenDBRequest物件,這個物件擁有兩個事件(success和error)。大部分IndexedDB的非同步功能都會回傳一個IDBDatabase類物件,然後我們可以註冊成功和失敗事件處理器。

+

Open方法第二個參數是資料庫版本,資料庫版本決定了資料庫結構,也就是資料庫物件存檔的結構。如果請求版本不存在(比如因為這是一個新資料庫或是資料庫版本已升級),onupgradeneeded事件會被觸發,然後我們可以在onupgradeneeded事件處理器中再建立新的版本,下面升級資料庫版本有更詳細的說明。

+

產生事件處理器

+

幾乎所有第一件要對請求做的事都是產生success和error事件處理器:

+
request.onerror = function(event) {
+  // Do something with request.errorCode!
+};
+request.onsuccess = function(event) {
+  // Do something with request.result!
+};
+

如果一切正常,success事件(也就是DOM事件的type屬性設為success)會以request為目標觸發,然後request物件上的onsuccess函數接著被呼叫,其中success事件就是參數;否則error事件(也就是DOM事件的type屬性設為error)會以request為目標觸發,然後request物件上的onerror函數接著被呼叫,其中error事件就是參數。

+

IndexedDB的API設計上盡量減少錯誤處理,所以不太常看到錯誤事件,不過開啟資料庫的時候還是有一些狀況會產產生錯誤,最常見的狀況是使用者拒絕我們建立資料庫。

+

IndexedDB設計目標之一為存放大量資料以供離線使用(請參考"儲存限制"了解更多細節)。但很明顯地,瀏覽器又不樂見一些廣告網站或惡意網站汙染電腦,所以當任一個網路應用第一次開啟IndexedDB資料庫,瀏覽器會徵詢使用者是否准許其作業;同時在私密瀏覽中開啟作業也會失敗,因為私密瀏覽不會留下任何瀏覽痕跡。

+

這裡呼叫indexedDB.open()開啟indexedDB資料庫並回傳request物件,假設使用者允許我們建立indexedDB資料庫,我們也收到suceess事件觸發了success回呼函數(callback),request物件的result屬性會是一個IDBDatabase物件 ,接下來便是要儲存這個物件之後使用。下方是整個作業的示範程式碼:

+
var db;
+var request = indexedDB.open("MyTestDatabase");
+request.onerror = function(event) {
+  alert("Why didn't you allow my web app to use IndexedDB?!");
+};
+request.onsuccess = function(event) {
+  db = request.result;
+};
+
+

錯誤處理

+

錯誤事件會向上傳遞;錯誤事件以產生錯誤之請求為目標觸發,然後一路傳遞到交易,最後到資料庫物件;如果不想要為每一個請求新增錯誤處理器,可以改為資料庫物件加入一個錯誤處理器。

+
db.onerror = function(event) {
+  // Generic error handler for all errors targeted at this database's
+  // requests!
+  alert("Database error: " + event.target.errorCode);
+};
+
+

最常見的錯誤之一就是VER_ERR,該錯誤代表現在資料料庫版本大於嘗試開啟的資料庫版本,這項錯誤必須要有錯誤處理器處理。

+

建立或更新資料庫版本

+

新版本資料庫建立會觸發onupgradeneeded事件,在這個事件的處理器中要建立這個版本資料庫需要的物件存檔。

+
// This event is only implemented in recent browsers
+request.onupgradeneeded = function(event) {
+  var db = event.target.result;
+
+  // Create an objectStore for this database
+  var objectStore = db.createObjectStore("name", { keyPath: "myKey" });
+};
+

資料庫版本是unsigned long long的數字,所以能夠非常長。

+
+

請注意這也意味著版本不能為浮點數,否則小數點部分將會無條件捨去,而交易也可能不會開始,upgradeneeded事件也不會觸發。不要像以下例子以2.4作版本:

+
var request = indexedDB.open("MyTestDatabase", 2.4); // don't do this, as the version will be rounded to 2
+
+

升級版本資料庫建立會觸發onupgradeneeded事件,這個時候資料庫裡面已經含有前版本下的物件存檔,所以說不需要再次建立這些物件存檔了,剩下的是新增或刪除物件存檔。如果想要更動既存物件存檔(例如改變資料鍵路徑),那麼會需要先刪除舊的再產生一個新的(請注意這也會刪除物件存檔裡的資料,所以如果資料需要保留的話,請在升級前先讀出資料備份。)

+

Webkit支援最新標準不過只有Chrome 23才開始導入,而較舊不支援最新版標準的版本則不支援indexedDB.open(name, version).onupgradeneeded。關於如何在舊版標準下升級資料庫版本請參考"IDBDatabase參考文章"

+

結構化資料庫

+

indexedDB不用資料表而是物件存檔,物件存檔可以有很多。一筆物件存檔裡的資料值對應一筆資料鍵,依據使用{資料鍵路徑(key path)}或{資料鍵產生器(key generator)}。

+

下表列出資料建各類產生途徑:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Key PathKey Generator描述
NoNo物件存檔資料值能為任何型別,即使像數字或字串。每當新增一筆資料,必須提供不同的資料鍵。
YesNo物件存檔資料值僅能為Javacript物件,而該資料物件必須含有和資料鍵路徑相同名稱之屬性成員。
NoYes物件存檔資料值能為任何型別,資料鍵自動產生,但如果想要指定資料鍵也可以另外提供資料鍵。
YesYes物件存檔資料值僅能為Javascript物件。通常被產生的新資料鍵的值會被存在物件屬性名稱和資料鍵路徑名稱相同的物件屬性下,如果這個屬性已經存在,這個已經存在之屬性之值將被用作為資料鍵,而非新產生的資料鍵。
+

我們可以替任何儲存資料為物件型態而非原始資料型態的物件存檔建立索引,索引讓我們能夠用物件存檔中資料物件內的某一個屬性值查找資料,而非僅僅物件的資料鍵。

+

除此之外,利用索引還可以施加簡單的儲存限制;建立索引時設定獨特旗標(flag),這個索引保證在此索引資料鍵下不會存在兩個物件存檔擁有同樣資料值,比如說現在有一個存放許多使用者的物件存檔,而且我們希望保證不會存在有兩個使用者的電子郵件地址一樣,此使索引的獨特旗標便可以幫助我們達成目標。

+

以上聽起來可能會有些複雜,請看一下下面的實例:

+
// This is what our customer data looks like.
+const customerData = [
+  { ssn: "444-44-4444", name: "Bill", age: 35, email: "bill@company.com" },
+  { ssn: "555-55-5555", name: "Donna", age: 32, email: "donna@home.org" }
+];
+const dbName = "the_name";
+
+var request = indexedDB.open(dbName, 2);
+
+request.onerror = function(event) {
+  // Handle errors.
+};
+request.onupgradeneeded = function(event) {
+  var db = event.target.result;
+
+  // Create an objectStore to hold information about our customers. We're
+  // going to use "ssn" as our key path because it's guaranteed to be
+  // unique.
+  var objectStore = db.createObjectStore("customers", { keyPath: "ssn" });
+
+  // Create an index to search customers by name. We may have duplicates
+  // so we can't use a unique index.
+  objectStore.createIndex("name", "name", { unique: false });
+
+  // Create an index to search customers by email. We want to ensure that
+  // no two customers have the same email, so use a unique index.
+  objectStore.createIndex("email", "email", { unique: true });
+
+  // Store values in the newly created objectStore.
+  for (var i in customerData) {
+    objectStore.add(customerData[i]);
+  }
+};
+
+

請注意onupgradeneeded事件是唯一能夠變更資料庫結構之處,在此事件才能建立或刪除物件存檔以及建立和刪除索引。

+
+ 呼叫IDBDatabase類別物件的createObjectStore方法會立刻創造一個物件存檔,這個方法接收兩個參數,一個是物件存檔名稱,一個是非必填的參數物件,雖然參數物件不為必填但是卻相當重要,因為它讓我們定義了一些重要屬性(請參考createObjectStore)。本例中我們要求建立了一個"customer"物件存檔,定義"ssn"屬性為資料件路徑,使用"ssn"作為資料鍵路徑是因為每個客戶的ssn碼一定是獨立的。一旦決定了"ssn"作為資料鍵路徑,那麼每一筆資料一定要含有"ssn"。
+

本例還創建一個稱為"name"的索引,"name"索引查找目標為資料的"name"屬性,且不設立其獨特旗標(unique為false),同樣地,我們又呼叫createIndex方法創建了一個"email"索引,不過"email"索引具備獨特旗標(unique為true)。雖然存在"name"索引,但資料不一定要含有"name"屬性,只是當搜索"name"索引時資料不會出現。

+

接下來我們可以開始用ssn從物件存檔中取出資料,或是用索引找出資料(請參考使用索引)。

+

使用資料鍵產生器

+

當建立物件存檔時設定autoIncrement旗標為ture將啟動資料鍵產生器,預設上該旗標為false。

+

有了資料鍵產生器,當新增資料到物件存檔中,資料鍵產生器會自動幫我們產生資料鍵。資料鍵產生器產生的資料鍵由整數1開始,而基本上新產生的資料鍵是由前一個資料鍵加1產生。資料鍵的產生不會因為資料刪除或清空所有資料而重新開始起算,所以資料鍵值是一直累加上去的,除非資料庫操作中斷,整個交易作業被取消。

+

我們可以建立一個有資料鍵產生器的物件存檔如下:

+
// Open the indexedDB.
+var request = indexedDB.open(dbName, 3);
+
+request.onupgradeneeded = function (event) {
+    var db = event.target.result;
+
+    // Create another object store called "names" with the autoIncrement flag set as true.
+    var objStore = db.createObjectStore("names", { autoIncrement : true });
+
+    // Because the "names" object store has the key generator, the key for the name value is generated automatically.
+    // The added records would be like:
+    // key : 1 => value : "Bill"
+    // key : 2 => value : "Donna"
+    for (var i in customerData) {
+        objStore.add(customerData[i].name);
+    }
+}
+

關於資料鍵產生器細節,請參考"W3C Key Generators"

+

新增和刪除資料

+

在操作資料庫之前必須要先進行交易,交易來自資料庫物件,在交易中要指定涵蓋物件存檔範圍,然後也要決定是要變更資料庫或純粹讀取資料。交易共有三種種類,分別是讀取(read-only),讀寫(read/write), 以及版本變更(versionchange),如果只需要讀資料最好只使用讀取(read-only)交易,因為讀取(read-only)交易可以多重同步進行。

+

新增資料到資料庫

+

創建資料庫後,如果要寫入資料請這麼做:

+
var transaction = db.transaction(["customers"], "readwrite");
+// Note: Older experimental implementations use the deprecated constant IDBTransaction.READ_WRITE instead of "readwrite".
+// In case you want to support such an implementation, you can just write:
+// var transaction = db.transaction(["customers"], IDBTransaction.READ_WRITE);
+

呼叫transaction()方法會回傳一個交易物件。transaction()第一個接受參數代表交易涵蓋的物件存檔,雖然傳入空陣列會讓交易涵蓋所有物件存檔,但請不要這麼做,因為根據正式標準傳入空陣列應該要導致InvalidAccessError錯誤;第二個參數代表交易種類,不傳入的話預設為讀取交易,本例要寫入資料庫所以傳入讀寫("readwrite")。

+

交易的生命週期和事件循環關係密切。當我們發起交易又回到事件循環中後,如果忽略,那麼交易將轉成結束,唯一保持交易存活的方法是在交易上發出請求;當請求完成後我們會收到DOM事件,假設請求結果成功,我們可以在事件的回呼函數(callback中)繼續進行交易,反之,如果我們沒有繼續進行交易,那麼交易將結束,也就是說只要尚有未完成請求的話,交易就會繼續存活,如果收到TRANSACTION_INACTIVE_ERR錯誤那便意謂著交易早已結束,我們錯過了繼續進行交易的機會。

+

交易能收到三種事件: 錯誤(error)、中斷(abort)以及完成(complete),其中錯誤事件會向上傳遞,所以任何一個交易下轄的請求產生錯誤事件,該交易都會收到。如果交易收到錯誤事件時,瀏覽器預設行為會中斷交易,除非我們有在錯誤事件上呼叫preventDefault()阻擋瀏覽器預設行動,否則整筆交易都將取消、復原,這樣的設計告訴我們必須要思考如何處裡錯誤,或者說如果對每一個錯誤進行處裡過於麻煩,那麼至少加入一個概括性的錯誤處理器也是可以。只要不處裡錯誤或呼叫abort(),交易將取消、復原,然後中斷事件接著觸發,反之,當所有請求都完成後,我們會收到一個完成事件,所以說如果我們同時發起多項請求時,可以只追蹤單一交易而非個別請求,這樣會大大減輕我們的負擔。

+

有了交易之後便能夠從中取得物件存檔,有了物件存檔便能夠新增資料(請注意唯有在建立交易時指定的物件存檔能夠取得)。

+
// Do something when all the data is added to the database.
+transaction.oncomplete = function(event) {
+  alert("All done!");
+};
+
+transaction.onerror = function(event) {
+  // Don't forget to handle errors!
+};
+
+var objectStore = transaction.objectStore("customers");
+for (var i in customerData) {
+  var request = objectStore.add(customerData[i]);
+  request.onsuccess = function(event) {
+    // event.target.result == customerData[i].ssn;
+  };
+}
+

呼叫add方法可以加入一筆新資料,呼叫後會回傳一個IDBRequest物件,即為上方範例中的request,如果新增成功,request的成功事件會被觸發,而成功事件物件中有一個result屬性,這個result值剛好就等於新資料的資料鍵,所以說上方範例中的event.target.result剛好就等於顧客的ssn值(因為我們用ssn屬性作為資料鍵路徑)。請注意add方法只在當物件存檔中沒有相同資料鍵資料存在時有用,如果想要更動或是直接覆蓋現存資料請呼叫put方法。

+

移除資料

+

移除資料十分容易:

+
var request = db.transaction(["customers"], "readwrite")
+                .objectStore("customers")
+                .delete("444-44-4444");
+request.onsuccess = function(event) {
+  // It's gone!
+};
+

讀取資料

+

要圖取資料庫內的資料有數種途徑,第一個最簡單的途徑就是提供資料鍵,呼叫get方法取得資料:

+
var transaction = db.transaction(["customers"]);
+var objectStore = transaction.objectStore("customers");
+var request = objectStore.get("444-44-4444");
+request.onerror = function(event) {
+  // Handle errors!
+};
+request.onsuccess = function(event) {
+  // Do something with the request.result!
+  alert("Name for SSN 444-44-4444 is " + request.result.name);
+};
+

假設我們把錯誤處理放在資料庫層級,我們可以再縮短上面的程式碼如下:

+
db.transaction("customers").objectStore("customers").get("444-44-4444").onsuccess = function(event) {
+  alert("Name for SSN 444-44-4444 is " + event.target.result.name);
+};
+

呼叫transcation方法而不指定模式會開啟讀取(readonly)模式,接著取得我們的目標物件存檔,輸入目標資料的資料鍵,呼叫get方法取得請求物件,然後在請求物件上註冊成功事件處理器,當作業成功後,成功事件會觸發,成功事件的物件中含有請求物件(event.target如上述範例),請求物件中含有請求結果(event.target.result如上述範例)。

+

使用指標(Cursor)

+

使用get方法需要知道資料鍵,如果想要一一存取物件存檔中的資料,我們可以利用指標:

+
var objectStore = db.transaction("customers").objectStore("customers");
+
+objectStore.openCursor().onsuccess = function(event) {
+  var cursor = event.target.result;
+  if (cursor) {
+    alert("Name for SSN " + cursor.key + " is " + cursor.value.name);
+    cursor.continue();
+  }
+  else {
+    alert("No more entries!");
+  }
+};
+

openCursor方法第一個參數用來接受資料鍵範圍物件來限制存取資料範圍,第二個參數用來指定存取進行方向,像上面的範例程式便是以資料鍵由小到大之方向存取資料;呼叫openCursor方法後一樣會回傳一個請求物件,成功時成功事件會觸發,不過這裡有些地方要特別注意,當成功事件處裡函數被喚起時,指標物件(cursor)會存放在result屬性內(亦即上述event.target.result),cursor物件下有兩個屬性,key屬性是資料鍵,value屬性是資料值,如果要取得下一份資料就呼叫cursor的continue()方法,然後cursor物件就會指向下一份資料,當沒有資料時,cursor會是undefined,當請求一開始便找沒有資料,result屬性也會是undefined。

+

以下用cursor存取一遍資料後放在陣列中的作法相當常見:

+
var customers = [];
+
+objectStore.openCursor().onsuccess = function(event) {
+  var cursor = event.target.result;
+  if (cursor) {
+    customers.push(cursor.value);
+    cursor.continue();
+  }
+  else {
+    alert("Got all customers: " + customers);
+  }
+};
+
+ Warning: 以下範例不是IndexedDB標準!
+

Mozilla瀏覽器自己做了一個getAll()方法來方便一次取得所有cursor下的資料值,這個方法相當方便,不過請小心未來它有可能會消失。以下程式碼的效果和上面的一樣:

+
objectStore.getAll().onsuccess = function(event) {
+  alert("Got all customers: " + event.target.result);
+};
+

一一檢查cursor的value屬性較不利性能表現,因為物件是被動一一建立,然而呼叫getAll(),Gecko一定要一次建立所有物件,所以如果想要一次取得所有物件的資料值陣列使用getAll()比較好,如果想要一一檢查每筆資料則請利用cursor的方法。

+

使用索引

+

利用一定唯一的ssn碼作為資料鍵相當合乎邏輯(隱私權的問題先擱置一放,不在本文探討範圍)。不過當我們想要查詢使用者的名字的時候,如果沒有索引就需要一一檢查每一筆資料,十分沒有效率,所以我們可以建立name的索引。

+
var index = objectStore.index("name");
+index.get("Donna").onsuccess = function(event) {
+  alert("Donna's SSN is " + event.target.result.ssn);
+};
+

因為name不是唯一值,所以可能會有多筆資料符合"Donna"名字,此時呼叫get()會取得資料鍵最小值的資料。

+

如果我們想要查看特定名字下所有的資料,可以利用cursor。有兩種cursor能用在索引上,第一種一般cursor會比對索引值並回傳整份資料(物件存檔中的物件),第二種資料鍵cursor則只會回傳資料鍵值,請參考下方範例比較兩者差異:

+
index.openCursor().onsuccess = function(event) {
+  var cursor = event.target.result;
+  if (cursor) {
+    // cursor.key is a name, like "Bill", and cursor.value is the whole object.
+    alert("Name: " + cursor.key + ", SSN: " + cursor.value.ssn + ", email: " + cursor.value.email);
+    cursor.continue();
+  }
+};
+
+index.openKeyCursor().onsuccess = function(event) {
+  var cursor = event.target.result;
+  if (cursor) {
+    // cursor.key is a name, like "Bill", and cursor.value is the SSN.
+    // No way to directly get the rest of the stored object.
+    alert("Name: " + cursor.key + ", SSN: " + cursor.value);
+    cursor.continue();
+  }
+};
+

設定指標查詢範圍和方向

+

如果想要限定指標查詢範圍,那麼在乎叫openCursor()或openKeyCursor()時第一個參數要傳入IDBKeyRange物件以限制範圍。IDBKeyRange物件能夠只聚焦在單一資料鍵上或者一段上下限區間;上下限區間可以是封閉(含界限)或開放(不含界限),請看以下範例:

+
// Only match "Donna"
+var singleKeyRange = IDBKeyRange.only("Donna");
+
+// Match anything past "Bill", including "Bill"
+var lowerBoundKeyRange = IDBKeyRange.lowerBound("Bill");
+
+// Match anything past "Bill", but don't include "Bill"
+var lowerBoundOpenKeyRange = IDBKeyRange.lowerBound("Bill", true);
+
+// Match anything up to, but not including, "Donna"
+var upperBoundOpenKeyRange = IDBKeyRange.upperBound("Donna", true);
+
+// Match anything between "Bill" and "Donna", but not including "Donna"
+var boundKeyRange = IDBKeyRange.bound("Bill", "Donna", false, true);
+
+index.openCursor(boundKeyRange).onsuccess = function(event) {
+  var cursor = event.target.result;
+  if (cursor) {
+    // Do something with the matches.
+    cursor.continue();
+  }
+};
+

有時候我們會想要由大到小查看資料而非預設由小到大方向,傳入第二個"prev"字串便能做到:

+
objectStore.openCursor(null, "prev").onsuccess = function(event) {
+  var cursor = event.target.result;
+  if (cursor) {
+    // Do something with the entries.
+    cursor.continue();
+  }
+};
+

由於"name"索引不具唯一性,所以一個名字下可能會出現多筆資料,此時如果想要避開這多筆資料,請傳入"nextunique"或"prevunique"做為第二個方向參數,當傳入之後,如一個名字下遇到多筆資料,則只有資料鍵最小的資料會被回傳。

+
index.openKeyCursor(null, "nextunique").onsuccess = function(event) {
+  var cursor = event.target.result;
+  if (cursor) {
+    // Do something with the entries.
+    cursor.continue();
+  }
+};
+

關於可傳入的方向參數,請參考IDBCursor常數。

+

當網頁應用程式於瀏覽器另一個分頁開啟時變更版本

+

請思考以下狀況: 使用者在第一個瀏覽器分頁中使用著舊版本,然後使用者又打開第二個分頁載入網頁,此時我們在新分頁需要對資料庫進行升級,所以呼叫open()以更新版本開啟資料庫,但是由於第一個瀏覽器分頁並沒有關閉資料庫,因此第二個分頁的資料庫升級作業會被擋住。所以我們需要注意多個分頁同時開啟的狀況,每個分頁都得注意當發生資料庫升級事件時,要記得關閉資料庫,讓資料庫升級作業得以進行。實際作法如下:

+
var openReq = mozIndexedDB.open("MyTestDatabase", 2);
+
+openReq.onblocked = function(event) {
+  // If some other tab is loaded with the database, then it needs to be closed
+  // before we can proceed.
+  alert("Please close all other tabs with this site open!");
+};
+
+openReq.onupgradeneeded = function(event) {
+  // All other databases have been closed. Set everything up.
+  db.createObjectStore(/* ... */);
+  useDatabase(db);
+}
+
+openReq.onsuccess = function(event) {
+  var db = event.target.result;
+  useDatabase(db);
+  return;
+}
+
+function useDatabase(db) {
+  // Make sure to add a handler to be notified if another page requests a version
+  // change. We must close the database. This allows the other page to upgrade the database.
+  // If you don't do this then the upgrade won't happen until the user closes the tab.
+  db.onversionchange = function(event) {
+    db.close();
+    alert("A new version of this page is ready. Please reload!");
+  };
+
+  // Do stuff with the database.
+}
+
+

安全性

+

IndexedDB遵守同源政策,所以它綁定創建它的來源網站,其他來源網站無法存取。
+ 就像對載入{{ HTMLElement("frame") }}和{{ HTMLElement("iframe") }}網頁的第三方cookie所設下的安全性和隱私權考量限制,IndexedDB無法在載入{{ HTMLElement("frame") }}和{{ HTMLElement("iframe") }}網頁上運作,詳情請見{{ bug(595307) }}。

+

瀏覽器關閉風險

+

當瀏覽器關閉,例如使用者按下關閉鈕,任何未完成IndexedDB交易都將默默中止,這些交易不會完成,錯誤事件也不會觸發。既然瀏覽器可能隨時被關閉,我們無法完全指望任何特定交易一定會完成,或是依賴錯誤事件做出相應處理,針對這種狀況,我們需要注意:

+

第一、每一筆交易結束後都應該要保持資料庫完整性,例如說,有一串使用者編輯項目清單正要存入資料庫,我們如果先在一個交易中清除舊清單,然後在另一個交易中存入新清單,那就會面臨到清除完就清單後,新清單存入交易還來不及回存,瀏覽器就關閉的風險,而這個時候資料庫裡面的清單資料將消失。所以比較好的做法應該是在同一筆交易中完成清除舊清單和存入新清單。

+

第二、永遠不要在unload事件中執行資料庫交易,因為如果unload事件是觸發在瀏覽器關閉下,任何資料庫交易都不會發生,或許,瀏覽器(或分頁)打開時讀取資料庫,更新資料庫當使用者編輯資料,當瀏覽器(或分頁)關閉時儲存資料這樣的做法比較直覺,不過資料庫的操作是非同步進行地,所以瀏覽器關閉的執行會在資料庫操作前發生,進而中斷後續非同步的資料庫交易,所以在unload事件中執行資料庫交易是行不通地。

+

事實上不論瀏覽器是否正常關閉,都沒有任何方法保證IndexedDB交易能夠順利完成,請見{{ bug(870645) }}。

+

完整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

+
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

+
(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', "線上範例") }}

+

下一步

+

請參考IndexedDB文件,看看有甚麼IndexedDB API可供使用,實際試玩一下吧。

+

延伸閱讀

+

參照

+ +

相關教學

+ +

相關文章

+ +

Firefox

+ diff --git a/files/zh-tw/web/api/keyboardevent/index.html b/files/zh-tw/web/api/keyboardevent/index.html new file mode 100644 index 0000000000..31d75cdf1f --- /dev/null +++ b/files/zh-tw/web/api/keyboardevent/index.html @@ -0,0 +1,449 @@ +--- +title: KeyboardEvent +slug: Web/API/KeyboardEvent +tags: + - 待翻譯 +translation_of: Web/API/KeyboardEvent +--- +

{{APIRef("DOM Events")}}

+ +

KeyboardEvent objects 用來詳述使用者和網頁之間,經由鍵盤產生的互動。每個事件(event)都記錄著一次鍵盤動作。事件類型(keydownkeypresskeyup)用來表示鍵盤執行哪種動作。

+ +
注意: KeyboardEvent 僅顯示在鍵盤上發生的事。當你需要進行文字輸入的操作,請使用 HTML5 input event 代替 KeyboardEvent 。舉例來說,當使用者在手寫系統,例如平板電腦,輸入文字時,並不會啟動 key events 。
+ +

Constructor

+ +
+
{{domxref("KeyboardEvent.KeyboardEvent", "KeyboardEvent()")}}
+
建立一 KeyboardEvent object。
+
+ +

Methods

+ +

本介面( interface)亦繼承其父, {{domxref("UIEvent")}} 和 {{domxref("Event")}} ,的 methods

+ +
+
{{domxref("KeyboardEvent.getModifierState()")}}
+
回傳一 {{jsxref("Boolean")}}。用來表示當事件建立時,修飾鍵(例如 Alt、 Shift、 Ctrl、或是 Meta) 是否是按下的。
+
{{domxref("KeyboardEvent.initKeyEvent()")}}{{deprecated_inline}}
+
初始化一個 KeyboardEvent object。這個 method 只有 Gecko 有在使用(其他瀏覽器是使用 {{domxref("KeyboardEvent.initKeyboardEvent()")}}),並且不應該再繼續使用。現代的標準規範是使用 {{domxref("KeyboardEvent.KeyboardEvent", "KeyboardEvent()")}} constructor。
+
{{domxref("KeyboardEvent.initKeyboardEvent()")}}{{deprecated_inline}}
+
初始化一個 KeyboardEvent object。 Gecko 從未實作過該 method (Gecko 是使用 {{domxref("KeyboardEvent.initKeyEvent()")}}) ,並且不應該再繼續使用。現代的標準規範是使用 {{domxref("KeyboardEvent.KeyboardEvent", "KeyboardEvent()")}} constructor。
+
+ +

Properties

+ +

本介面( interface)亦繼承其父,{{domxref("UIEvent")}} 和 {{domxref("Event")}} ,的 properties 。

+ +
+
{{domxref("KeyboardEvent.altKey")}} {{Readonlyinline}}
+
一個 {{jsxref("Boolean")}} 。用來表示在事件建立時, Alt (OS X 中是 Option ) 鍵是否執行中。
+
{{domxref("KeyboardEvent.char")}} {{Non-standard_inline}}{{Deprecated_inline}}{{Readonlyinline}}
+
一個 {{domxref("DOMString")}} ,返回鍵盤對應的字符。若是該鍵對應一個實際的字符,則其值為對應該字符的一個非空的 Unicode 字串;若沒對應的話,則返回一個空字串。 +
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.
+ +
警告: 在 DOM Level 3 Events ,該 propertie 已被移除。現在只有 IE9+ 支持它。
+
+
{{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. +
警告: 此 attribute 已被淘汰。如果可以,建議使用 {{domxref("KeyboardEvent.key")}} 。
+
+
{{domxref("KeyboardEvent.code")}} {{Readonlyinline}}
+
一個 {{domxref("DOMString")}} 。返回事件對應的按鍵的代碼。
+
{{domxref("KeyboardEvent.ctrlKey")}} {{Readonlyinline}}
+
一個 {{jsxref("Boolean")}} 。用來表示在事件建立時, Ctrl 鍵是否執行中。
+
{{domxref("KeyboardEvent.isComposing")}} {{Readonlyinline}}
+
一個 {{jsxref("Boolean")}} 。用來表示其觸發時間是否在 compositionstartcompositionend 之間。
+
{{domxref("KeyboardEvent.key")}} {{Readonlyinline}}
+
一個 {{domxref("DOMString")}} ,用來事件對應的按鍵的值(key value)。
+
{{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. +
警告: 此 attribute 已被淘汰。如果可以,建議使用{{domxref("KeyboardEvent.key")}} 。
+
+
{{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 (on Mac keyboards, the ⌘ Command key; on Windows keyboards, the Windows key ()) 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. +
警告: 此 attribute 已被淘汰。如果可以,建議使用 {{domxref("KeyboardEvent.key")}} 。
+
+
+ +

注意

+ +

KeyboardEvent 有 keydownkeypresskeyup 三種事件。對大多數的按鍵而言, Gecko 觸發事件的順序如下:

+ +
    +
  1. 當按鍵按下時,會送出 keydown event 。
  2. +
  3. 當按鍵不是特殊鍵( modifier key),例如CtrlAlt……等等,會送出 keypress event 。
  4. +
  5. 當按鍵放開時,會送出 keyup event 。
  6. +
+ +

特殊狀況

+ +

某些按鍵,例如 Caps Lock 、 Num Lock 和 Scroll Lock 能切換鍵盤上的 LED 燈。在 Windows 和 Linux 系統上,這些按鍵只會觸發 keydown 和 keyup 事件。但是 Linux 上的 Firefox 12 或更早的版本亦會觸發 keypress 事件。

+ +

而在 Mac 電腦則不同, Caps Lock 只會觸發 keydown 事件;而 Num Lock 則是只有舊版的 Mac 電腦(2007 或之前的版本)才有,現在的 Mac 即便使用外部鍵盤也不支援  Num Lock 。雖說舊版的 Mac 電腦支援 Num Lock 鍵,但 Num Lock  並不會執行任何 KeyboardEvent;而 Gecko 瀏覽器在特殊情況(外接一個有 F14 的鍵盤)下能支援 Scroll Lock ,但是它會產生 keypress 事件。這個異常狀態是個 bug ,詳情可參考 {{bug(602812)}}。

+ +

自動迴圈(Auto-Repeat )的執行

+ +

當按鍵按下去不放時,它會開始一個自動迴圈。並導致觸發一系列的相似事件,如下所示:

+ +
    +
  1. keydown
  2. +
  3. keypress
  4. +
  5. keydown
  6. +
  7. keypress
  8. +
  9. (不斷重複,直到使用者放開按鍵)
  10. +
  11. keyup
  12. +
+ +

在 DOM Level 3 說明書有提及這問題是會發生的。其中所存在的問題如下說明:

+ +

部分 GTK 環境,例如 Ubuntu 9.4 ,的自動迴圈

+ +

部分的 GTK-based 環境之中,自動迴圈在發生的過程中會自動觸發電腦本機的 key-up 事件。然而,對 Gecko 而言,並沒有方法可以分辨使用者重複點擊按鍵與自動迴圈(按鍵按住不放)的差異。在這類的環境下,按鍵按住不放會重複執行下列事件:

+ +
    +
  1. keydown
  2. +
  3. keypress
  4. +
  5. keyup
  6. +
  7. keydown
  8. +
  9. keypress
  10. +
  11. keyup
  12. +
  13. (不斷重複,直到使用者放開按鍵)
  14. +
  15. keyup
  16. +
+ +

不幸地,在這些環境之下,web content 亦沒有方法告訴使用者重複點擊按鍵與自動迴圈的差異。

+ +

Gecko 5.0 以前的自動迴圈

+ +

Gecko 5.0 {{geckoRelease('5.0')}} 以前,在不同平台上,鍵盤的處理與現在相比較不統一。

+ +
+
Windows
+
自動迴圈的結果與 Gecko 4.0 或更新的版本類似
+
Mac
+
在第一個 keydown 執行後,僅執行 keypress 事件,一直到案件放開(即送出 keyup 事件指令),過程中不會送出任何 keydown 事件。
+
Linux
+
鍵盤事件的執行根據平台不同而有所不同。它有可能表現得像是 Windows 也有可能像 Mac ,這取決於本地的事件模型(native event model)是如何執行的。
+
+ +

範例

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

規格

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM3 Events', '#interface-KeyboardEvent', 'KeyboardEvent')}}{{Spec2('DOM3 Events')}}原始定義
+ +

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()")}}.

+ +

瀏覽器支援度

+ +

More compatibility data is available on other pages:

+ + + +

{{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/zh-tw/web/api/keyboardevent/keyboardevent/index.html b/files/zh-tw/web/api/keyboardevent/keyboardevent/index.html new file mode 100644 index 0000000000..3af92514bb --- /dev/null +++ b/files/zh-tw/web/api/keyboardevent/keyboardevent/index.html @@ -0,0 +1,202 @@ +--- +title: KeyboardEvent() +slug: Web/API/KeyboardEvent/KeyboardEvent +translation_of: Web/API/KeyboardEvent/KeyboardEvent +--- +

{{APIRef("DOM Events")}}

+ +

KeyboardEvent() constructor 能用來建立一個新的 {{domxref("KeyboardEvent")}}。

+ +

語法

+ +
 event = new KeyboardEvent(typeArg, KeyboardEventInit);
+ +

參數

+ +
+
typeArg
+
一 {{domxref("DOMString")}} 用來表示事件名稱。
+
KeyboardEventInit{{optional_inline}}
+
一個 KeyboardEventInit dictionary,能接受以下參數: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
參數可選默認值類型說明
"key"""{{domxref("DOMString")}}用來設定 {{domxref("KeyboardEvent.key")}} 的值
"code"""{{domxref("DOMString")}}用來設定 {{domxref("KeyboardEvent.code")}} 的值
"location"0unsigned long用來設定 {{domxref("KeyboardEvent.location")}} 的值
"ctrlKey"false{{jsxref("Boolean")}}用來設定 {{domxref("KeyboardEvent.ctrlKey")}} 的值
"shiftKey"false{{jsxref("Boolean")}}用來設定 {{domxref("KeyboardEvent.shiftKey")}} 的值
"altKey"false{{jsxref("Boolean")}}用來設定 {{domxref("KeyboardEvent.altKey")}} 的值
"metaKey"false{{jsxref("Boolean")}}用來設定 {{domxref("KeyboardEvent.metaKey")}} 的值
"repeat"false{{jsxref("Boolean")}}用來設定 {{domxref("KeyboardEvent.repeat")}} 的值
"isComposing"false{{jsxref("Boolean")}}用來設定 {{domxref("KeyboardEvent.isComposing")}} 的值
"charCode"0unsigned long用來設定 {{domxref("KeyboardEvent.charCode")}} 的值
"keyCode"0unsigned long用來設定 {{domxref("KeyboardEvent.keyCode")}} 的值
"which"0unsigned long用來設定 {{domxref("KeyboardEvent.which")}} 的值
+ +
+

 KeyboardEventInit dictionary 亦接受 {{domxref("UIEvent.UIEvent", "UIEventInit")}} 和{{domxref("Event.Event", "EventInit")}} 所接受的參數。

+
+
+
+ +

規格

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM3 Events','#interface-KeyboardEvent','KeyboardEvent()')}}{{Spec2('DOM3 Events')}}Initial definition.
+ +

瀏覽器支援度

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatVersionUnknown() }}{{ CompatGeckoDesktop(13) }}{{ CompatNo() }}{{ CompatVersionUnknown() }}{{ CompatUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{ CompatUnknown }}{{ CompatVersionUnknown() }}{{ CompatGeckoMobile(31) }}{{ CompatNo() }}{{ CompatVersionUnknown() }}{{ CompatUnknown() }}{{CompatVersionUnknown}}
+
+ +

延伸閱讀

+ + diff --git a/files/zh-tw/web/api/media_streams_api/index.html b/files/zh-tw/web/api/media_streams_api/index.html new file mode 100644 index 0000000000..6813a5d1d6 --- /dev/null +++ b/files/zh-tw/web/api/media_streams_api/index.html @@ -0,0 +1,87 @@ +--- +title: Media Capture and Streams API (Media Stream) +slug: Web/API/Media_Streams_API +tags: + - API + - Audio + - Media + - Video +translation_of: Web/API/Media_Streams_API +--- +
{{DefaultAPISidebar("Media Capture and Streams")}}
+ +

媒體捕獲和流API,通常被稱為媒體流API或者乾脆MediaStream API,是關係到一個API的WebRTC提供流式音頻和視頻數據的支持。它提供了用於處理流及其組成軌道的接口和方法,與數據格式關聯的約束,異步使用數據時的成功和錯誤回調以及在此過程中觸發的事件。

+ +

概念和用法

+ +

該API基於{{domxref("MediaStream")}}對象的操作,該對象代表與音頻或視頻相關的數據流。請參閱“獲取視頻”中的示例。

+ +

A MediaStream consists of zero or more {{domxref("MediaStreamTrack")}} objects, representing various audio or video tracks. Each MediaStreamTrack may have one or more channels. The channel represents the smallest unit of a media stream, such as an audio signal associated with a given speaker, like left or right in a stereo audio track.

+ +

MediaStream objects have a single input and a single output. A MediaStream object generated by {{domxref("MediaDevices.getUserMedia", "getUserMedia()")}} is called local, and has as its source input one of the user's cameras or microphones. A non-local MediaStream may be representing to a media element, like {{HTMLElement("video")}} or {{HTMLElement("audio")}}, a stream originating over the network, and obtained via the WebRTC {{domxref("RTCPeerConnection")}} API, or a stream created using the Web Audio API {{domxref("MediaStreamAudioSourceNode")}}.

+ +

The output of the MediaStream object is linked to a consumer. It can be a media elements, like {{HTMLElement("audio")}} or {{HTMLElement("video")}}, the WebRTC {{domxref("RTCPeerConnection")}} API or a Web Audio API {{domxref("MediaStreamAudioSourceNode")}}.

+ +

Interfaces

+ +

In these reference articles, you'll find the fundamental information you'll need to know about each of the interfaces that make up the Media Capture and Streams API.

+ +
+ +
+ +

Early versions of the Media Capture and Streams API specification included separate AudioStreamTrack and VideoStreamTrack interfaces—each based upon {{domxref("MediaStreamTrack")}}—which represented streams of those types. These no longer exist, and you should update any existing code to instead use MediaStreamTrack directly.

+ +

Events

+ +
+ +
+ +

Guides and tutorials

+ +

The articles below provide additional guidance and how-to information that will help you learn to use the API, and how to perform specific tasks that you may wish to handle.

+ +

{{LandingPageListSubpages}}

+ +

Browser compatibility

+ + + +

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

+ +

也可以看看

+ + diff --git a/files/zh-tw/web/api/mediaquerylist/index.html b/files/zh-tw/web/api/mediaquerylist/index.html new file mode 100644 index 0000000000..ef3128a4b8 --- /dev/null +++ b/files/zh-tw/web/api/mediaquerylist/index.html @@ -0,0 +1,144 @@ +--- +title: MediaQueryList +slug: Web/API/MediaQueryList +translation_of: Web/API/MediaQueryList +--- +
{{APIRef("CSSOM View")}}{{SeeCompatTable}}
+ +

MediaQueryList 物件維護一組針對 {{ domxref("document") }} 的 media querie , 並且當 media querie 相對應的文件狀態改變時,觸發註冊的事件處理器通知之。

+ +

MediaQueryList 物件讓我們不用一直定期去偵測,而是直接去觀察文件的狀態變化。

+ +

Method overview

+ + + + + + + + + + +
void addListener(MediaQueryListListener listener);
void removeListener(MediaQueryListListener listener);
+ +

Properties

+ + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
matchesbooleantrue 當 {{ domxref("document") }} 目前狀態符合 media query list 所維護的條件; 否則 false。 唯獨
mediaDOMString序列化 (serialized) 的 media query list.
+ +

Methods

+ +

addListener()

+ +

添加一個新的事件處理器 (listener),若 listener 已存在則無作用。

+ +
void addListener(
+  MediaQueryListListener listener
+);
+ +

Parameter (for addListener method)

+ +
+
listener
+
當 media query 對應的狀態改變時所觸發的事件處理函數 ({{ domxref("MediaQueryListListener") }})。
+
+ +

removeListener()

+ +

移除一個事件處理器 (listener),若 listener 不存在則無作用。

+ +
void removeListener(
+  MediaQueryListListener listener
+);
+ +

Parameter (for removeListener method)

+ +
+
listener
+
欲移除的事件處理函數 ({{ domxref("MediaQueryListListener") }})。
+
+ +

瀏覽器相容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support9{{ CompatGeckoDesktop("6.0") }}1012.15
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

 

+ +

規範標準

+ + + +

延伸閱讀

+ + diff --git a/files/zh-tw/web/api/mediasource/activesourcebuffers/index.html b/files/zh-tw/web/api/mediasource/activesourcebuffers/index.html new file mode 100644 index 0000000000..90777f675c --- /dev/null +++ b/files/zh-tw/web/api/mediasource/activesourcebuffers/index.html @@ -0,0 +1,126 @@ +--- +title: MediaSource.activeSourceBuffers +slug: Web/API/MediaSource/activeSourceBuffers +translation_of: Web/API/MediaSource/activeSourceBuffers +--- +
{{APIRef("Media Source Extensions")}}{{SeeCompatTable}}
+ +

activeSourceBuffers 是 {{domxref("MediaSource")}} 介面的唯讀屬性,回傳一個 {{domxref("SourceBufferList")}} 物件,含有在 {{domxref("SourceBuffers")}} 之中的 {{domxref("SourceBuffer")}} 物件子集合—物件的串列提供被選擇的影片軌 (video track), 啟用的音軌 (audio tracks), 以及顯示或隱藏的字軌。

+ +

語法

+ +
var myActiveSourceBuffers = mediaSource.activeSourceBuffers;
+ +

回傳值

+ +

一個 {{domxref("SourceBufferList")}} 。

+ +

範例

+ +

以下的片段基於 Nick Desaulniers 所編纂的簡單範例(觀看實際演示,或者下載原始碼 以利更進一步研究。)

+ +
function sourceOpen (_) {
+  //console.log(this.readyState); // open
+  var mediaSource = this;
+  var sourceBuffer = mediaSource.addSourceBuffer(mimeCodec);
+  fetchAB(assetURL, function (buf) {
+    sourceBuffer.addEventListener('updateend', function (_) {
+      mediaSource.endOfStream();
+      console.log(mediaSource.activeSourceBuffers);
+      // will contain the source buffer that was added above,
+      // as it is selected for playing in the video player
+      video.play();
+      //console.log(mediaSource.readyState); // ended
+    });
+    sourceBuffer.appendBuffer(buf);
+  });
+};
+
+...
+ +

規格

+ + + + + + + + + + + + + + +
規格狀態注釋
{{SpecName('Media Source Extensions', '#widl-MediaSource-activeSourceBuffers', 'activeSourceBuffers')}}{{Spec2('Media Source Extensions')}}Initial definition.
+ +

相容性表格

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support23{{CompatVersionUnknown}}{{CompatGeckoDesktop("25.0")}}[1]
+ {{CompatGeckoDesktop("42.0")}}
11[2]158
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support4.4.4{{CompatVersionUnknown}} +

{{CompatNo}}

+
{{CompatNo}}1130{{CompatNo}}
+
+ +

[1] 在切換 about:config 偏好設定 media.mediasource.enabled 為 true 時可以使用。此外,支援只限於白名單內的網站,如:YouTube, Netflix, 以及其他熱門的串流網站。白名單已經被移除且 Media Source Extensions 在 42+ 對所有網站已預設為啟用。

+ +

[2] 只在 Windows 8+ 上有效。

+ +

相關資料

+ + diff --git a/files/zh-tw/web/api/mediasource/duration/index.html b/files/zh-tw/web/api/mediasource/duration/index.html new file mode 100644 index 0000000000..b9fab966e4 --- /dev/null +++ b/files/zh-tw/web/api/mediasource/duration/index.html @@ -0,0 +1,149 @@ +--- +title: MediaSource.duration +slug: Web/API/MediaSource/duration +translation_of: Web/API/MediaSource/duration +--- +
{{APIRef("Media Source Extensions")}}{{SeeCompatTable}}
+ +

{{domxref("MediaSource")}} 介面的 duration 屬性用來取得以及設置正被表示的媒體時間長度。

+ +

語法

+ +
mediaSource.duration = 5.5; // 5.5 seconds
+
+var myDuration = mediaSource.duration;
+ +

回傳值

+ +

單位為秒的 double 型別。

+ +

錯誤

+ +

當設置此屬性一個新的值時以下錯誤可能發生。

+ + + + + + + + + + + + + + + + + + +
錯誤解釋
InvalidAccessError嘗試設置的時間長度是負值,或者 NaN
InvalidStateError{{domxref("MediaSource.readyState")}} 不是 open,或者 {{domxref("MediaSource.sourceBuffers")}} 中一個或多個以上的 {{domxref("SourceBuffer")}} 物件正在被更新(例如:他們的 {{domxref("SourceBuffer.updating")}} 屬性為 true。)
+ +

範例

+ +

以下的片段基於 Nick Desaulniers 所編纂的簡單範例(觀看實際演示,或者下載原始碼以利更進一步研究。)

+ +
function sourceOpen (_) {
+  //console.log(this.readyState); // open
+  var mediaSource = this;
+  var sourceBuffer = mediaSource.addSourceBuffer(mimeCodec);
+  fetchAB(assetURL, function (buf) {
+    sourceBuffer.addEventListener('updateend', function (_) {
+      mediaSource.endOfStream();
+      mediaSource.duration = 120;
+      video.play();
+      //console.log(mediaSource.readyState); // ended
+    });
+    sourceBuffer.appendBuffer(buf);
+  });
+};
+
+...
+ +

規格

+ + + + + + + + + + + + + + +
規格狀態注釋
{{SpecName('Media Source Extensions', '#widl-MediaSource-duration', 'duration')}}{{Spec2('Media Source Extensions')}}Initial definition.
+ +

相容性表格

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support23{{CompatVersionUnknown}}{{CompatGeckoDesktop("25.0")}}[1]
+ {{CompatGeckoDesktop("42.0")}}
11[2]158
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support4.4.4{{CompatVersionUnknown}} +

{{CompatNo}}

+
{{CompatNo}}1130{{CompatNo}}
+
+ +

[1] 在切換 about:config 偏好設定 media.mediasource.enabledtrue時可以使用。此外,支援只限於白名單內的網站,如:YouTube, Netflix, 以及其他熱門的串流網站。白名單已經被移除且 Media Source Extensions 在 42+ 對所有網站已預設為啟用。

+ +

[2] 只在 Windows 8+ 上有效。

+ +

相關資料

+ + diff --git a/files/zh-tw/web/api/mediasource/index.html b/files/zh-tw/web/api/mediasource/index.html new file mode 100644 index 0000000000..0006121f46 --- /dev/null +++ b/files/zh-tw/web/api/mediasource/index.html @@ -0,0 +1,144 @@ +--- +title: MediaSource +slug: Web/API/MediaSource +translation_of: Web/API/MediaSource +--- +

{{APIRef("Media Source Extensions")}}{{SeeCompatTable}}

+ +

Media Source Extensions APIMediaSource 介面代表 {{domxref("HTMLMediaElement")}} 物件的媒體資料來源。一個 MediaSource 物件可以被附加到一個 {{domxref("HTMLMediaElement")}} 以被用戶代理 (user agent) 播放。

+ +

{{InheritanceDiagram}}

+ +

建構子 (Constructor)

+ +
+
{{domxref("MediaSource.MediaSource", "MediaSource()")}}
+
建構且回傳一個新的 MediaSource 物件但不與任何來源緩衝 (source buffers) 關聯 (associate)。
+
+ +

屬性 (Properties)

+ +
+
{{domxref("MediaSource.sourceBuffers")}} {{readonlyInline}}
+
回傳一個含有與此 MediaSource 關聯的 {{domxref("SourceBuffer")}} 物件串列的 {{domxref("SourceBufferList")}} 物件。
+
{{domxref("MediaSource.activeSourceBuffers")}} {{readonlyInline}}
+
回傳一個 {{domxref("SourceBufferList")}} 物件,含有 {{domxref("SourceBuffers")}} 的子集合 {{domxref("SourceBuffer")}} 物件 — 物件的串列提供被選擇的影片軌 (video track), 啟用的音軌 (audio tracks), 以及顯示或隱藏的字軌。
+
{{domxref("MediaSource.readyState")}} {{readonlyInline}}
+
回傳一個列舉類型表示目前 MediaSource 的狀態:沒有附加到媒體元件 (closed),已經附加且可以接收 {{domxref("SourceBuffer")}} 物件 (open),已經附加但是串流已經經由 {{domxref("MediaSource.endOfStream()")}} 結束 (ended)。
+
{{domxref("MediaSource.duration")}}
+
取得或設置現在正被表示的媒體的時間長度。
+
+

事件處理函數 (Event handlers)

+ + +
+
{{domxref("MediaSource.onsourceclose")}}
+
sourceclose 事件的事件處理函數。
+
{{domxref("MediaSource.onsourceended")}}
+
sourceended 事件的事件處理函數。
+
{{domxref("MediaSource.onsourceopen")}}
+
sourceopen 事件的事件處理函數。
+
+ +
+
+ +
+
+ +

方法 (Methods)

+ +

從親介面 (parent interface) {{domxref("EventTarget")}} 繼承屬性。

+ +
+
{{domxref("MediaSource.addSourceBuffer()")}}
+
依據指定的 MIME 類型建立一個新的 {{domxref("SourceBuffer")}} 且將其加入 MediaSource 的 {{domxref("SourceBuffers")}} 串列。
+
{{domxref("MediaSource.clearLiveSeekableRange()")}}
+
清除先前藉由呼叫 setLiveSeekableRange() 所設定的可尋找範圍。
+
{{domxref("MediaSource.endOfStream()")}}
+
示意串流的結束。
+
{{domxref("MediaSource.removeSourceBuffer()")}}
+
從與此 MediaSource 物件關聯的 {{domxref("SourceBuffers")}} 串列移除指定的 {{domxref("SourceBuffer")}}。
+
{{domxref("MediaSource.setLiveSeekableRange()")}}
+
設定使用者可以在媒體元素中的可尋找範圍。
+
+ +

靜態方法 (Static methods)

+ +
+
{{domxref("MediaSource.isTypeSupported()")}}
+
回傳一個 {{domxref("Boolean")}} 值表示指定的 MIME 類型是否被現在的用戶代理支援 — 意即可否成功的為該 MIME 類型建立 {{domxref("SourceBuffer")}} 物件。
+
+ +

範例

+ +

以下簡單的範例儘快的載入一個個影片塊 (chunk) 且儘快的播放。這個範例是由 Nick Desaulniers 所撰寫且可以在此實際觀看(您也可以下載原始碼以更進一步研究)

+ +
var video = document.querySelector('video');
+
+var assetURL = 'frag_bunny.mp4';
+// Need to be specific for Blink regarding codecs
+// ./mp4info frag_bunny.mp4 | grep Codec
+var mimeCodec = 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"';
+
+if ('MediaSource' in window && MediaSource.isTypeSupported(mimeCodec)) {
+  var mediaSource = new MediaSource();
+  //console.log(mediaSource.readyState); // closed
+  video.src = URL.createObjectURL(mediaSource);
+  mediaSource.addEventListener('sourceopen', sourceOpen);
+} else {
+  console.error('Unsupported MIME type or codec: ', mimeCodec);
+}
+
+function sourceOpen (_) {
+  //console.log(this.readyState); // open
+  var mediaSource = this;
+  var sourceBuffer = mediaSource.addSourceBuffer(mimeCodec);
+  fetchAB(assetURL, function (buf) {
+    sourceBuffer.addEventListener('updateend', function (_) {
+      mediaSource.endOfStream();
+      video.play();
+      //console.log(mediaSource.readyState); // ended
+    });
+    sourceBuffer.appendBuffer(buf);
+  });
+};
+
+function fetchAB (url, cb) {
+  console.log(url);
+  var xhr = new XMLHttpRequest;
+  xhr.open('get', url);
+  xhr.responseType = 'arraybuffer';
+  xhr.onload = function () {
+    cb(xhr.response);
+  };
+  xhr.send();
+};
+ +

規格

+ + + + + + + + + + + + + + +
規格狀態註釋
{{SpecName('Media Source Extensions', '#mediasource', 'MediaSource')}}{{Spec2('Media Source Extensions')}}Initial definition.
+ +

相容性表格

+ +
{{Compat("api.MediaSource")}}
+ +

相關資料

+ + diff --git a/files/zh-tw/web/api/mediasource/mediasource/index.html b/files/zh-tw/web/api/mediasource/mediasource/index.html new file mode 100644 index 0000000000..54e9e6dfef --- /dev/null +++ b/files/zh-tw/web/api/mediasource/mediasource/index.html @@ -0,0 +1,122 @@ +--- +title: MediaSource.MediaSource() +slug: Web/API/MediaSource/MediaSource +translation_of: Web/API/MediaSource/MediaSource +--- +
{{APIRef("Media Source Extensions")}}{{SeeCompatTable}}
+ +

{{domxref("MediaSource")}} 介面的 MediaSource() 建構子建構且回傳一個沒有與任何來源緩衝 (source buffer) 關聯的新 MediaSource 物件。

+ +

語法

+ +
var mediaSource = new MediaSource();
+ +

參數

+ +

無。

+ +

範例

+ +

以下的片段擷取自 Nick Desaulniers 所編纂的簡單範例(觀看實際演示,或者下載原始碼 以利更進一步研究。)

+ +
var video = document.querySelector('video');
+
+var assetURL = 'frag_bunny.mp4';
+// Need to be specific for Blink regarding codecs
+// ./mp4info frag_bunny.mp4 | grep Codec
+var mimeCodec = 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"';
+
+if ('MediaSource' in window && MediaSource.isTypeSupported(mimeCodec)) {
+  var mediaSource = new MediaSource;
+  //console.log(mediaSource.readyState); // closed
+  video.src = URL.createObjectURL(mediaSource);
+  mediaSource.addEventListener('sourceopen', sourceOpen);
+} else {
+  console.error('Unsupported MIME type or codec: ', mimeCodec);
+}
+
+...
+
+ +

規格

+ + + + + + + + + + + + + + +
規格狀態註釋
{{SpecName('Media Source Extensions', '#mediasource', 'MediaSource')}}{{Spec2('Media Source Extensions')}}Initial definition.
+ +

相容性表格

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support23{{CompatGeckoDesktop("25.0")}}[1]
+ {{CompatGeckoDesktop("42.0")}}
11[2]158
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support4.4.4 +

{{CompatNo}}

+
{{CompatNo}}1130{{CompatNo}}
+
+ +

[1] 在切換 about:config 偏好設定 media.mediasource.enabled 為 true 時可以使用。此外,支援只限於白名單內的網站,如:YouTube, Netflix, 以及其他熱門的串流網站。白名單已經被移除且 Media Source Extensions 在 42+ 對所有網站已預設為啟用。

+ +

[2] 只在 Windows 8+ 上有效。

+ +

相關資料

+ + diff --git a/files/zh-tw/web/api/mediasource/readystate/index.html b/files/zh-tw/web/api/mediasource/readystate/index.html new file mode 100644 index 0000000000..b7e5f1835b --- /dev/null +++ b/files/zh-tw/web/api/mediasource/readystate/index.html @@ -0,0 +1,136 @@ +--- +title: MediaSource.readyState +slug: Web/API/MediaSource/readyState +translation_of: Web/API/MediaSource/readyState +--- +
{{APIRef("Media Source Extensions")}}{{SeeCompatTable}}
+ +

{{domxref("MediaSource")}} 介面的唯讀屬性 readyState 回傳表示當前 MediaSource 狀態的列舉值。三種可能的值為:

+ + + +

語法

+ +
var myReadyState = mediaSource.readyState;
+ +

回傳值

+ +

一個 {{domxref("DOMString")}}。

+ +

範例

+ +

以下片段是由 Nick Desaulniers 所撰寫的簡單範例(在此實際觀看,或者下載原始碼以更進一步研究)

+ +
if ('MediaSource' in window && MediaSource.isTypeSupported(mimeCodec)) {
+  var mediaSource = new MediaSource;
+  //console.log(mediaSource.readyState); // closed
+  video.src = URL.createObjectURL(mediaSource);
+  mediaSource.addEventListener('sourceopen', sourceOpen);
+} else {
+  console.error('Unsupported MIME type or codec: ', mimeCodec);
+}
+
+function sourceOpen (_) {
+  //console.log(this.readyState); // open
+  var mediaSource = this;
+  var sourceBuffer = mediaSource.addSourceBuffer(mimeCodec);
+  fetchAB(assetURL, function (buf) {
+    sourceBuffer.addEventListener('updateend', function (_) {
+      mediaSource.endOfStream();
+      video.play();
+      //console.log(mediaSource.readyState); // ended
+    });
+    sourceBuffer.appendBuffer(buf);
+  });
+};
+ +

規格

+ + + + + + + + + + + + + + +
規格狀態註釋
{{SpecName('Media Source Extensions', '#widl-MediaSource-readyState', 'readyState')}}{{Spec2('Media Source Extensions')}}Initial definition.
+ +

相容性表格

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support23{{CompatVersionUnknown}}{{CompatGeckoDesktop("25.0")}}[1]
+ {{CompatGeckoDesktop("42.0")}}
11[2]158
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support4.4.4{{CompatVersionUnknown}} +

{{CompatNo}}

+
{{CompatNo}}1130{{CompatNo}}
+
+ +

[1] 在切換 about:config preference media.mediasource.enabled 為 true 時可以使用。此外,支援只限於白名單內的網站,如:YouTube, Netflix, 以及其他熱門的串流網站。白名單已經被移除且 Media Source Extensions 在 42+ 對所有網站已預設為啟用。

+ +

[2] 只在 Windows 8+ 上有效。

+ +

相關資料

+ + diff --git a/files/zh-tw/web/api/mouseevent/index.html b/files/zh-tw/web/api/mouseevent/index.html new file mode 100644 index 0000000000..43f2a3a26d --- /dev/null +++ b/files/zh-tw/web/api/mouseevent/index.html @@ -0,0 +1,317 @@ +--- +title: MouseEvent +slug: Web/API/MouseEvent +translation_of: Web/API/MouseEvent +--- +

{{APIRef("DOM Events")}}

+ +

MouseEvent 介面表示了由使用者經指標裝置(如滑鼠)進行互動所發生的事件。常見的 MouseEvent 實作事件包括了 {{event("click")}}、{{event("dblclick")}}、{{event("mouseup")}} 與 {{event("mousedown")}}。

+ +

MouseEvent 繼承自 {{domxref("UIEvent")}},而 UIEvent 則繼承自 {{domxref("Event")}}。雖然 {{domxref("MouseEvent.initMouseEvent()")}} 方法仍然向下相容新的瀏覽器,但現今應該使用 {{domxref("MouseEvent.MouseEvent", "MouseEvent()")}} 建構式來建立 MouseEvent 物件。

+ +

另外還有一些特定的事件繼承自 MouseEvent:{{domxref("WheelEvent")}} 及 {{domxref("DragEvent")}}。

+ +

建構式

+ +
+
{{domxref("MouseEvent.MouseEvent", "MouseEvent()")}}
+
建立一個 MouseEvent 物件。
+
+ +

屬性

+ +

此介面也繼承了其父介面 {{domxref("UIEvent")}} 與 {{domxref("Event")}} 的屬性

+ +
+
{{domxref("MouseEvent.altKey")}} {{readonlyinline}}
+
Returns true if the alt key was down when the mouse event was fired.
+
{{domxref("MouseEvent.button")}} {{readonlyinline}}
+
The button number that was pressed when the mouse event was fired. 
+
{{domxref("MouseEvent.buttons")}} {{readonlyinline}} {{gecko_minversion_inline("15.0")}}
+
+

The buttons being pressed when the mouse event was fired

+
+
{{domxref("MouseEvent.clientX")}} {{readonlyinline}}
+
The X coordinate of the mouse pointer in local (DOM content) coordinates.
+
{{domxref("MouseEvent.clientY")}} {{readonlyinline}}
+
The Y coordinate of the mouse pointer in local (DOM content) coordinates.
+
{{domxref("MouseEvent.ctrlKey")}} {{readonlyinline}}
+
Returns true if the control key was down when the mouse event was fired.
+
{{domxref("MouseEvent.metaKey")}} {{readonlyinline}}
+
Returns true if the meta key was down when the mouse event was fired.
+
{{domxref("MouseEvent.movementX")}} {{readonlyinline}}
+
The X coordinate of the mouse pointer relative to the position of the last {{event("mousemove")}} event.
+
{{domxref("MouseEvent.movementY")}} {{readonlyinline}}
+
The Y coordinate of the mouse pointer relative to the position of the last {{event("mousemove")}} event.
+
{{domxref("MouseEvent.offsetX")}} {{readonlyinline}}{{experimental_inline}}
+
The X coordinate of the mouse pointer relative to the position of the padding edge of the target node.
+
{{domxref("MouseEvent.offsetY")}} {{readonlyinline}}{{experimental_inline}}
+
The Y coordinate of the mouse pointer relative to the position of the padding edge of the target node.
+
{{domxref("MouseEvent.pageX")}} {{readonlyinline}}{{experimental_inline}}
+
The X coordinate of the mouse pointer relative to the whole document.
+
{{domxref("MouseEvent.pageY")}} {{readonlyinline}}{{experimental_inline}}
+
The Y coordinate of the mouse pointer relative to the whole document.
+
{{domxref("MouseEvent.region")}} {{readonlyinline}}
+
Returns the id of the hit region affected by the event. If no hit region is affected, null is returned.
+
{{domxref("MouseEvent.relatedTarget")}} {{readonlyinline}}
+
+

The secondary target for the event, if there is one.

+
+
{{domxref("MouseEvent.screenX")}} {{readonlyinline}}
+
The X coordinate of the mouse pointer in global (screen) coordinates.
+
{{domxref("MouseEvent.screenY")}} {{readonlyinline}}
+
The Y coordinate of the mouse pointer in global (screen) coordinates.
+
{{domxref("MouseEvent.shiftKey")}} {{readonlyinline}}
+
Returns true if the shift key was down when the mouse event was fired.
+
{{domxref("MouseEvent.which")}} {{non-standard_inline}} {{readonlyinline}}
+
The button being pressed when the mouse event was fired.
+
{{domxref("MouseEvent.mozPressure")}} {{non-standard_inline()}} {{readonlyinline}}
+
The amount of pressure applied to a touch or tablet device when generating the event; this value ranges between 0.0 (minimum pressure) and 1.0 (maximum pressure).
+
{{domxref("MouseEvent.mozInputSource")}} {{non-standard_inline()}} {{readonlyinline}}
+
+

The type of device that generated the event (one of the MOZ_SOURCE_* constants listed below). This lets you, for example, determine whether a mouse event was generated by an actual mouse or by a touch event (which might affect the degree of accuracy with which you interpret the coordinates associated with the event).

+
+
{{domxref("MouseEvent.webkitForce")}} {{non-standard_inline()}} {{readonlyinline}}
+
The amount of pressure applied when clicking
+
{{domxref("MouseEvent.x")}} {{experimental_inline}}{{readonlyinline}}
+
Alias for {{domxref("MouseEvent.clientX")}}.
+
{{domxref("MouseEvent.y")}} {{experimental_inline}}{{readonlyinline}}
+
Alias for {{domxref("MouseEvent.clientY")}}
+
+ +

Constants

+ +
+
{{domxref("MouseEvent.WEBKIT_FORCE_AT_MOUSE_DOWN")}} {{non-standard_inline}}{{readonlyinline}}
+
Minimum force necessary for a normal click
+
{{domxref("MouseEvent.WEBKIT_FORCE_AT_FORCE_MOUSE_DOWN")}} {{non-standard_inline}}{{readonlyinline}}
+
Minimum force necessary for a force click
+
+ +

方法

+ +

此介面也繼承了其父介面 {{domxref("UIEvent")}} 與 {{domxref("Event")}} 的方法

+ +
+
{{domxref("MouseEvent.getModifierState()")}}
+
Returns the current state of the specified modifier key. See the {{domxref("KeyboardEvent.getModifierState")}}() for details.
+
{{domxref("MouseEvent.initMouseEvent()")}} {{deprecated_inline}}
+
Initializes the value of a MouseEvent created. If the event has already being dispatched, this method does nothing.
+
+ +

範例

+ +

This example demonstrates simulating a click (that is programmatically generating a click event) on a checkbox using DOM methods. 

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

Click on the button to see how the sample works:

+ +

{{ EmbedLiveSample('Example', '', '', '') }}

+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSSOM View','#extensions-to-the-mouseevent-interface', 'MouseEvent')}}{{Spec2('CSSOM View')}}Redefines MouseEvent from long to double. This means that a PointerEvent whose pointerType is mouse will be a double.
{{SpecName("HTML WHATWG", "#dom-mouseevent-region", "MouseEvent.region")}}{{Spec2('HTML WHATWG')}}From {{SpecName('DOM3 Events')}}, added the region property.
{{SpecName('Pointer Lock','#extensions-to-the-mouseevent-interface','MouseEvent')}}{{Spec2('Pointer Lock')}}From {{SpecName('DOM3 Events')}}, added movementX and movementY properties.
{{SpecName('CSSOM View', '#extensions-to-the-mouseevent-interface', 'MouseEvent')}}{{Spec2('CSSOM View')}}From {{SpecName('DOM3 Events')}}, added offsetX and offsetY, pageX and pageY, x, and y properties. Redefined screen, page, client and coordinate (x and y) properties as double from long.
{{SpecName('DOM3 Events','#events-mouseevents','MouseEvent')}}{{Spec2('DOM3 Events')}}From {{SpecName('DOM2 Events')}}, added the MouseEvent() constructor, the getModifierState() method and the buttons property.
{{SpecName('DOM2 Events','#Events-MouseEvent','MouseEvent')}}{{Spec2('DOM2 Events')}}Initial definition.
+ +

瀏覽器相容性

+ +

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

+ +

參見

+ + diff --git a/files/zh-tw/web/api/mutationobserver/index.html b/files/zh-tw/web/api/mutationobserver/index.html new file mode 100644 index 0000000000..e2e1e50bfd --- /dev/null +++ b/files/zh-tw/web/api/mutationobserver/index.html @@ -0,0 +1,276 @@ +--- +title: MutationObserver +slug: Web/API/MutationObserver +translation_of: Web/API/MutationObserver +--- +

{{APIRef("DOM")}}

+ +

MutationObserver 提供開發人員一個方法,來對 DOM tree 的變動來作反應,這被設計用來替換在 DOM3 事件規範中的 Mutation Events

+ +

建構式

+ +

MutationObserver()

+ +

以下舉例為一個新的 DOM mutation observers 建構式。

+ +
new MutationObserver(
+  function callback
+);
+
+ +
參數
+ +
+
callback
+
這個函式會在 DOM 有變化時被呼叫,observer 會用兩個參數來呼叫它,第一個是 MutationRecord 物件陣列,而第二個參數則是觀察者目標本身。
+
+ +

Instance methods

+ + + + + + + + + + + + + +
void observe( {{domxref("Node")}} target, MutationObserverInit options );
void disconnect();
Array takeRecords();
+ +
+

筆記: {{domxref("Node")}} target should not be confused with NodeJS.

+
+ +

observe()

+ +

Registers the MutationObserver instance to receive notifications of DOM mutations on the specified node.

+ +
void observe(
+  {{domxref("Node")}} target,
+  MutationObserverInit options
+);
+
+ +
Parameters
+ +
+
target
+
The {{domxref("Node")}} on which to observe DOM mutations.
+
options
+
A MutationObserverInit object, specifies which DOM mutations should be reported.
+
+ +
NOTE: Adding an observer to an element is just like addEventListener, if you observe the element multiple times it does not make a difference. Meaning if you observe element twice, the observe callback does not fire twice, nor will you have to run disconnect() twice. In other words, once an element is observed, observing it again with the same observer instance will do nothing. However if the callback object is different it will of course add another observer to it.
+ +

disconnect()

+ +

Stops the MutationObserver instance from receiving notifications of DOM mutations. Until the observe() method is used again, observer's callback will not be invoked.

+ +
void disconnect();
+
+ +

takeRecords()

+ +

Empties the MutationObserver instance's record queue and returns what was in there.

+ +
Array takeRecords();
+
+ +
Return value
+ +

Returns an Array of MutationRecords.

+ +

MutationObserverInit

+ +

MutationObserverInit is an object which can specify the following properties:

+ +
NOTE: At the very least, childList, attributes, or characterData must be set to true. Otherwise, "An invalid or illegal string was specified" error is thrown.
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyDescription
childListSet to true if additions and removals of the target node's child elements (including text nodes) are to be observed.
attributesSet to true if mutations to target's attributes are to be observed.
characterDataSet to true if mutations to target's data are to be observed.
subtreeSet to true if mutations to not just target, but also target's descendants are to be observed.
attributeOldValueSet to true if attributes is set to true and target's attribute value before the mutation needs to be recorded.
characterDataOldValueSet to true if characterData is set to true and target's data before the mutation needs to be recorded.
attributeFilterSet to an array of attribute local names (without namespace) if not all attribute mutations need to be observed.
+ +

MutationRecord

+ +

MutationRecord is the object that will be passed to the observer's callback. It has the following properties:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
typeStringReturns attributes if the mutation was an attribute mutation, characterData if it was a mutation to a CharacterData node, and childList if it was a mutation to the tree of nodes.
target{{domxref("Node")}}Returns the node the mutation affected, depending on the type. For attributes, it is the element whose attribute changed. For characterData, it is the CharacterData node. For childList, it is the node whose children changed.
addedNodes{{domxref("NodeList")}}Return the nodes added. Will be an empty NodeList if no nodes were added.
removedNodes{{domxref("NodeList")}}Return the nodes removed. Will be an empty NodeList if no nodes were removed.
previousSibling{{domxref("Node")}}Return the previous sibling of the added or removed nodes, or null.
nextSibling{{domxref("Node")}}Return the next sibling of the added or removed nodes, or null.
attributeNameStringReturns the local name of the changed attribute, or null.
attributeNamespaceStringReturns the namespace of the changed attribute, or null.
oldValueStringThe return value depends on the type. For attributes, it is the value of the changed attribute before the change. For characterData, it is the data of the changed node before the change. For childList, it is null.
+ +

Example usage

+ +

The following example was taken from this blog post.

+ +
// select the target node
+var target = document.querySelector('#some-id');
+
+// create an observer instance
+var observer = new MutationObserver(function(mutations) {
+  mutations.forEach(function(mutation) {
+    console.log(mutation.type);
+  });
+});
+
+// configuration of the observer:
+var config = { attributes: true, childList: true, characterData: true };
+
+// pass in the target node, as well as the observer options
+observer.observe(target, config);
+
+// later, you can stop observing
+observer.disconnect();
+
+ +

Additional reading

+ + + +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support18 {{property_prefix("-webkit")}}
+ 26
{{CompatGeckoDesktop(14)}}11156.0 {{property_prefix("-webkit")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatUnknown}}18 {{property_prefix("-webkit")}}
+ 26
{{CompatGeckoMobile(14)}}11 (8.1)156 {{property_prefix("-webkit")}}
+ 7
+
diff --git a/files/zh-tw/web/api/namednodemap/index.html b/files/zh-tw/web/api/namednodemap/index.html new file mode 100644 index 0000000000..1aafe72d0a --- /dev/null +++ b/files/zh-tw/web/api/namednodemap/index.html @@ -0,0 +1,156 @@ +--- +title: NamedNodeMap +slug: Web/API/NamedNodeMap +translation_of: Web/API/NamedNodeMap +--- +
{{APIRef("DOM")}}
+ +

NamedNodeMap 介面表示了 {{domxref("Attr")}} 物件的集合。雖然 NamedNodeMap 與 {{domxref("NodeList")}} 都能如陣列一般透過索引訪問成員,但和 NodeList 不同的是,NamedNodeMap 中的成員並沒有順序。

+ +

NamedNodeMap 物件具有即時性(live),如果其內部成員(屬性節點物件)發生改變,NamedNodeMap 物件會自動更新至最新的狀態。

+ +
+

僅管被稱作 NamedNodeMap,但本介面並不是直接用來處理節點物件({{domxref("Node")}}),而是專門負責屬性節點物件({{domxref("Attr")}})。屬性節點是一種特殊的節點,在部分瀏覽器實作中依然存在。

+
+ +

屬性

+ +

This interface doesn't inherit any property.

+ +
+
{{domxref("NamedNodeMap.length")}} {{ReadOnlyInline}}
+
Returns the amount of objects in the map.
+
+ +

方法

+ +

This interface doesn't inherit any method.

+ +
+
{{domxref("NamedNodeMap.getNamedItem()")}}
+
Returns a {{domxref("Attr")}}, corresponding to the given name.
+
{{domxref("NamedNodeMap.setNamedItem()")}}
+
Replaces, or adds, the {{domxref("Attr")}} identified in the map by the given name.
+
{{domxref("NamedNodeMap.removeNamedItem()")}}
+
Removes the {{domxref("Attr")}} identified by the given map.
+
{{domxref("NamedNodeMap.item()")}}
+
Returns the {{domxref("Attr")}} at the given index, or null if the index is higher or equal to the number of nodes.
+
{{domxref("NamedNodeMap.getNamedItemNS()")}}
+
Returns a {{domxref("Attr")}} identified by a namespace and related local name.
+
{{domxref("NamedNodeMap.setNamedItemNS()")}}
+
Replaces, or adds, the {{domxref("Attr")}} identified in the map by the given namespace and related local name.
+
{{domxref("NamedNodeMap.removeNamedItemNS()")}}
+
Removes the {{domxref("Attr")}} identified by the given namespace and related local name.
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#interface-namednodemap', 'NamedNodeMap')}}{{Spec2('DOM WHATWG')}}Deals with {{domxref("Attr")}} instead of {{domxref("Node")}}
{{SpecName('DOM3 Core', 'core.html#ID-1780488922', 'NamedNodeMap')}}{{Spec2('DOM3 Core')}}No change from {{SpecName('DOM2 Core')}}
{{SpecName('DOM2 Core', 'core.html#ID-1780488922', 'NamedNodeMap')}}{{Spec2('DOM2 Core')}}Added getNamedItemNS(), setNamedItemNS() and removeNamedItemNS()
{{SpecName('DOM1', 'core.html#ID-1780488922', 'NamedNodeMap')}}{{Spec2('DOM1')}}Initial definition
+ +

瀏覽器相容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Deals with {{domxref("Attr")}} rather than {{domxref("Node")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop(22)}}[1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Deals with {{domxref("Attr")}} rather than {{domxref("Node")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(22)}}[1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] In Gecko 22 this interface was named mozNamedAttrMap. In Gecko 34 it was named back to NamedNodeMap.

+ +

參見

+ + diff --git a/files/zh-tw/web/api/navigator/geolocation/index.html b/files/zh-tw/web/api/navigator/geolocation/index.html new file mode 100644 index 0000000000..7c709b0b21 --- /dev/null +++ b/files/zh-tw/web/api/navigator/geolocation/index.html @@ -0,0 +1,96 @@ +--- +title: Navigator.geolocation +slug: Web/API/Navigator/geolocation +translation_of: Web/API/Navigator/geolocation +--- +
{{APIRef("Geolocation API")}}
+ +

Navigator.geolocation 回傳一個唯讀的 {{domxref("Geolocation")}} 物件,透過這個物件可以存取設備的位置訊息。同時也允許網站或應用程式根據使用者的位置提供客製化的結果。

+ +
+

備註: 因為隱私的因素,當網頁要求存取位置資訊時,用戶會被提示通知並且詢問授權與否。注意不同的瀏覽器在詢問授權時有各自不同的策略和方式。

+
+ +

語法

+ +
geo = navigator.geolocation
+
+ +

規格

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Geolocation', '#navi-geo', 'Navigator.geolocation')}}{{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}}
+
+ +

請參考

+ + diff --git a/files/zh-tw/web/api/navigator/index.html b/files/zh-tw/web/api/navigator/index.html new file mode 100644 index 0000000000..84fcfacf61 --- /dev/null +++ b/files/zh-tw/web/api/navigator/index.html @@ -0,0 +1,154 @@ +--- +title: Navigator +slug: Web/API/Navigator +tags: + - API + - HTML-DOM + - Interface + - NeedsTranslation + - Reference + - TopicStub + - Web Performance +translation_of: Web/API/Navigator +--- +

{{ APIRef("DOM4") }}

+ +

Navigator 介面標示了用戶代理(user agent)的狀態與身份。它允許腳本查詢與註冊,以進行一些活動。

+ +

Navigator 可以被檢索,只要使用唯讀的 {{domxref("window.navigator")}} 屬性。

+ +

屬性

+ +

它並不繼承任何屬性,但其實做已被定義於 {{domxref("NavigatorID")}}、{{domxref("NavigatorLanguage")}}、{{domxref("NavigatorOnLine")}}、{{domxref("NavigatorContentUtils")}}、{{domxref("NavigatorStorage")}}、{{domxref("NavigatorStorageUtils")}}、{{domxref("NavigatorConcurrentHardware")}}、{{domxref("NavigatorPlugins")}}、{{domxref("NavigatorUserMedia")}}.

+ +

標準

+ +
+
{{domxref("Navigator.activeVRDisplays")}} {{readonlyInline}}{{experimental_inline}}
+
Returns an array containing every {{domxref("VRDisplay")}} object that is currently presenting ({{domxref("VRDisplay.ispresenting")}} is true).
+
{{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("Navigator.connection")}} {{readonlyInline}}{{experimental_inline}}
+
Provides a {{domxref("NetworkInformation")}} object containing information about the network connection of a device.
+
{{domxref("Navigator.cookieEnabled")}} {{readonlyinline}}
+
Returns false if setting a cookie will be ignored and true otherwise.
+
{{domxref("Navigator.geolocation")}} {{readonlyInline}}
+
Returns a {{domxref("Geolocation")}} object allowing accessing the location of the device.
+
{{domxref("NavigatorConcurrentHardware.hardwareConcurrency")}} {{readOnlyInline}}
+
Returns the number of logical processor cores available.
+
{{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("Navigator.permissions")}} {{readonlyinline}}{{experimental_inline}}
+
Returns a {{domxref("Permissions")}} object that can be used to query and update permission status of APIs covered by the Permissions API.
+
{{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("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.
+
{{domxref("Navigator.storage")}} {{readonlyinline}}
+
Returns the singleton {{domxref('StorageManager')}} object used for managing persistance permissions and estimating available storage on a site-by-site/app-by-app basis.
+
{{domxref("NavigatorID.userAgent")}} {{readonlyInline}}
+
Returns the user agent string for the current browser.
+
+ +

Non-standard

+ +
+

Firefox OS devices adds more non-standard properties. You can consult them on the Firefox OS Navigator extensions article.

+
+ +
+
{{domxref("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.credentials")}} {{non-standard_inline}}
+
Returns the {{domxref("CredentialsContainer")}} interface which exposes methods to request credentials and notify the user agent when interesting events occur such as successful sign in or sign out. 
+
{{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("Navigator.mediaDevices")}} {{non-standard_inline}}
+
Returns a reference to a {{domxref("MediaDevices")}} object which can then be used to get information about available media devices ({{domxref("MediaDevices.enumerateDevices()")}}), find out what constrainable properties are supported for media on the user's computer and user agent ({{domxref("MediaDevices.getSupportedConstraints()")}}), and to request access to media using {{domxref("MediaDevices.getUserMedia()")}}.
+
{{domxref("Navigator.mozNotification")}} {{deprecated_inline("22")}} {{non-standard_inline}}
+ {{domxref("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("Navigator.presentation")}} {{non-standard_inline}}
+
Returns a reference to the {{domxref("Presentation")}} API.
+
{{domxref("Navigator.productSub")}} {{non-standard_inline}}
+
Returns the build number of the current browser (e.g., "20060909").
+
{{domxref("Navigator.securitypolicy")}} {{non-standard_inline}}
+
Returns an empty string. In Netscape 4.7x, returns "US & CA domestic policy" or "Export policy".
+
{{domxref("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("Navigator.storageQuota")}} {{readonlyinline}} {{experimental_inline}}
+
Returns a {{domxref('StorageQuota')}} interface which provides means to query and request storage usage and quota information.
+
{{domxref("Navigator.vendor")}} {{non-standard_inline}}
+
Returns the vendor name of the current browser (e.g., "Netscape6").
+
{{domxref("Navigator.vendorSub")}} {{non-standard_inline}}
+
Returns the vendor version number (e.g. "6.1").
+
{{domxref("Navigator.webkitPointer")}} {{non-standard_inline}}
+
Returns a PointerLock object for the Mouse Lock API.
+
+ +

方法

+ +

Doesn't inherit any method, but implements those defined in {{domxref("NavigatorID")}}, {{domxref("NavigatorContentUtils")}}, {{domxref("NavigatorUserMedia")}}, and {{domxref("NavigatorStorageUtils")}}.

+ +

Standard

+ +
+
{{domxref("Navigator.getVRDisplays()")}} {{experimental_inline}}
+
Returns a promise that resolves to an array of {{domxref("VRDisplay")}} objects representing any available VR devices connected to the computer.
+
{{domxref("Navigator.getUserMedia", "Navigator.getUserMedia()")}} {{experimental_inline}}
+
After having prompted the user for permission, returns the audio or video stream associated to a camera or microphone on the local computer.
+
{{domxref("Navigator.registerContentHandler()")}}
+
Allows web sites to register themselves as a possible handler for a given MIME type.
+
{{domxref("Navigator.registerProtocolHandler()")}}
+
Allows web sites to register themselves as a possible handler for a given protocol.
+
{{domxref("Navigator.requestMediaKeySystemAccess()")}} {{experimental_inline}}
+
Returns a {{jsxref("Promise")}} for a MediaKeySystemAccess object.
+
{{domxref("Navigator.sendBeacon()")}}{{experimental_inline}}
+
Used to asynchronously transfer a small amount of data using {{Glossary("HTTP")}} from the User Agent to a web server.
+
{{domxref("Navigator.share()")}}{{experimental_inline}}
+
Invokes the native sharing mechanism of the current platform.
+
{{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

+ +
+

Firefox OS devices adds more non-standard methods. You can consult them on the Firefox OS Navigator extensions article.

+
+ +

{{domxref("Navigator.mozIsLocallyAvailable()")}} {{non-standard_inline}}

+ +
+
Lets code check to see if the document at a given URI is available without using the network.
+
{{domxref("Navigator.mozPay()")}} {{non-standard_inline}}
+
Allows in-app payment.
+
diff --git a/files/zh-tw/web/api/navigator/registerprotocolhandler/index.html b/files/zh-tw/web/api/navigator/registerprotocolhandler/index.html new file mode 100644 index 0000000000..2ffd20da9d --- /dev/null +++ b/files/zh-tw/web/api/navigator/registerprotocolhandler/index.html @@ -0,0 +1,170 @@ +--- +title: Navigator.registerProtocolHandler() +slug: Web/API/Navigator/registerProtocolHandler +translation_of: Web/API/Navigator/registerProtocolHandler +--- +
{{APIRef("HTML DOM")}}
+ +

In progress. Allows web sites to register themselves as possible handlers for particular protocols.

+ +

For security reasons, by default, web sites may only register protocol handlers for themselves — the domain and protocol of the handler must match the current site. However, users may set a preference in Firefox to allow cross website installation, by setting the gecko.handlerService.allowRegisterFromDifferentHost pref to true in about:config.

+ +

Extensions can register protocol handlers targeting other sites: see the 'See Also' section for how to use them from XPCOM.

+ +

Syntax

+ +
window.navigator.registerProtocolHandler(protocol, url, title);
+
+ +

Parameters

+ +
+
protocol
+
The protocol the site wishes to handle, specified as a string. For example, you can register to handle SMS text message links by registering to handle the "sms" scheme.
+
url
+
The URL of the handler, as a string. This string should include "%s" as a placeholder which will be replaced with the escaped URL of the document to be handled. This URL might be a true URL, or it could be a phone number, email address, or so forth. +
The handler's URL must use one of "http" or "https" as its scheme.
+
+
title
+
A user-readable title string for the protocol handler. This will be displayed to the user in interface objects as needed.
+
+ +

Exceptions

+ +
+
SecurityError
+
The user agent blocked registration of the protocol handler. This might happen if an invalid scheme is specified, such as "http", which cannot be registered for obvious security reasons.
+
SyntaxError
+
The "%s" string is missing from the specified protocol handler URL.
+
+ +

Permitted schemes

+ +

For security reasons, registerProtocolHandler() has restrictions on which schemes may be registered. A custom scheme may be registered as long as the scheme's name begins with "web+", is at least five characters long (including the "web+" prefix), and has only lower-case ASCII letters in its name. For example, "web+burger", as shown in the {{anch("Example")}} below.

+ +

Otherwise, the scheme must be one of the schemes on the whitelist below:

+ +
+ +
+ +

Example

+ +

If your web application is located at http://www.google.co.uk, you can register a protocol handler for it to handle "web+burger" links like this:

+ +
navigator.registerProtocolHandler("web+burger",
+                                  "https://www.google.co.uk/?uri=%s",
+                                  "Burger handler");
+
+ +

This creates a handler that allows web+burger:// links to direct the user to your web application, inserting the burger information specified in the link into the URL. Recall that this script must be run from the same domain (so any page location at google.co.uk) and the second argument passed must be of http or https scheme (in this example it is https) .

+ +

The user will be notified that your code has asked to register the protocol handler, so that they can decide whether or not to permit it. See the screenshot below for an example.

+ +

+ +
+

"Register a webmail service as mailto handler" shows how to do this from XPCOM scope.

+
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'webappapis.html#dom-navigator-registerprotocolhandler', 'registerProtocolHandler()')}}{{Spec2('HTML WHATWG')}}Initial definition
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support13[1]{{CompatGeckoDesktop("1.9")}}{{CompatUnknown}}11.60{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatGeckoMobile("3.5")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Protocol whitelist includes mailto, mms, nntp, rtsp, and webcal. Custom protocols must be prefixed with web+.

+ +

See also

+ + diff --git a/files/zh-tw/web/api/navigator/registerprotocolhandler/web-based_protocol_handlers/index.html b/files/zh-tw/web/api/navigator/registerprotocolhandler/web-based_protocol_handlers/index.html new file mode 100644 index 0000000000..f32ac8ca88 --- /dev/null +++ b/files/zh-tw/web/api/navigator/registerprotocolhandler/web-based_protocol_handlers/index.html @@ -0,0 +1,28 @@ +--- +title: Firefox 3 Web-based protocol handler +slug: Web/API/Navigator/registerProtocolHandler/Web-based_protocol_handlers +translation_of: Web/API/Navigator/registerProtocolHandler/Web-based_protocol_handlers +--- +

摘要

+

window.navigator.registerProtocolHandler 讓網站可以將自己註冊為特定通訊協定的處理者。

+

語法

+
window.navigator.registerProtocolHandler(protocol, uri, title);
+ +

例子

+
navigator.registerProtocolHandler("mailto",
+                                 "https://mail.google.com/mail?view=cm&tf=0&to=%s",
+                                 "Google Mail");
+
+

這會建立一個 handler,它允許 mailto 的鏈結將使用者帶到 Google Mail,將鏈結中指定的 email 位址插入到 URL。

+

參考資料

+
    +
  1. DOM:window.navigator.registerProtocolHandler 原始網頁
  2. +
+

延伸閱讀

+
    +
  1. WHATWG's Web Applications 1.0 working draft
  2. +
diff --git a/files/zh-tw/web/api/navigatoronline/index.html b/files/zh-tw/web/api/navigatoronline/index.html new file mode 100644 index 0000000000..6e6eafaa48 --- /dev/null +++ b/files/zh-tw/web/api/navigatoronline/index.html @@ -0,0 +1,129 @@ +--- +title: NavigatorOnLine +slug: Web/API/NavigatorOnLine +translation_of: Web/API/NavigatorOnLine +--- +

{{APIRef("HTML DOM")}}

+ +

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

+ +

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

+ +

Properties

+ +

The NavigatorOnLine interface doesn't inherit any property.

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

Methods

+ +

The NavigatorOnLine interface neither implements, nor inherit any method.

+ +

Specifications

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

Browser compatibility

+ +

{{ CompatibilityTable() }}

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

See also

+ + diff --git a/files/zh-tw/web/api/navigatoronline/online_and_offline_events/index.html b/files/zh-tw/web/api/navigatoronline/online_and_offline_events/index.html new file mode 100644 index 0000000000..c8bf629d8c --- /dev/null +++ b/files/zh-tw/web/api/navigatoronline/online_and_offline_events/index.html @@ -0,0 +1,101 @@ +--- +title: Firefox 3 Online and Offline Events +slug: Web/API/NavigatorOnLine/Online_and_offline_events +translation_of: Web/API/NavigatorOnLine/Online_and_offline_events +--- +

Firefox 3 Online and Offline Events From MoztwWiki

+

Firefox 3 依據 WHATWG Web Applications 1.0 Specification 實做了 Offline/Online Events

+

概觀

+

打造可以離線跑的網路應用程式時,我們往往需要讓程式知道目前的網路狀況。實際上,網路應用程式一般的需求可細分如下:

+ +

有了 Online/offline events,要滿足這些需求變得很簡單。

+

此外,你的網路應用程式有時可能必須將某些 HTML 文件列入快取中,以便使用者離線時可以存取,如有這個需求,你可以在 HTML 文件的 <HEAD> 加入 <link> 元素:

+
<link rel="offline-resource" href="myresource">
+

Firefox 3 看到這些語法時,就會將這些資源列入一個特殊的離線資源快取(offline resource cache)中,讓使用者在離線時,依舊可以被存取這些資源。

+

API

+ +
+
+ avigator.onLine 是一個 property,其值可為 true/false (true 代表 online, false 代表 offline)。當使用者將瀏覽器切換成 Offline Mode 時(透過 主選單 -> 檔案 -> 離線模式),這個 property 就會被更新。
+
+
+
+ 除此之外,根據規格書的建議,在瀏覽器無法連接到網路時,也應該更新這個 property。規格書上是這樣寫的:
+
+
+ The navigator.onLine attribute must return false if the user agent will not contact the network when the user follows links or when a script requests a remote page (or knows that such an attempt would fail)...
+
+
+
+
+ Firefox 2 在我們將瀏覽器切換成為離線模式、或離開離線模式時,會更新這個 property,在失去網路連線、或重新連線到網路時,也會更新這個 property。
+
+
+
+ 在比較老的 Firefox 與 Internet Explorer 版本,也有支援這個 property (事實上,規格書是依據這些之前版本的實做結果來制定的),所以現在就可以馬上開始使用它。
+
+
+
+ 但「自動偵測網路狀況」是在 Firefox 2 中才實做出來。
+
+

online and offline events

+
+
+ Firefox 3 新增了兩個 events 的支援: "online" 及 "offline"。當我們切換瀏覽器的 online/offline 狀態時,就會對每個頁面的 <body> 觸發這兩個事件。除此之外,這兩個事件會從 document.body bubble up 到 document,到 window 才結束。這兩個事件都是 non-cancellable 的(因為你無法防止使用者連線到網路、或離線)。
+
+
+
+ 有好幾種你熟悉的方式可以用來註冊這兩個事件的 listeners:
+
+
+
+
    +
  • 對 window, document 或 document.body 使用 addEventListener。
  • +
  • 對 document 或 document.body 設定 .ononline 或 .onoffline properties 作為一個 JavaScript Function object. (注意: 使用 window.ononline 或 window.onoffline 無法作用,這是為了相容性。)
  • +
  • 在 html 文件的 <body> 指定 ononline="..." 或 onoffline="..." attributes。
  • +
+
+
+

例子

+

這裡有個簡單的例子

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

參考資料

+ diff --git a/files/zh-tw/web/api/network_information_api/index.html b/files/zh-tw/web/api/network_information_api/index.html new file mode 100644 index 0000000000..c7f24856a4 --- /dev/null +++ b/files/zh-tw/web/api/network_information_api/index.html @@ -0,0 +1,46 @@ +--- +title: Network Information API +slug: Web/API/Network_Information_API +translation_of: Web/API/Network_Information_API +--- +

{{ SeeCompatTable() }}

+

Network Information API 將提供系統連線的相關資訊,如使用者裝置的現有頻寬,或目前的連線狀態。根據使用者的連線情形,可進一步選擇高解析度或低解析度的內容。此完整的 API 另包含 domxref("Connection") 介面,以及 Navigator 介面的單一屬性 ─ Navigator.connection

+

偵測連線變化

+

此範例將觀察使用者連線的變化。舉例來說,當使用者從高價位連線轉用低價位連線時,就會降低頻寬需求以避免連線費用暴增,並採用類似 Apps 受到警示的方法。

+
var connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
+
+function updateConnectionStatus() {
+  alert("Connection bandwidth: " + connection.bandwidth + " MB/s");
+  if (connection.metered) {
+    alert("The connection is metered!");
+  }
+}
+
+connection.addEventListener("change", updateConnectionStatus);
+updateConnectionStatus();
+
+

規格

+ + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('Network Information', '', 'Network Information API') }}{{ Spec2('Network Information') }}Initial specification
+

瀏覽器相容性

+

{{Page('/en-US/docs/Web/API/window.navigator.connection','Browser compatibility')}}

+

See also

+ diff --git a/files/zh-tw/web/api/node/childnodes/index.html b/files/zh-tw/web/api/node/childnodes/index.html new file mode 100644 index 0000000000..a828bd781b --- /dev/null +++ b/files/zh-tw/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")}}
+
+ +

Node.childNodes 唯讀屬性會回傳一個即時更新的動態集合(live collection),其包含了指定元素的子{{domxref("Node","節點")}},而第一個子節點會被指派為索引 0。

+ +

語法

+ +
var ndList = elementNodeReference.childNodes;
+
+ +

ndList 是一個 {{domxref("NodeList")}},為一個有順序性、由目前元素之 DOM 子節點組成之集合。假如目前元素沒有子節點,則 ndList 會是空的。

+ +

範例

+ +
// parg is an object reference to a <p> element
+
+// First check that the element has child nodes
+if (parg.hasChildNodes()) {
+  var children = parg.childNodes;
+
+  for (var i = 0; i < children.length; i++) {
+    // do something with each child as children[i]
+    // NOTE: List is live, adding or removing children will change the list
+  }
+}
+ +
+
// This is one way to remove all children from a node
+// box is an object reference to an element
+
+while (box.firstChild) {
+    //The list is LIVE so it will re-index each call
+    box.removeChild(box.firstChild);
+}
+ +

備註

+ +

The items in the collection of nodes are objects and not strings. To get data from node objects, use their properties (e.g. elementNodeReference.childNodes[1].nodeName to get the name, etc.).

+ +

The document object itself has 2 children: the Doctype declaration and the root element, typically referred to as documentElement. (In (X)HTML documents this is the HTML element.)

+ +

childNodes includes all child nodes, including non-element nodes like text and comment nodes. To get a collection of only elements, use {{ domxref("ParentNode.children") }} instead.

+ +

規範

+ + + +

參見

+ + diff --git a/files/zh-tw/web/api/node/clonenode/index.html b/files/zh-tw/web/api/node/clonenode/index.html new file mode 100644 index 0000000000..2bd1998650 --- /dev/null +++ b/files/zh-tw/web/api/node/clonenode/index.html @@ -0,0 +1,160 @@ +--- +title: Node.cloneNode() +slug: Web/API/Node/cloneNode +translation_of: Web/API/Node/cloneNode +--- +
{{APIRef("DOM")}}
+ +

Node.cloneNode() 方法會回傳一個呼叫此方法之節點物件的拷貝。

+ +

語法

+ +
var dupNode = node.cloneNode(deep);
+
+ +
+
node
+
The node to be cloned.
+
dupNode
+
The new node that will be a clone of node
+
deep {{optional_inline}}
+
true if the children of the node should also be cloned, or false to clone only the specified node.
+
+ +
+

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.

+
+ +

範例

+ +
var p = document.getElementById("para1");
+var p_prime = p.cloneNode(true);
+
+ +

備註

+ +

Cloning a node copies all of its attributes and their values, including intrinsic (in–line) listeners. It does not copy event listeners added using addEventListener() or those assigned to element properties. (e.g. node.onclick = fn) Moreover, for a <canvas> element, the painted image is not copied.

+ +

The duplicate node returned by cloneNode() is not part of the document until it is added to another node that is part of the document using {{domxref("Node.appendChild()")}} or a similar method. It also has no parent until it is appended to another node.

+ +

If deep is set to false, child nodes are not cloned. Any text that the node contains is not cloned either, as it is contained in one or more child {{domxref("Text")}} nodes.

+ +

If deep evaluates to true, the whole subtree (including text that may be in child {{domxref("Text")}} nodes) is copied too. For empty nodes (e.g. {{HTMLElement("img")}} and {{HTMLElement("input")}} elements) it doesn't matter whether deep is set to true or false.

+ +
Warning: cloneNode() may lead to duplicate element IDs in a document.
+ +

If the original node has an ID and the clone is to be placed in the same document, the ID of the clone should be modified to be unique. Name attributes may need to be modified also, depending on whether duplicate names are expected.

+ +

To clone a node for appending to a different document, use {{domxref("Document.importNode()")}} instead.

+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{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")}}Initial definition
+ +

瀏覽器相容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
deep as an optional parameter +

{{CompatVersionUnknown}}[1]

+
{{CompatUnknown}}{{CompatGeckoDesktop("13.0")}}{{CompatVersionUnknown}}{{CompatUnknown}} +

{{CompatVersionUnknown}}[1]

+
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
deep as an optional parameter{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("13.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Default value for the deep parameter is false.

diff --git a/files/zh-tw/web/api/node/index.html b/files/zh-tw/web/api/node/index.html new file mode 100644 index 0000000000..fc04145fce --- /dev/null +++ b/files/zh-tw/web/api/node/index.html @@ -0,0 +1,529 @@ +--- +title: Node +slug: Web/API/Node +tags: + - API + - DOM + - DOM Reference + - Interface + - NeedsTranslation + - Node + - Reference + - TopicStub +translation_of: Web/API/Node +--- +
{{APIRef("DOM")}}
+ +

Node 是一個被多種 DOM 類型繼承的介面,它讓各種類型的 DOM 都能以同樣的方式來操作。如繼承了相同的方法,或能以相同的方式測試。

+ +

Node 繼承自 {{domxref("EventTarget")}},而繼承了 Node 的屬性及方法的介面則有:{{domxref("Document")}}、{{domxref("Element")}}、{{domxref("CharacterData")}}(被 {{domxref("Text")}}、{{domxref("Comment")}} 以及 {{domxref("CDATASection")}} 所繼承)、{{domxref("ProcessingInstruction")}}、{{domxref("DocumentFragment")}}、{{domxref("DocumentType")}}、{{domxref("Notation")}}、{{domxref("Entity")}}、{{domxref("EntityReference")}}。

+ +

These interfaces may return null in particular cases where the methods and properties are not relevant. They may throw an exception - for example when adding children to a node type for which no children can exist.

+ +

{{InheritanceDiagram}}

+ +

屬性

+ +

Inherits properties from its parents {{domxref("EventTarget")}}.[1]

+ +
+
{{domxref("Node.baseURI")}} {{readonlyInline}}
+
Returns a {{domxref("DOMString")}} representing the base URL. The concept of base URL changes from one language to another; in HTML, it corresponds to the protocol, the domain name and the directory structure, that is all until the last '/'.
+
{{domxref("Node.baseURIObject")}} {{Non-standard_inline()}} {{ Fx_minversion_inline("3") }}
+
(Not available to web content.) The read-only {{ Interface("nsIURI") }} object representing the base URI for the element.
+
{{domxref("Node.childNodes")}} {{readonlyInline}}
+
Returns a live {{domxref("NodeList")}} containing all the children of this node. {{domxref("NodeList")}} being live means that if the children of the Node change, the {{domxref("NodeList")}} object is automatically updated.
+
{{domxref("Node.firstChild")}} {{readonlyInline}}
+
Returns a {{domxref("Node")}} representing the first direct child node of the node, or null if the node has no child.
+
{{domxref("Node.lastChild")}} {{readonlyInline}}
+
Returns a {{domxref("Node")}} representing the last direct child node of the node, or null if the node has no child.
+
{{domxref("Node.nextSibling")}} {{readonlyInline}}
+
Returns a {{domxref("Node")}} representing the next node in the tree, or null if there isn't such node.
+
{{domxref("Node.nodeName")}} {{readonlyInline}}
+
Returns a {{domxref("DOMString")}} containing the name of the Node. The structure of the name will differ with the node type. E.g. An {{domxref("HTMLElement")}} will contain the name of the corresponding tag, like 'audio' for an {{domxref("HTMLAudioElement")}}, a {{domxref("Text")}} node will have the '#text' string, or a {{domxref("Document")}} node will have the '#document' string.
+
{{domxref("Node.nodePrincipal")}} {{Non-standard_inline()}}{{ Fx_minversion_inline("3") }}
+
A {{ Interface("nsIPrincipal") }} representing the node principal.
+
{{domxref("Node.nodeType")}}{{readonlyInline}}
+
Returns an unsigned short representing the type of the node. Possible values are: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameValue
ELEMENT_NODE1
ATTRIBUTE_NODE {{deprecated_inline()}}2
TEXT_NODE3
CDATA_SECTION_NODE {{deprecated_inline()}}4
ENTITY_REFERENCE_NODE {{deprecated_inline()}}5
ENTITY_NODE {{deprecated_inline()}}6
PROCESSING_INSTRUCTION_NODE7
COMMENT_NODE8
DOCUMENT_NODE9
DOCUMENT_TYPE_NODE10
DOCUMENT_FRAGMENT_NODE11
NOTATION_NODE {{deprecated_inline()}}12
+
+
{{domxref("Node.nodeValue")}}
+
Returns / Sets the value of the current node
+
{{domxref("Node.ownerDocument")}} {{readonlyInline}}
+
Returns the {{domxref("Document")}} that this node belongs to. If no document is associated with it, returns null.
+
{{domxref("Node.parentNode")}} {{readonlyInline}}
+
Returns a {{domxref("Node")}} that is the parent of this node. If there is no such node, like if this node is the top of the tree or if doesn't participate in a tree, this property returns null.
+
{{domxref("Node.parentElement")}} {{readonlyInline}}
+
Returns an {{domxref("Element")}} that is the parent of this node. If the node has no parent, or if that parent is not an {{domxref("Element")}}, this property returns null.
+
{{domxref("Node.previousSibling")}} {{readonlyInline}}
+
Returns a {{domxref("Node")}} representing the previous node in the tree, or null if there isn't such node.
+
{{domxref("Node.textContent")}}
+
Returns / Sets the textual content of an element and all its descendants.
+
+ +

Deprecated properties

+ +
+
{{domxref("Node.rootNode")}} {{readOnlyInline}} {{deprecated_inline}}
+
Returns a {{domxref("Node")}} object representing the topmost node in the tree, or the current node if it's the topmost node in the tree. This has been replaced by {{domxref("Node.getRootNode()")}}.
+
+ +

Obsolete properties

+ +
+
{{domxref("Node.localName")}} {{obsolete_inline}}{{readonlyInline}}
+
Returns a {{domxref("DOMString")}} representing the local part of the qualified name of an element. +
+

Note: In Firefox 3.5 and earlier, the property upper-cases the local name for HTML elements (but not XHTML elements). In later versions, this does not happen, so the property is in lower case for both HTML and XHTML. {{gecko_minversion_inline("1.9.2")}}

+
+
+
{{domxref("Node.namespaceURI")}} {{obsolete_inline}}{{readonlyInline}}
+
The namespace URI of this node, or null if it is no namespace. +
+

Note: In Firefox 3.5 and earlier, HTML elements are in no namespace. In later versions, HTML elements are in the https://www.w3.org/1999/xhtml/ namespace in both HTML and XML trees. {{gecko_minversion_inline("1.9.2")}}

+
+
+
{{domxref("Node.prefix")}} {{obsolete_inline}}{{readonlyInline}}
+
Is a {{domxref("DOMString")}} representing the namespace prefix of the node, or null if no prefix is specified.
+
+ +

方法

+ +

Inherits methods from its parent, {{domxref("EventTarget")}}.[1]

+ +
+
{{domxref("Node.appendChild()")}}
+
Adds the specified childNode argument as the last child to the current node.
+ If the argument referenced an existing node on the DOM tree, the node will be detached from its current position and attached at the new position.
+
{{domxref("Node.cloneNode()")}}
+
Clone a {{domxref("Node")}}, and optionally, all of its contents. By default, it clones the content of the node.
+
{{domxref("Node.compareDocumentPosition()")}}
+
Compares the position of the current node against another node in any other document.
+
{{domxref("Node.contains()")}}
+
Returns a {{jsxref("Boolean")}} value indicating whether a node is a descendant of a given node or not.
+
{{domxref("Node.getRootNode()")}}
+
Returns the context object's root which optionally includes the shadow root if it is available.
+
{{domxref("Node.hasChildNodes()")}}
+
Returns a {{jsxref("Boolean")}} indicating if the element has any child nodes, or not.
+
{{domxref("Node.insertBefore()")}}
+
Inserts a {{domxref("Node")}} before the reference node as a child of the current node.
+
{{domxref("Node.isDefaultNamespace()")}}
+
Accepts a namespace URI as an argument and returns a {{jsxref("Boolean")}} with a value of true if the namespace is the default namespace on the given node or false if not.
+
{{domxref("Node.isEqualNode()")}}
+
Returns a {{jsxref("Boolean")}} which indicates whether or not two nodes are of the same type and all their defining data points match.
+
{{domxref("Node.isSameNode()")}}
+
Returns a {{jsxref("Boolean")}} value indicating whether or not the two nodes are the same (that is, they reference the same object).
+
{{domxref("Node.lookupPrefix()")}}
+
Returns a {{domxref("DOMString")}} containing the prefix for a given namespace URI, if present, and null if not. When multiple prefixes are possible, the result is implementation-dependent.
+
{{domxref("Node.lookupNamespaceURI()")}}
+
Accepts a prefix and returns the namespace URI associated with it on the given node if found (and null if not). Supplying null for the prefix will return the default namespace.
+
{{domxref("Node.normalize()")}}
+
Clean up all the text nodes under this element (merge adjacent, remove empty).
+
{{domxref("Node.removeChild()")}}
+
Removes a child node from the current element, which must be a child of the current node.
+
{{domxref("Node.replaceChild()")}}
+
Replaces one child {{domxref("Node")}} of the current one with the second one given in parameter.
+
+ +

Obsolete methods

+ +
+
{{domxref("Node.getFeature()")}} {{obsolete_inline}}
+
x
+
{{domxref("Node.getUserData()")}} {{obsolete_inline}}
+
Allows a user to get some {{domxref("DOMUserData")}} from the node.
+
{{domxref("Node.hasAttributes()")}} {{obsolete_inline}}
+
Returns a {{jsxref("Boolean")}} indicating if the element has any attributes, or not.
+
{{domxref("Node.isSupported()")}} {{obsolete_inline}}
+
Returns a {{jsxref("Boolean")}} flag containing the result of a test whether the DOM implementation implements a specific feature and this feature is supported by the specific node.
+
{{domxref("Node.setUserData()")}} {{obsolete_inline}}
+
Allows a user to attach, or remove, {{domxref("DOMUserData")}} to the node.
+
+ +

範例

+ +

Browse all child nodes

+ +

The following function recursively cycles all child nodes of a node and executes a callback function upon them (and upon the parent node itself).

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

Syntax

+ +
DOMComb(parentNode, callbackFunction);
+ +

Description

+ +

Recursively cycle all child nodes of parentNode and parentNode itself and execute the callbackFunction upon them as this objects.

+ +

Parameters

+ +
+
parentNode
+
The parent node (Node Object).
+
callbackFunction
+
The callback function (Function).
+
+ +

Sample usage

+ +

The following example send to the console.log the text content of the body:

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

Remove all children nested within a node

+ +
Element.prototype.removeAll = function () {
+  while (this.firstChild) { this.removeChild(this.firstChild); }
+  return this;
+};
+ +

Sample usage

+ +
/* ... an alternative to document.body.innerHTML = "" ... */
+document.body.removeAll();
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#interface-node', 'Node')}}{{Spec2('DOM WHATWG')}}Removed the following properties: attributes, namespaceURI, prefix, and localName.
+ Removed the following methods: isSupported(), hasAttributes(), getFeature(), setUserData(), and getUserData().
{{SpecName('DOM3 Core', 'core.html#ID-1950641247', 'Node')}}{{Spec2('DOM3 Core')}}The methods insertBefore(), replaceChild(), removeChild(), and appendChild() returns one more kind of error (NOT_SUPPORTED_ERR) if called on a {{domxref("Document")}}.
+ The normalize() method has been modified so that {{domxref("Text")}} node can also be normalized if the proper {{domxref("DOMConfiguration")}} flag is set.
+ Added the following methods: compareDocumentPosition(), isSameNode(), lookupPrefix(), isDefaultNamespace(), lookupNamespaceURI(), isEqualNode(), getFeature(), setUserData(), and getUserData().
+ Added the following properties: baseURI and textContent.
{{SpecName('DOM2 Core', 'core.html#ID-1950641247', 'Node')}}{{Spec2('DOM2 Core')}}The ownerDocument property was slightly modified so that {{domxref("DocumentFragment")}} also returns null.
+ Added the following properties: namespaceURI, prefix, and localName.
+ Added the following methods: normalize(), isSupported() and hasAttributes().
{{SpecName('DOM1', 'level-one-core.html#ID-1950641247', 'Node')}}{{Spec2('DOM1')}}Initial definition
+ +

瀏覽器相容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}[1]{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}[1]{{CompatVersionUnknown}}[1]
getFeature(){{obsolete_inline}}{{CompatNo}}{{CompatUnknown}}{{CompatGeckoDesktop("1.0")}}
+ {{CompatNo}}{{CompatGeckoDesktop("7.0")}}
{{CompatUnknown}}{{CompatNo}}{{CompatNo}}
getUserData(), setUserData() and hasAttributes() {{deprecated_inline}}{{CompatNo}}{{CompatUnknown}}{{CompatGeckoDesktop("1.0")}}
+ {{CompatNo}}{{CompatGeckoDesktop("22.0")}}
{{CompatUnknown}}{{CompatNo}}{{CompatNo}}
isSameNode(){{CompatVersionUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop("1.0")}}
+ Removed in {{CompatGeckoDesktop("10")}}
+ Returned in {{CompatGeckoDesktop("48")}}
{{CompatUnknown}}{{CompatNo}}{{CompatNo}}
isSupported() {{obsolete_inline}}{{CompatNo}}{{CompatUnknown}}{{CompatGeckoDesktop("1.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
attributes{{CompatNo}}{{CompatUnknown}}{{CompatGeckoDesktop("1.0")}}
+ {{CompatNo}}{{CompatGeckoDesktop("22.0")}}[2]
{{CompatNo}}{{CompatNo}}{{CompatNo}}
rootNode(){{CompatUnknown}}{{CompatUnknown}}CompatGeckoDesktop(48)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
namespaceURI, localName, prefix {{obsolete_inline}}{{CompatVersionUnknown}}
+ {{CompatNo}}46.0[3]
{{CompatUnknown}}{{CompatVersionUnknown}}
+ {{CompatNo}}48.0[3]
{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
getRootNode(), and rootNode deprecated{{CompatChrome(54.0)}}{{CompatUnknown}}{{CompatGeckoDesktop(53)}}{{CompatUnknown}}{{CompatOpera(41)}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}[1]{{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}[1]{{CompatVersionUnknown}}[1]{{CompatVersionUnknown}}[1]
getFeature(){{obsolete_inline}}{{CompatNo}}{{CompatNo}}{{CompatUnknown}}{{CompatGeckoMobile("1.0")}}
+ {{CompatNo}}{{CompatGeckoDesktop("7.0")}}
{{CompatUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
getUserData(), setUserData() and hasAttributes() {{deprecated_inline}}{{CompatNo}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatNo}}
isSameNode(){{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}} +

{{CompatGeckoDesktop("1.0")}}
+ Removed in {{CompatGeckoDesktop("10")}}
+ Returned in {{CompatGeckoDesktop("48")}}

+
{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
isSupported() {{obsolete_inline}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatNo}}
attributes{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatNo}}
rootNode(){{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatGeckoMobile(48)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatNo}}
namespaceURI, localName, prefix {{obsolete_inline}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatVersionUnknown}}
+ {{CompatNo}}48.0[3]
{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatNo}}
getRootNode(), and rootNode deprecated{{CompatNo}}{{CompatChrome(54.0)}}{{CompatUnknown}}{{CompatGeckoMobile(53)}}{{CompatUnknown}}{{CompatOperaMobile(41)}}{{CompatUnknown}}{{CompatChrome(54.0)}}
+
+ +

[1] WebKit and old versions of Blink incorrectly do not make Node inherit from {{domxref("EventTarget")}}.

+ +

[2] In Gecko 22.0 {{geckoRelease("22.0")}} the attributes property was moved to {{domxref("Element")}}.

+ +

[3] The properties were moved to the {{domxref("Element")}} and {{domxref("Attr")}} APIs according to the DOM4 standard.

diff --git a/files/zh-tw/web/api/node/innertext/index.html b/files/zh-tw/web/api/node/innertext/index.html new file mode 100644 index 0000000000..4c8a4272fc --- /dev/null +++ b/files/zh-tw/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")}}
+ +

概述

+ +

Node.innerText 是一個代表節點及其後代之「已渲染」(rendered)文字內容的屬性。如同一個存取器,Node.innerText 近似於使用者利用游標選取成高亮後複製至剪貼簿之元素的內容。此功能最初由 Internet Explorer 提供,並在被所有主要瀏覽器採納之後,於 2016 年正式成為 HTML 標準。

+ +

{{domxref("Node.textContent")}} 屬性是一個相似的選擇,但兩者之間仍有非常不同的差異。

+ +

規範

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'dom.html#the-innertext-idl-attribute', 'innerText')}}{{Spec2('HTML WHATWG')}}Introduced, based on the draft of the innerText specification. See whatwg/html#465 and whatwg/compat#5 for history.
+ +

瀏覽器相容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support4{{ CompatGeckoDesktop(45) }}69.6 (probably earlier)3
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support2.3 (probably earlier){{ CompatGeckoMobile(45) }}10 (probably earlier)124.1 (probably earlier)
+
+ +

參見

+ + diff --git a/files/zh-tw/web/api/node/insertbefore/index.html b/files/zh-tw/web/api/node/insertbefore/index.html new file mode 100644 index 0000000000..393cc88d80 --- /dev/null +++ b/files/zh-tw/web/api/node/insertbefore/index.html @@ -0,0 +1,167 @@ +--- +title: Node.insertBefore() +slug: Web/API/Node/insertBefore +translation_of: Web/API/Node/insertBefore +--- +
+
{{APIRef("DOM")}}
+
+ +

Node.insertBefore() 方法將一個節點安插在參考節點之前,作為某個特定父節點之子節點。If the given child is a reference to an existing node in the document, insertBefore() moves it from its current position to the new position (there is no requirement to remove the node from its parent node before appending it to some other node).

+ +

同一個節點並不會同時出現在兩個地方。所以當節點已經有父節點,它會先被移除,然後被插入在新的位置上。The {{domxref("Node.cloneNode()")}} can be used to make a copy of the node before appending it under the new parent. Note that the copies made with cloneNode will not be automatically kept in sync.

+ +

若參考節點為 null, 那需插入的節點就會成為特定父節點的最後一個子節點。

+ +

If the given child is a {{domxref("DocumentFragment")}}, the entire contents of the {{domxref("DocumentFragment")}} are moved into the child list of the specified parent node.

+ +

Syntax

+ +
var insertedNode = parentNode.insertBefore(newNode, referenceNode);
+
+ +

If referenceNode is null, the newNode is inserted at the end of the list of child nodes.

+ +
+

referenceNode 並非可選擇的參數 -- 一定要傳入一個節點或是   null。若是傳入失敗或不正確的參數,可能會依不同的瀏覽器版本而有不同的行為

+
+ +

Returns

+ +

會回傳新加入的子節點。若該值(newNode)是{{domxref("DocumentFragment")}}, 則回傳空的 {{domxref("DocumentFragment")}}。

+ +

Example

+ +
<div id="parentElement">
+   <span id="childElement">foo bar</span>
+</div>
+
+<script>
+// Create the new node to insert
+var newNode = document.createElement("span");
+
+// Get a reference to the parent node
+var parentDiv = document.getElementById("childElement").parentNode;
+
+// Begin test case [ 1 ] : Exist a childElement --> All working correctly
+var sp2 = document.getElementById("childElement");
+parentDiv.insertBefore(newNode, sp2);
+// End test case [ 1 ]
+
+// Begin test case [ 2 ] : childElement is of Type undefined
+var sp2 = undefined; // Not exist a node of id "childElement"
+parentDiv.insertBefore(newNode, sp2); // Implicit dynamic cast to type Node
+// End test case [ 2 ]
+
+// Begin test case [ 3 ] : childElement is of Type "undefined" ( string )
+var sp2 = "undefined"; // Not exist a node of id "childElement"
+parentDiv.insertBefore(newNode, sp2); // Generate "Type Error: Invalid Argument"
+// End test case [ 3 ]
+</script>
+ + + +

Example

+ +
<div id="parentElement">
+  <span id="childElement">foo bar</span>
+</div>
+
+<script>
+// Create a new, plain <span> element
+var sp1 = document.createElement("span");
+
+// Get a reference to the element, before we want to insert the element
+var sp2 = document.getElementById("childElement");
+// Get a reference to the parent element
+var parentDiv = sp2.parentNode;
+
+// Insert the new element into the DOM before sp2
+parentDiv.insertBefore(sp1, sp2);
+</script>
+
+ +

There is no insertAfter method. It can be emulated by combining the insertBefore method with nextSibling.

+ +

In the previous example, sp1 could be inserted after sp2 using:

+ +
parentDiv.insertBefore(sp1, sp2.nextSibling);
+ +

If sp2 does not have a next sibling, then it must be the last child — sp2.nextSibling returns null, and sp1 is inserted at the end of the child node list (immediately after sp2).

+ +

Example

+ +

Insert an element before the first child element, using the firstChild property.

+ +
// Get a reference to the element in which we want to insert a new node
+var parentElement = document.getElementById('parentElement');
+// Get a reference to the first child
+var theFirstChild = parentElement.firstChild;
+
+// Create a new element
+var newElement = document.createElement("div");
+
+// Insert the new element before the first child
+parentElement.insertBefore(newElement, theFirstChild);
+
+ +

When the element does not have a first child, then firstChild is null. The element is still appended to the parent, after the last child. Since the parent element did not have a first child, it did not have a last child either. Consequently, the new element is the only element, after insertion.

+ +

Browser compatibility

+ + + +

{{Compat("api.Node.insertBefore")}}

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG','#dom-node-insertbefore','Node.insertBefore')}}{{Spec2('DOM WHATWG')}}Fixes errors in the insertion algorithm
{{SpecName('DOM4','#dom-node-insertbefore','Node.insertBefore')}}{{Spec2('DOM4')}}Describes the algorithm in more detail
{{SpecName('DOM3 Core','core.html#ID-952280727','Node.insertBefore')}}{{Spec2('DOM3 Core')}}No notable changes
{{SpecName('DOM2 Core','core.html#ID-952280727','Node.insertBefore')}}{{Spec2('DOM2 Core')}}No notable changes
{{SpecName('DOM1','level-one-core.html#method-insertBefore','Node.insertBefore')}}{{Spec2('DOM1')}}Introduced
+ +

See also

+ + diff --git a/files/zh-tw/web/api/node/nodename/index.html b/files/zh-tw/web/api/node/nodename/index.html new file mode 100644 index 0000000000..b9c95b6e2f --- /dev/null +++ b/files/zh-tw/web/api/node/nodename/index.html @@ -0,0 +1,102 @@ +--- +title: Node.nodeName +slug: Web/API/Node/nodeName +translation_of: Web/API/Node/nodeName +--- +
+
{{APIRef("DOM")}}
+
+ +

Node.nodeName 唯讀屬性會回傳目前節點名稱的字串。

+ +

不同類型節點之回傳值:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
介面nodeName 值
{{domxref("Attr")}}The value of {{domxref("Attr.name")}}
{{domxref("CDATASection")}}"#cdata-section"
{{domxref("Comment")}}"#comment"
{{domxref("Document")}}"#document"
{{domxref("DocumentFragment")}}"#document-fragment"
{{domxref("DocumentType")}}The value of {{domxref("DocumentType.name")}}
{{domxref("Element")}}The value of {{domxref("Element.tagName")}}
{{domxref("Entity")}}The entity name
{{domxref("EntityReference")}}The name of entity reference
{{domxref("Notation")}}The notation name
{{domxref("ProcessingInstruction")}}The value of {{domxref("ProcessingInstruction.target")}}
{{domxref("Text")}}"#text"
+ +

語法

+ +
var str = node.nodeName;
+
+ +

範例

+ +

Given the following markup:

+ +
<div id="d1">hello world</div>
+<input type="text" id="t"/>
+
+ +

and the following script:

+ +
var div1 = document.getElementById("d1");
+var text_field = document.getElementById("t");
+
+text_field.value = div1.nodeName;
+
+ +

In XHTML (or any other XML format), text_field's value would read "div". However, in HTML, text_field's value would read "DIV", because nodeName and tagName return in upper case on HTML elements in DOMs flagged as HTML documents. Read more details on nodeName case sensitivity in different browsers.

+ +

Note that tagName property could have been used instead, since nodeName has the same value as tagName for an element. Bear in mind, however, that nodeName will return #text for text nodes while tagName will return undefined.

+ +

規範

+ + diff --git a/files/zh-tw/web/api/node/nodetype/index.html b/files/zh-tw/web/api/node/nodetype/index.html new file mode 100644 index 0000000000..606cbd1b94 --- /dev/null +++ b/files/zh-tw/web/api/node/nodetype/index.html @@ -0,0 +1,171 @@ +--- +title: Node.nodeType +slug: Web/API/Node/nodeType +translation_of: Web/API/Node/nodeType +--- +
+
{{APIRef("DOM")}}
+
+ +

Node.nodeType 唯讀屬性表示了節點物件的類型。

+ +

描述

+ +

The nodeType property can be used to distinguish different kind of nodes, such that {{domxref("Element", "elements")}}, {{domxref("Text", "text")}} and {{domxref("Comment", "comments")}}, from each other.

+ +

語法

+ +
var type = node.nodeType;
+
+ +

Returns an integer value which specifies the type of the node; possible values are listed in {{anch("Node type constants")}}.

+ +

常數

+ +

節點類型常數

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ConstantValueDescription
{{domxref("Node.ELEMENT_NODE")}} {{readonlyinline}}1表示元素的 {{domxref("Element")}} 節點,如 {{HTMLElement("body")}}、{{HTMLElement("a")}}、{{HTMLElement("p")}}、{{HTMLElement("script")}}、{{HTMLElement("style")}}、{{HTMLElement("html")}}、{{HTMLElement("h1")}} 或 {{HTMLElement("div")}}
{{domxref("Node.TEXT_NODE")}} {{readonlyinline}}3於表示元素的 {{domxref("Element")}} 節點或表示 {{Glossary("attribute", "HTML 元素屬性")}}的 {{domxref("Attr")}} 節點中,表示了實際文字字元的 {{domxref("Text")}} 節點,它包括了換行與空格。
{{domxref("Node.PROCESSING_INSTRUCTION_NODE")}} {{readonlyinline}}7A {{domxref("ProcessingInstruction")}} of an XML document such as <?xml-stylesheet ... ?> declaration.
{{domxref("Node.COMMENT_NODE")}} {{readonlyinline}}8表示註解的 {{domxref("Comment")}} 節點。
{{domxref("Node.DOCUMENT_NODE")}} {{readonlyinline}}9表示文件的 {{domxref("Document")}} 節點。
{{domxref("Node.DOCUMENT_TYPE_NODE")}} {{readonlyinline}}10表示文件類型的 {{domxref("DocumentType")}} 節點,例如 HTML5 的 <!DOCTYPE html>
{{domxref("Node.DOCUMENT_FRAGMENT_NODE")}} {{readonlyinline}}11A {{domxref("DocumentFragment")}} node.
+ +

已過時的節點類型常數 {{deprecated_inline()}}

+ +

The following constants have been deprecated and should not be used anymore.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ConstantValueDescription
Node.ATTRIBUTE_NODE2An {{domxref("Attr", "Attribute")}} of an {{domxref("Element")}}. The element attributes are no longer implementing the {{domxref("Node")}} interface in {{SpecName("DOM4")}} specification.
Node.CDATA_SECTION_NODE4A {{domxref("CDATASection")}}. Removed in {{SpecName("DOM4")}} specification.
Node.ENTITY_REFERENCE_NODE5An XML Entity Reference node. Removed in {{SpecName("DOM4")}} specification.
Node.ENTITY_NODE6An XML <!ENTITY ...> node. Removed in {{SpecName("DOM4")}} specification.
Node.NOTATION_NODE12An XML <!NOTATION ...> node. Removed in {{SpecName("DOM4")}} specification.
+ +

範例

+ +

Different types of nodes

+ +
document.nodeType === Node.DOCUMENT_NODE; // true
+document.doctype.nodeType === Node.DOCUMENT_TYPE_NODE; // true
+
+var fragment = document.createDocumentFragment();
+fragment.nodeType === Node.DOCUMENT_FRAGMENT_NODE; // true
+
+var p = document.createElement("p");
+p.textContent = "Once upon a time...";
+
+p.nodeType === Node.ELEMENT_NODE; // true
+p.firstChild.nodeType === Node.TEXT_NODE; // true
+
+ +

Comments

+ +

This example checks if the first node inside the document element is a comment node, and if it is not, displays a message.

+ +
var node = document.documentElement.firstChild;
+if (node.nodeType != Node.COMMENT_NODE)
+  console.log("You should comment your code well!");
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-node-nodetype', 'Node.nodeType')}}{{Spec2('DOM WHATWG')}}Deprecated ATTRIBUTE_NODE, CDATA_SECTION_NODE, ENTITY_REFERENCE_NODE and NOTATION_NODE types.
{{SpecName('DOM3 Core', 'core.html#ID-1950641247', 'Node.nodeType')}}{{Spec2('DOM3 Core')}}No changes.
{{SpecName('DOM2 Core', 'core.html#ID-111237558', 'Node.nodeType')}}{{Spec2('DOM2 Core')}}No changes.
{{SpecName('DOM1', 'level-one-core.html#ID-111237558', 'Node.nodeType')}}{{Spec2('DOM1')}}Initial definition.
diff --git a/files/zh-tw/web/api/node/ownerdocument/index.html b/files/zh-tw/web/api/node/ownerdocument/index.html new file mode 100644 index 0000000000..33e8e641e8 --- /dev/null +++ b/files/zh-tw/web/api/node/ownerdocument/index.html @@ -0,0 +1,111 @@ +--- +title: Node.ownerDocument +slug: Web/API/Node/ownerDocument +translation_of: Web/API/Node/ownerDocument +--- +
{{APIRef("DOM")}}
+ +

Node.ownerDocument 唯讀屬性會回傳一個此節點所屬的的頂層 document 物件。

+ +

語法

+ +
document = element.ownerDocument
+
+ + + +

範例

+ +
// given a node "p", get the top-level HTML child
+// of the document object
+
+var d = p.ownerDocument;
+var html = d.documentElement;
+
+ +

備註

+ +

The document object returned by this property is the main object with which all the child nodes in the actual HTML document are created. If this property is used on a node that is itself a document, the result is null.

+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("DOM4", "#dom-node-ownerdocument", "Node.ownerDocument")}}{{Spec2("DOM4")}} 
{{SpecName("DOM3 Core", "core.html#node-ownerDoc", "Node.ownerDocument")}}{{Spec2("DOM3 Core")}}No change
{{SpecName("DOM2 Core", "core.html#node-ownerDoc", "Node.ownerDocument")}}{{Spec2("DOM2 Core")}}Initial definition
+ +

瀏覽器相容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}[1]6.0[2]{{CompatVersionUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}[1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Starting in Gecko 9.0 {{geckoRelease("9.0")}}, the ownerDocument of doctype nodes (that is, nodes for which {{domxref("Node.nodeType")}} is Node.DOCUMENT_TYPE_NODE or 10) is no longer null. Instead, the ownerDocument is the document on which document.implementation.createDocumentType() was called.

+ +

[2] http://msdn.microsoft.com/en-us/library/ie/ms534315(v=vs.85).aspx

diff --git a/files/zh-tw/web/api/node/removechild/index.html b/files/zh-tw/web/api/node/removechild/index.html new file mode 100644 index 0000000000..d453835c0c --- /dev/null +++ b/files/zh-tw/web/api/node/removechild/index.html @@ -0,0 +1,133 @@ +--- +title: Node.removeChild() +slug: Web/API/Node/removeChild +translation_of: Web/API/Node/removeChild +--- +
{{APIRef("DOM")}}
+ +

Node.removeChild() 方法從 DOM 移除一個子節點,並傳回移除的節點。

+ +

語法

+ +
var oldChild = node.removeChild(child);
+
+node.removeChild(child);
+
+ + + +

被刪除的子節點仍然存於記憶體之中,只是不在 DOM 了。從上述的第一種語法形式中,我們知道,透過引用 oldChild 還是可以在程式中重新使用已經被移除的子節點。

+ +

而第二種語法形式,因為沒有保留 oldChild 引用,因此假設你並沒有在其他地方保留節點引用,則它會立即無法使用且不可挽回,而且通常會在短時間內從內存管理中被自動刪除。

+ +

如果 child 並非某 element 節點的子元素,則此方法會拋出異常。而如果調用此方法時,child 雖是某 element 的子元素,但在嘗試刪除它的過程中已被其他事件處理程序刪除,也會拋出異常(例如 {{Event("blur")}})。

+ +

會丟出的錯誤

+ +

兩種不同的方式拋出異常:

+ +
    +
  1. +

    如果 child 確實是 element 的子元素且確實存在於 DOM,但已被刪除,則會丟出以下異常:

    + +

    Uncaught NotFoundError: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.

    +
  2. +
  3. +

    如果 child 不存在於頁面的 DOM,則會拋出下列的異常:
    +
    + Uncaught TypeError: Failed to execute 'removeChild' on 'Node': parameter 1 is not of type 'Node'.

    +
  4. +
+ +

例子

+ +

簡單的例子

+ +

HTML:

+ +
<div id="top">
+  <div id="nested"></div>
+</div>
+
+ +

在知道父節點的情況下,刪除特定元素:

+ +
let d = document.getElementById("top");
+let d_nested = document.getElementById("nested");
+let throwawayNode = d.removeChild(d_nested);
+
+ +

沒有指定父節點的情況下,刪除特定元素:

+ +
let node = document.getElementById("nested");
+if (node.parentNode) {
+  node.parentNode.removeChild(node);
+}
+
+ +

從一個元素中移除所有子元素:

+ +
let element = document.getElementById("top");
+while (element.firstChild) {
+  element.removeChild(element.firstChild);
+}
+
+ +

造成一個TypeError

+ +
<!--Sample HTML code-->
+<div id="top"> </div>
+
+<script type="text/javascript">
+  let top = document.getElementById("top");
+  let nested = document.getElementById("nested");
+
+  // Throws Uncaught TypeError
+  let garbage = top.removeChild(nested);
+</script>
+
+ +

造成一個NotFoundError

+ +
<!--Sample HTML code-->
+<div id="top">
+  <div id="nested"></div>
+</div>
+
+<script type="text/javascript">
+  let top = document.getElementById("top");
+  let nested = document.getElementById("nested");
+
+  // This first call correctly removes the node
+  let garbage = top.removeChild(nested);
+
+  // Throws Uncaught NotFoundError
+  garbage = top.removeChild(nested);
+</script>
+
+ +

規範

+ + + +

瀏覽器相容性

+ + + +

{{Compat("api.Node.removeChild")}}

+ +

相關連結

+ + diff --git a/files/zh-tw/web/api/node/textcontent/index.html b/files/zh-tw/web/api/node/textcontent/index.html new file mode 100644 index 0000000000..9375396158 --- /dev/null +++ b/files/zh-tw/web/api/node/textcontent/index.html @@ -0,0 +1,158 @@ +--- +title: Node.textContent +slug: Web/API/Node/textContent +translation_of: Web/API/Node/textContent +--- +
{{APIRef("DOM")}}
+ +

Node.textContent 屬性表示了節點或其後代的文字內容。

+ +

語法

+ +
var text = element.textContent;
+element.textContent = "this is some sample text";
+
+ +

描述

+ + + +

與 innerText 的差異

+ +

Internet Explorer introduced element.innerText. The intention is similar but with the following differences:

+ + + +

innerHTML 的差異

+ +

innerHTML returns the HTML as its name indicates. Quite often, in order to retrieve or write text within an element, people use innerHTML. textContent should be used instead. Because the text is not parsed as HTML, it's likely to have better performance. Moreover, this avoids an XSS attack vector.

+ +

範例

+ +
// Given the following HTML fragment:
+//   <div id="divA">This is <span>some</span> text</div>
+
+// Get the text content:
+var text = document.getElementById("divA").textContent;
+// |text| is set to "This is some text".
+
+// Set the text content:
+document.getElementById("divA").textContent = "This is some text";
+// The HTML for divA is now:
+//   <div id="divA">This is some text</div>
+
+ +

Polyfill for 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",
+     {
+       get: function() {
+         return innerText.get.call(this);
+       },
+       set: function(s) {
+         return innerText.set.call(this, s);
+       }
+     }
+   );
+  })();
+}
+
+ +

瀏覽器相容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1+299.64 (possibly earlier)3 (possibly earlier)
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG','#dom-node-textcontent','Node.textContent')}}{{Spec2('DOM WHATWG')}}No changes versus DOM4
{{SpecName('DOM4','#dom-node-textcontent','Node.textContent')}}{{Spec2('DOM4')}} 
{{SpecName('DOM3 Core','core.html#Node3-textContent','Node.textContent')}}{{Spec2('DOM3 Core')}}Introduced
+ +

參見

+ + diff --git a/files/zh-tw/web/api/nodelist/index.html b/files/zh-tw/web/api/nodelist/index.html new file mode 100644 index 0000000000..f431bd1761 --- /dev/null +++ b/files/zh-tw/web/api/nodelist/index.html @@ -0,0 +1,219 @@ +--- +title: NodeList +slug: Web/API/NodeList +translation_of: Web/API/NodeList +--- +
{{APIRef("DOM")}}
+ +

NodeList 物件是節點的集合,可藉由 {{domxref("Node.childNodes")}} 屬性以及 {{domxref("document.querySelectorAll()")}} 方法取得。

+ +
+

雖然 NodeList 不是 Array,但仍可以使用 forEach() 方法來進行迭代。一些老舊瀏覽器並未實作此方法。

+
+ +

在某些情況下,NodeList動態集合(live collection),意思是 DOM 的改變會反映於集合。例如,{{domxref("Node.childNodes")}} 便是即時更新(live)的:

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

在其他的情況下,NodeList 是一個靜態的集合(static collection),代表任何之後的 DOM 變化都不會影響集合的內容。{{domxref("document.querySelectorAll()")}} 會回傳一個靜態的 NodeList

+ +

當你要選擇如何迭代 NodeList 中的項目時,最好能於心中區分動態與靜態集合,尤其是在取得集合長度(length of the list)的時候。

+ +

屬性

+ +
+
{{domxref("NodeList.length")}}
+
The number of nodes in the NodeList.
+
+ +

方法

+ +
+
{{domxref("NodeList.item()")}}
+
Returns an item in the list by its index, or null if the index is out-of-bounds; can be used as an alternative to simply accessing nodeList[idx] (which instead returns  undefined when idx is out-of-bounds).
+
{{domxref("NodeList.entries()")}}
+
Returns an {{jsxref("Iteration_protocols","iterator")}} allowing to go through all key/value pairs contained in this object.
+
{{domxref("NodeList.forEach()")}}
+
Executes a provided function once per NodeList element.
+
{{domxref("NodeList.keys()")}}
+
Returns an {{jsxref("Iteration_protocols", "iterator")}} allowing to go through all keys of the key/value pairs contained in this object.
+
{{domxref("NodeList.values()")}}
+
Returns an {{jsxref("Iteration_protocols", "iterator")}} allowing to go through all values of the key/value pairs contained in this object.
+
+ +

範例

+ +

It's possible to loop over the items in a NodeList using:

+ +
for (var i = 0; i < myNodeList.length; ++i) {
+  var item = myNodeList[i];  // Calling myNodeList.item(i) isn't necessary in JavaScript
+}
+
+ +

Don't be tempted to use for...in or for each...in to enumerate the items in the list, since that will also enumerate the length and item properties of the NodeList and cause errors if your script assumes it only has to deal with {{domxref("element")}} objects. Also, for..in is not guaranteed to visit the properties in any particular order.

+ +

for...of loops will loop over NodeList objects correctly:

+ +
var list = document.querySelectorAll( 'input[type=checkbox]' );
+for (var item of list) {
+  item.checked = true;
+}
+ +

Recent browsers also support iterator methods, {{domxref("NodeList.forEach()", "forEach()")}}, as well as {{domxref("NodeList.entries()", "entries()")}}, {{domxref("NodeList.values()", "values()")}}, and {{domxref("NodeList.keys()", "keys()")}}

+ +

There is also an Internet Explorer compatible way to use {{jsxref("Array.forEach()", "Array.prototype.forEach")}} for iteration.

+ +
var list = document.querySelectorAll( 'input[type=checkbox]' );
+Array.prototype.forEach.call(list, function (item) {
+  item.checked = true;
+});
+ +

NodeList 原型

+ +

You can also add prototypes to 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
+ +

For information about forEach see Array.prototype.forEach()

+ +

規範

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

瀏覽器相容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
entries(), keys(), values(), forEach(){{CompatChrome(51)}}{{CompatNo}}{{CompatGeckoDesktop(50)}}{{CompatNo}}3810 (maybe prior)
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewEdgeFirefox Mobile (Gecko)Firefox OS (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
entries(), keys(), values(), forEach(){{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(50)}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}10 (maybe prior){{CompatChrome(51)}}
+
diff --git a/files/zh-tw/web/api/nondocumenttypechildnode/index.html b/files/zh-tw/web/api/nondocumenttypechildnode/index.html new file mode 100644 index 0000000000..31fb8c91e5 --- /dev/null +++ b/files/zh-tw/web/api/nondocumenttypechildnode/index.html @@ -0,0 +1,125 @@ +--- +title: NonDocumentTypeChildNode +slug: Web/API/NonDocumentTypeChildNode +translation_of: Web/API/NonDocumentTypeChildNode +--- +
{{APIRef("DOM")}}
+ +

NonDocumentTypeChildNode 介面定義了可以擁有父節點但不適用 {{domxref("DocumentType")}} 之 {{domxref("Node")}} 物件的方法。

+ +

NonDocumentTypeChildNode 是一個原始的介面,且不能以此建立物件實體。{{domxref("Element")}} 及 {{domxref("CharacterData")}} 物件皆實作了 NonDocumentTypeChildNode

+ +

屬性

+ +

There is no inherited property.

+ +
+
{{domxref("NonDocumentTypeChildNode.previousElementSibling")}} {{readonlyInline}}
+
Returns the {{domxref("Element")}} immediately prior to this node in its parent's children list, or null if there is no {{domxref("Element")}} in the list prior to this node.
+
{{domxref("NonDocumentTypeChildNode.nextElementSibling")}} {{readonlyInline}}
+
Returns the {{domxref("Element")}} immediately following this node in its parent's children list, or null if there is no {{domxref("Element")}} in the list following this node.
+
+ +

方法

+ +

There is neither inherited, nor specific method.

+ +

規範

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#interface-childnode', 'NonDocumentTypeChildNode')}}{{Spec2('DOM WHATWG')}}Splitted the ElementTraversal interface in {{domxref("ParentNode")}}, {{domxref("ChildNode")}}, and NonDocumentTypeChildNode. The previousElementSibling and nextElementSibling are now defined on the latter.
+ The {{domxref("CharacterData")}} and {{domxref("Element")}} implemented the new interfaces.
{{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")}}.
+ +

瀏覽器相容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support (on {{domxref("Element")}})1.0{{CompatGeckoDesktop("1.9.1")}}9.010.04.0
Support (on {{domxref("CharacterData")}})1.0{{CompatGeckoDesktop("25.0")}} [1]9.010.04.0
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support (on {{domxref("Element")}}){{ CompatVersionUnknown() }}{{CompatGeckoDesktop("1.9.1")}}{{ CompatVersionUnknown() }}10.0{{ CompatVersionUnknown() }}
Support (on {{domxref("CharacterData")}}){{ CompatVersionUnknown() }}{{CompatGeckoDesktop("25.0")}}{{ CompatVersionUnknown() }}10.0{{ CompatVersionUnknown() }}
+
+ +

[1] Firefox 25 also added the two properties defined here on {{domxref("DocumentType")}}, this was removed in Firefox 28 due to compatibility problems, and led to the creation of this new pure interface.

+ +

參見

+ + diff --git a/files/zh-tw/web/api/notification/index.html b/files/zh-tw/web/api/notification/index.html new file mode 100644 index 0000000000..fc1e0f9434 --- /dev/null +++ b/files/zh-tw/web/api/notification/index.html @@ -0,0 +1,355 @@ +--- +title: Notification +slug: Web/API/notification +tags: + - 待翻譯 +translation_of: Web/API/Notification +--- +

{{APIRef("Web Notifications")}}

+ +

Notifications API 的 Notification interface 是用來設置及顯示「桌面通知」給使用。

+ +

{{AvailableInWorkers}}

+ +

Constructor

+ +
+
{{domxref("Notification.Notification", "Notification()")}}
+
建立一個新的 {{domxref('Notification')}} 實例。
+
+ +

Properties

+ +

靜態屬性

+ +

以下的屬性僅適用於 Notification 實例。

+ +
+
{{domxref("Notification.permission")}} {{readonlyinline}}
+
一個表示允許通知顯示與否的權限的 string。可能的值有:「denied」(使用者不允許顯示 Notification )、「granted」(使用者允許顯示 Notification ),或者是「default」(還不知道使用者允許與否,預設行為與 denied 一致)。
+
+ +

實例屬性

+ +

以下屬應僅適用於 Notification 實例。

+ +
+
{{domxref("Notification.title")}} {{readonlyinline}}
+
在建構子的 options 參數中指定的 Notification 的標題。
+
{{domxref("Notification.dir")}} {{readonlyinline}}
+
在建構子的 options 參數中指定的 Notification 的文字顯示方向。
+
{{domxref("Notification.lang")}} {{readonlyinline}}
+
在建構子的 options 參數中指定的 Notification 的語言代號。
+
{{domxref("Notification.body")}} {{readonlyinline}}
+
在建構子的 options 參數中指定的 Notification 的內容。
+
{{domxref("Notification.tag")}} {{readonlyinline}}
+
The ID of the notification (if any) as specified in the options parameter of the constructor.
+
{{domxref("Notification.icon")}} {{readonlyinline}}
+
在建構子的 options 參數中指定的 Notification 的 icon 的網址。
+
{{domxref("Notification.data")}} {{readonlyinline}}
+
回傳結構化的 Notification 的資料。
+
{{domxref("Notification.requireInteraction")}} {{readonlyinline}}
+
一個 {{jsxref("Boolean")}} 指示在有充足大小的螢幕上的時候,Notfication 實例是否會持續顯示直到使用者點擊它或者 dismisses it。
+
{{domxref("Notification.silent")}} {{readonlyinline}}
+
表示 Notfication 是否設定要以較低調的方式呈現(比如不撥放通知音效、不震動)。這個設定與裝置本身的設定無關。
+
+ +
+
{{domxref("Notification.timestamp")}} {{readonlyinline}}
+
表示 Notification 的建立時間、或者可啟動的時間 (可能是過去、現在或未來)。
+
+ +
+
{{domxref("Notification.vibrate")}} {{readonlyinline}}
+
表示在可震動的裝置上的震動模式。
+
+ +

尚未支援的屬性

+ +

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

+ +
+
{{domxref("Notification.noscreen")}} {{readonlyinline}}
+
表示 Notification 顯示時是否要打開裝置的螢幕。
+
{{domxref("Notification.renotify")}} {{readonlyinline}}
+
表示使用者是否會在舊的 Notification 被新的 Notification 替換掉時通知。
+
{{domxref("Notification.sound")}} {{readonlyinline}}
+
表示當 Notification 顯示時要用來代替系統預設音效撥放的音訊資源。
+
{{domxref("Notification.sticky")}} {{readonlyinline}}
+
表示 Notification 是否「sticky」(比如使用者不太容易清除它)。
+
+ +

事件處理器

+ +
+
{{domxref("Notification.onclick")}}
+
一個 {{event("click")}} 事件的 handler。每次使用者點擊 Notification 都會被觸發。
+
{{domxref("Notification.onerror")}}
+
一個 {{event("error")}} 事件的 handler. 每次 Notification 發生 Error 都會被觸發。
+
+ +

停止支援的事件處理器

+ +

底下這些列在 {{anch("browser compatibility")}} 中的 event handlers 雖然還有支援,但已經從近期的 spec 中移除了。因為瀏覽器會在未來的版本逐漸停止支援,最好還是不要使用它們。

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

方法

+ +

靜態方法

+ +

這些方法只能在 Notification 實例上使用。

+ +
+
{{domxref("Notification.requestPermission()")}}
+
向使用者詢問是否開放顯示 Notification 的權限。
+
+ +

實例方法

+ +

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

+ +
+
{{domxref("Notification.close()")}}
+
透過這個方法關閉 Notification 。
+
+ +

範例

+ +

先看這段基本的 HTML:

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

用下面的程式碼我們可以送出通知: 底下的程式碼雖然略嫌冗長,但完整的示範了如何在送出通知之前,事先檢查了瀏覽器是否支援 Notification、使用者是否授權這個網域的網頁送出通知,以及在需要的時候向使用者詢問是否開放權限。

+ +
function notifyMe() {
+  // 首先讓我們確定瀏覽器支援 Notification
+  if (!("Notification" in window)) {
+    alert("這個瀏覽器不支援 Notification");
+  }
+
+  // 再檢查使用者是否已經授權執行 Notification
+  else if (Notification.permission === "granted") {
+    // 如果已經授權就可以直接新增 Notification 了!
+    var notification = new Notification("安安你好!");
+  }
+
+  // 否則,我們會需要詢問使用者是否開放權限
+  else if (Notification.permission !== 'denied') {
+    Notification.requestPermission(function (permission) {
+      // 如果使用者同意了就來新增一個 Notification 打聲招呼吧
+      if (permission === "granted") {
+        var notification = new Notification("安安~");
+      }
+    });
+  }
+
+  // 如果使用者還是不同意授權執行 Notification
+  // 最好還是進行適當的處理以避免繼續打擾使用者
+}
+ +

{{EmbedLiveSample('範例', '100%', 30)}}

+ +

在很多時候,你應該不會想要這麼冗長的程式碼。 比如說,在我們的 Emogotchi demo (see source code)  之中,我們只寫了 {{domxref("Notification.requestPermission")}} 而不用進一步檢查是否已經獲得了權限:

+ +
Notification.requestPermission();
+ +

然後我們只需要在要新增 Notfication 時執行這個 spawnNotification()  — 透過傳入指定的 body、icon、title,然後它就會產生我們所需的 options 參數並透過 {{domxref("Notification.Notification","Notification()")}} 建構子發送 Notification.

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

規格

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

瀏覽器支援度

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support5{{property_prefix("webkit")}}[1]
+ 22
4.0 {{property_prefix("moz")}}[2]
+ 22
{{CompatNo}}256[3]
icon5{{property_prefix("webkit")}}[1]
+ 22
4.0 {{property_prefix("moz")}}[2]
+ 22
{{CompatNo}}25{{CompatNo}}
Available in workers{{CompatUnknown}}{{CompatGeckoDesktop("41.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
silent{{CompatChrome(43.0)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
noscreen, renotify, sound, sticky{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}} +

{{CompatVersionUnknown}}

+
4.0{{property_prefix("moz")}}[2]
+ 22
1.0.1{{property_prefix("moz")}}[2]
+ 1.2
{{CompatNo}}{{CompatUnknown}}{{CompatNo}} +

{{CompatVersionUnknown}}

+
icon{{CompatUnknown}}{{CompatVersionUnknown}}4.0{{property_prefix("moz")}}[2]
+ 22
1.0.1{{property_prefix("moz")}}[2]
+ 1.2
{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatVersionUnknown}}
Available in workers{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("41.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
silent{{CompatNo}}{{CompatChrome(43.0)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatChrome(43.0)}}
noscreen, renotify, sound, sticky{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

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

+ +

Before Chrome 32, {{domxref("Notification.permission")}} was not supported.

+ +

Before Chrome 42, service worker additions were not supported.

+ +

[2] Prior to Firefox 22 (Firefox OS <1.2), the instantiation of a new notification must be done with the {{domxref("window.navigator.mozNotification", "navigator.mozNotification")}} object through its createNotification method.

+ +

Prior to Firefox 22 (Firefox OS <1.2), the Notification was displayed when calling the show method and supported only the click and close events.

+ +

Nick Desaulniers wrote a Notification shim to cover both newer and older implementations.

+ +

One particular Firefox OS issue is that you can pass a path to an icon to use in the notification, but if the app is packaged you cannot use a relative path like /my_icon.png. You also can't use window.location.origin + "/my_icon.png" because window.location.origin is null in packaged apps. The manifest origin field fixes this, but it is only available in Firefox OS 1.1+. A potential solution for supporting Firefox OS <1.1 is to pass an absolute URL to an externally hosted version of the icon. This is less than ideal as the notification is displayed immediately without the icon, then the icon is fetched, but it works on all versions of Firefox OS.

+ +

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

+ +

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

+ +

延伸閱讀

+ + diff --git a/files/zh-tw/web/api/notifications_api/index.html b/files/zh-tw/web/api/notifications_api/index.html new file mode 100644 index 0000000000..8cf3276371 --- /dev/null +++ b/files/zh-tw/web/api/notifications_api/index.html @@ -0,0 +1,198 @@ +--- +title: Notifications API +slug: Web/API/Notifications_API +translation_of: Web/API/Notifications_API +--- +

{{DefaultAPISidebar("Web Notifications")}}

+ +

Notifications API允許網頁控制向終端用戶顯示系統通知 — 它在網頁瀏覽器的視圖之外,因此使用者切換顯示卡或移至不同的應用程式也能顯示。此 API 設計為在相容於不同平台與現有的通知系統相容。

+ +

概念與使用方法

+ +

在受到支持的平台上,顯示系統通知通常涉及兩件事。 首先,用戶需要授予當前的來源權限才能顯示系統通知,通常在應用程式或網站初始化完成後使用{{domxref("Notification.requestPermission()")}} 方法。

+ +
btn.addEventListener('click', function() {
+  let promise = Notification.requestPermission();
+  // wait for permission
+})
+ +

這不僅是最佳實踐 — 您不應向用戶發送他們不同意的通知,並且在未來瀏覽器將明確禁止沒有響應用戶請求允許通知對話框的通知。Firefox 72 開始已遵循這項約定。使用此方法將產生一個請求對話框,如下所示:

+ +

+ +

用戶可以從此處選擇允許、屏蔽來自此來源的通知,也可以不做選擇。 一旦選定,該設置通常將在當前會話中保持不變。

+ +
+

注意: 從 Firefox 44 開始,Notifications 和 Push 的權限已合併。如果授予通知權限則推送也將被啟用。

+
+ +

下一步,使用 {{domxref("Notification.Notification","Notification()")}} 構造函數創建一個新通知。 這必須要傳遞一個標題參數(title),並且可以選擇性的傳遞選擇物件指定諸如文字方向、正文、圖標、撥放通知的聲音等等。

+ +

{{AvailableInWorkers}}

+ +

另外,Notifications API規範指定了 ServiceWorker API 的許多附加功能,以允許服務人員觸發通知。

+ +
+

注意: 要了解有關在自己的應用程序中使用通知的更多信息,請閱讀 Using the Notifications API

+
+ +

Notifications 介面

+ +
+
{{domxref("Notification")}}
+
定義一個通知物件。
+
+ +

Service worker 附加功能

+ +
+
{{domxref("ServiceWorkerRegistration")}}
+
包含 {{domxref("ServiceWorkerRegistration.showNotification()")}} 和 {{domxref("ServiceWorkerRegistration.getNotifications()")}} 用於控制通知顯示的方法。
+
{{domxref("ServiceWorkerGlobalScope")}}
+
包含 {{domxref("ServiceWorkerGlobalScope.onnotificationclick")}} 點擊通知時觸發自定義函數的處理程序。
+
{{domxref("NotificationEvent")}}
+
基於 {{domxref("ExtendableEvent")}} 的特定類型的事件對象,它表示已觸發的通知。
+
+ +

規範

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

瀏覽器相容性

+ +

{{CompatibilityTable}}

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

{{CompatChrome(42.0)}}

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

{{CompatVersionUnknown}}

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

{{CompatVersionUnknown}}

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

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

+ +

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

+ +

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

+ +

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

+ +

Firefox OS permissions

+ +

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

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

參見

+ + diff --git a/files/zh-tw/web/api/notifications_api/using_the_notifications_api/index.html b/files/zh-tw/web/api/notifications_api/using_the_notifications_api/index.html new file mode 100644 index 0000000000..1a970509c2 --- /dev/null +++ b/files/zh-tw/web/api/notifications_api/using_the_notifications_api/index.html @@ -0,0 +1,236 @@ +--- +title: 使用 Web Notifications +slug: Web/API/Notifications_API/Using_the_Notifications_API +translation_of: Web/API/Notifications_API/Using_the_Notifications_API +--- +

{{SeeCompatTable}}

+ +

摘要

+ +

Web Notifications API 可將通知傳送至頁面以外的系統層級並顯示通知。因此即使 Web Apps 處於閒置狀態,亦可傳送資訊予使用者。絕佳範例之一,就是在使用其他 Apps 時,Web Mail App 同樣可通知使用者已接收到新郵件。

+ +

要求權限

+ +

網頁內容

+ +

在 Apps 傳送通知之前,使用者必須先許可 Apps 的動作。只要 APIs 嘗試予網頁之外的東西互動,均必須先獲得使用者的授權。如此可避免濫發通知而影響使用經驗。

+ +

透過 Notification.permission 唯讀屬性,要傳送通知的 Apps 將檢查目前的授權狀態。此屬性共有 3 組參數:

+ + + +
+

注意:Chrome 與 Safari 尚未建構 permission 屬性。

+
+ +

若使用者尚未給予權限,則 Apps 必須透過 Notification.requestPermission() 函式讓使用者選擇,接著由此函式接收 1 組回呼 (Callback) 函式作為參數;而該回呼函式則提供使用者是否授權的資訊。

+ +

以下為啟動 Apps 時要求權限的常用範例:

+ +
window.addEventListener('load', function () {
+  Notification.requestPermission(function (status) {
+    // This allows to use Notification.permission with Chrome/Safari
+    if (Notification.permission !== status) {
+      Notification.permission = status;
+    }
+  });
+});
+ +
+

注意:Chrome 不允許於載入事件中呼叫 Notification.requestPermission() (參閱 issue 274284)。

+
+ +

已安裝的 Apps

+ +

在安裝 Apps 之後,若於 Apps 的 manifest 檔案中直接添加權限,即可省去再次向使用者要求權限的動作。

+ +
permissions: {
+  "desktop-notification": {
+    "description: "Allows to display notifications on the user's desktop.
+  }
+}
+ +

建立通知

+ +

透過 Notification 建構子 (Constructor) 即可建立通知。此建構子包含 1 組標題,可於通知內顯示;另有如 icon 或文字 body數個選項,可強化通知的內容。

+ +

在建立實體 (Instantiated) 之後,就會儘快顯示通知。若要追蹤通知的目前狀態,必須在 Notification 的實體階層觸發 4 個事件:

+ + + +

而透過 onshowonclickonclose,或 onerror 等事件處理器 (Event handler),即可追蹤這些事件。由於 Notification 是繼承 EventTarget 而來,因此亦可使用 addEventListener() 函式。

+ +
+

注意:Firefox 與 Safari 並未遵守 close 事件的規格。此規格雖然規定「僅限使用者能關閉通知」,但 Firefox 與 Safari 卻可於數分鐘後自動關閉通知。因此不一定是由使用者關閉通知。

+ +

此規格並明確規定「應透過 Notification.close() 函式,於應用程式層級完成自動關閉通知」。範例程式碼如下:

+ +
var n = new Notification("Hi!");
+n.onshow = function () {
+  setTimeout(n.close, 5000);
+}
+
+
+ +

簡易範例

+ +

先假設下列基本 HTML:

+ +
<button>Notify me!</button>
+ +

則能以這種方法處理通知:

+ +
window.addEventListener('load', function () {
+  // At first, let's check if we have permission for notification
+  // If not, let's ask for it
+  if (Notification && Notification.permission !== "granted") {
+    Notification.requestPermission(function (status) {
+      if (Notification.permission !== status) {
+        Notification.permission = status;
+      }
+    });
+  }
+  var button = document.getElementsByTagName('button')[0];
+  button.addEventListener('click', function () {
+    // If the user agreed to get notified
+    if (Notification && Notification.permission === "granted") {
+      var n = new Notification("Hi!");
+    }
+    // If the user hasn't told if he wants to be notified or not
+    // Note: because of Chrome, we are not sure the permission property
+    // is set, therefore it's unsafe to check for the "default" value.
+    else if (Notification && Notification.permission !== "denied") {
+      Notification.requestPermission(function (status) {
+        if (Notification.permission !== status) {
+          Notification.permission = status;
+        }
+        // If the user said okay
+        if (status === "granted") {
+          var n = new Notification("Hi!");
+        }
+        // Otherwise, we can fallback to a regular modal alert
+        else {
+          alert("Hi!");
+        }
+      });
+    }
+    // If the user refuses to get notified
+    else {
+      // We can fallback to a regular modal alert
+      alert("Hi!");
+    }
+  });
+});
+ +

現場測試結果

+ +

若無法顯示,可至本文右上角「Language」切換回英文原文觀看。

+ +

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

+ +

處理多筆通知

+ +

某些情況下 (如某個即時訊息 App 持續通知每一筆進來的訊息),使用者可能會接收大量的通知。為了避免太多非必要訊息擠爆使用者的桌面,則應該讓等待中的通知進入佇列。

+ +

將標籤添加至任何新的通知,即可達到佇列效果。若通知擁有相同的標籤且尚未顯示,則新通知就會取代先前的通知;反之,若已顯示了相同標籤的通知,就會關閉先前的通知而顯示新通知。

+ +

標籤範例

+ +

先假設下列基本 HTML:

+ +
<button>Notify me!</button>
+ +

則能以下列方式處理多筆通知:

+ +
window.addEventListener('load', function () {
+  // At first, let's check if we have permission for notification
+  // If not, let's ask for it
+  if (Notification && Notification.permission !== "granted") {
+    Notification.requestPermission(function (status) {
+      if (Notification.permission !== status) {
+        Notification.permission = status;
+      }
+    });
+  }
+  var button = document.getElementsByTagName('button')[0];
+  button.addEventListener('click', function () {
+    // If the user agreed to get notified
+    // Let's try to send ten notifications
+    if (Notification && Notification.permission === "granted") {
+      for (var i = 0; i < 10; i++) {
+        // Thanks to the tag, we should only see the "Hi! 10" notification
+        var n = new Notification("Hi! " + i, {tag: 'soManyNotification'});
+      }
+    }
+    // If the user hasn't told if he wants to be notified or not
+    // Note: because of Chrome, we are not sure the permission property
+    // is set, therefore it's unsafe to check for the "default" value.
+    else if (Notification && Notification.permission !== "denied") {
+      Notification.requestPermission(function (status) {
+        if (Notification.permission !== status) {
+          Notification.permission = status;
+        }
+        // If the user said okay
+        if (status === "granted") {
+          for (var i = 0; i < 10; i++) {
+            // Thanks to the tag, we should only see the "Hi! 10" notification
+            var n = new Notification("Hi! " + i, {tag: 'soManyNotification'});
+          }
+        }
+        // Otherwise, we can fallback to a regular modal alert
+        else {
+          alert(Hi!");
+        }
+      });
+    }
+    // If the user refuses to get notified
+    else {
+      // We can fallback to a regular modal alert
+      alert(Hi!");
+    }
+  });
+});
+ +

現場測試結果

+ +

若無法顯示,可至本文右上角「Language」切換回英文原文觀看。

+ +

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

+ +

規格

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Notifications')}}{{Spec2('Web Notifications')}}Initial specification.
+ +

瀏覽器相容性

+ +

{{page("/en-US/Web/API/Notification","Browser compatibility")}}

+ +

另可參閱

+ + diff --git a/files/zh-tw/web/api/parentnode/children/index.html b/files/zh-tw/web/api/parentnode/children/index.html new file mode 100644 index 0000000000..f9f6c76115 --- /dev/null +++ b/files/zh-tw/web/api/parentnode/children/index.html @@ -0,0 +1,152 @@ +--- +title: ParentNode.children +slug: Web/API/ParentNode/children +translation_of: Web/API/ParentNode/children +--- +

{{ APIRef("DOM") }}

+ +

Node.children 唯讀屬性會回傳一個 Node 之子{{domxref("Element","元素")}}的動態(live){{domxref("HTMLCollection")}}。

+ +

語法

+ +
var children = node.children;
+ +

children 是一個 {{ domxref("HTMLCollection") }},為一個有順序性、由 node 中的 DOM 子元素所組成的集合。假如沒有子元素,則 children 內便不包含任何元素,且 length0

+ +

範例

+ +
var foo = document.getElementById('foo');
+for (var i = 0; i < foo.children.length; i++) {
+    console.log(foo.children[i].tagName);
+}
+
+ +

Polyfill

+ +
// Overwrites native 'children' prototype.
+// Adds Document & DocumentFragment support for IE9 & Safari.
+// Returns array instead of HTMLCollection.
+;(function(constructor) {
+    if (constructor &&
+        constructor.prototype &&
+        constructor.prototype.children == null) {
+        Object.defineProperty(constructor.prototype, 'children', {
+            get: function() {
+                var i = 0, node, nodes = this.childNodes, children = [];
+                while (node = nodes[i++]) {
+                    if (node.nodeType === 1) {
+                        children.push(node);
+                    }
+                }
+                return children;
+            }
+        });
+    }
+})(window.Node || window.Element);
+
+ +

規範

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-parentnode-children', 'ParentNode.children')}}{{Spec2('DOM WHATWG')}}Initial definition.
+ +

瀏覽器相容性

+ +

{{ 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 and 8 supported it, but erroneously includes {{domxref("Comment")}} nodes.

+ +

參見

+ + diff --git a/files/zh-tw/web/api/parentnode/firstelementchild/index.html b/files/zh-tw/web/api/parentnode/firstelementchild/index.html new file mode 100644 index 0000000000..4fa9722123 --- /dev/null +++ b/files/zh-tw/web/api/parentnode/firstelementchild/index.html @@ -0,0 +1,95 @@ +--- +title: ParentNode.firstElementChild +slug: Web/API/ParentNode/firstElementChild +translation_of: Web/API/ParentNode/firstElementChild +--- +

{{ APIRef("DOM") }}

+ +

ParentNode.firstElementChild 介面會會返回 ParentNode的第一個子元素(唯讀) ,如果該節點沒有子節點則返回null

+ +
+

This property was initially defined in the {{domxref("ElementTraversal")}} pure interface. As this interface contained two distinct set of properties, one aimed at {{domxref("Node")}} that have children, one at those that are children, they have been moved into two separate pure interfaces, {{domxref("ParentNode")}} and {{domxref("ChildNode")}}. In this case, firstElementChild moved to {{domxref("ParentNode")}}. This is a fairly technical change that shouldn't affect compatibility.

+
+ +

語法

+ +
var element = node.firstElementChild;
+
+ +

範例

+ +
<ul id="foo">
+  <li>First  (1)</li>
+  <li>Second (2)</li>
+  <li>Third  (3)</li>
+</ul>
+
+<script>
+var foo = document.getElementById('foo');
+// yields: First  (1)
+console.log(foo.firstElementChild.textContent);
+</script>
+
+ +

適用於IE8, IE9 和 Safari的Polyfill

+ +
// Overwrites native 'firstElementChild' prototype.
+// Adds Document & DocumentFragment support for IE9 & Safari.
+;(function(constructor) {
+    if (constructor &&
+        constructor.prototype &&
+        constructor.prototype.firstElementChild == null) {
+        Object.defineProperty(constructor.prototype, 'firstElementChild', {
+            get: function() {
+                var node, nodes = this.childNodes, i = 0;
+                while (node = nodes[i++]) {
+                    if (node.nodeType === 1) {
+                        return node;
+                    }
+                }
+                return null;
+            }
+        });
+    }
+})(window.Node || window.Element);
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-parentnode-firstelementchild', 'ParentNode.firstElementChild')}}{{Spec2('DOM WHATWG')}}Split the ElementTraversal interface in {{domxref("ChildNode")}} and ParentNode. This method is now defined on the latter.
+ The {{domxref("Document")}} and {{domxref("DocumentFragment")}} implemented the new interfaces.
{{SpecName('Element Traversal', '#attribute-firstElementChild', 'ElementTraversal.firstElementChild')}}{{Spec2('Element Traversal')}}Added its initial definition to the ElementTraversal pure interface and use it on {{domxref("Element")}}.
+ +

瀏覽器相容性

+ + + +

{{Compat("api.ParentNode.firstElementChild")}}

+ +

參見

+ + diff --git a/files/zh-tw/web/api/parentnode/index.html b/files/zh-tw/web/api/parentnode/index.html new file mode 100644 index 0000000000..f3a37abb2f --- /dev/null +++ b/files/zh-tw/web/api/parentnode/index.html @@ -0,0 +1,166 @@ +--- +title: ParentNode +slug: Web/API/ParentNode +translation_of: Web/API/ParentNode +--- +
{{APIRef("DOM")}}
+ +

ParentNode 介面定義了可以擁有子節點之 {{domxref("Node")}} 物件的方法。

+ +

ParentNode 是一個原始的介面,且不能以此建立物件實體。{{domxref("Element")}}、{{domxref("Document")}} 及 {{domxref("DocumentFragment")}} 物件皆實作了 ParentNode

+ +

屬性

+ +
+
{{domxref("ParentNode.children")}} {{experimental_inline}} {{readonlyInline}}
+
該屬性會返回一個 {{domxref("HTMLCollection")}} 實例,包括 ParentNode的所有子元素節點,需要特別注意的是:該屬性為唯讀
+
{{domxref("ParentNode.firstElementChild")}} {{experimental_inline}} {{readonlyInline}}
+
該屬性會返回 ParentNode的第一個子元素 ,如果該節點沒有子節點則返回null
+
{{domxref("ParentNode.lastElementChild")}} {{experimental_inline}} {{readonlyInline}}
+
該屬性會返回 ParentNode的最後一個子元素 ,如果該節點沒有子節點則返回null
+
{{domxref("ParentNode.childElementCount")}} {{experimental_inline}} {{readonlyInline}}
+
該屬性會返回一個無符號長整數 ,該值表示了該節點的子節點數量。
+
+ +

方法

+ +
+
{{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.
+
{{domxref("ParentNode.querySelector()")}}
+
Returns the first {{domxref("Element")}} with the current element as root that matches the specified group of selectors.
+
{{domxref("ParentNode.querySelectorAll()")}}
+
Returns a {{domxref("NodeList")}} representing a list of elements with the current element as root that matches the specified group of selectors.
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#parentnode', 'ParentNode')}}{{Spec2('DOM WHATWG')}}Added the append() and prepend() methods.
{{SpecName('DOM4', '#parentnode', 'ParentNode')}}{{Spec2('DOM4')}}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 and the querySelector() and querySelectorAll() methods.
{{SpecName('Element Traversal', '#interface-elementTraversal', 'ElementTraversal')}}{{Spec2('Element Traversal')}}Added the initial definition of its properties to the ElementTraversal pure interface and used it on {{domxref("Element")}}.
+ +

瀏覽器相容性

+ +

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

+ +

參見

+ + diff --git a/files/zh-tw/web/api/payment_request_api/index.html b/files/zh-tw/web/api/payment_request_api/index.html new file mode 100644 index 0000000000..d9953e4cfd --- /dev/null +++ b/files/zh-tw/web/api/payment_request_api/index.html @@ -0,0 +1,117 @@ +--- +title: Payment Request API +slug: Web/API/Payment_Request_API +translation_of: Web/API/Payment_Request_API +--- +
{{DefaultAPISidebar("Payment Request API")}}{{securecontext_header}}
+ +

Payment Request API 提供商家與用戶雙方一致的用戶體驗。它並不是嶄新的支付方式、而是讓用戶選擇偏好的支付方式、並把該方式提供給商家。

+ +

Payment Request 的概念和用法

+ +

很多放棄線上購物的問題,與結帳表單的填寫有關:填寫這些東西既困難又耗時、步驟還極度繁雜。Payment Request API正是為減少、甚至擺脫要完成表單所需的填寫步驟而生。它藉由不假手 HTML 表單的情況下,記下要傳給商家的用戶資訊,來簡化結帳步驟。

+ +

針對信用卡付款,使用 Payment Request API 的好處有:

+ + + +

要請求支付的話,建立 {{domxref("PaymentRequest")}} 物件的網頁,將回應用戶發動付款的行為,像是點選「購物」按鈕。PaymentRequest 將允許網頁在用戶提供完成交易所需資訊時交換之。

+ +

你可以在 使用 Payment Request API 文章看到完整教學。

+ +
+

注意:此 API 只有在設定 {{htmlattrxref("allowpaymentrequest","iframe")}} 屬性下,才可支援跨域 {{htmlelement("iframe")}} 元素。

+
+ +

介面

+ +
+
{{domxref('PaymentAddress')}}
+
地址資訊物件,具體用途有付款與送達。
+
{{domxref('PaymentRequest')}}
+
提供 API 以便建立與管理{{Glossary("用戶代理")}}的付款介面物件。
+
{{domxref('PaymentRequestEvent')}}
+
建立 {{domxref("PaymentRequest")}} 時發送給付款處理器(payment handler)的事件。
+
{{domxref('PaymentRequestUpdateEvent')}}
+
允許網頁針對用戶行為,發動更新用戶付款資訊的請求。
+
{{domxref('PaymentMethodChangeEvent')}}
+
表示用戶更改付款工具(例如從信用卡轉為簽帳金融卡)。
+
{{domxref('PaymentResponse')}}
+
在用戶選取付款方法、並同意付款請求後,所回傳的物件。
+
{{domxref('MerchantValidationEvent')}}
+
表示商家(網站)要求使用特定支付方法的瀏覽器驗證處理器(例如:要不要放行 Apple Pay)
+
+ +

字詞(dictionary)

+ +
+
{{domxref("AddressErrors")}}
+
此字詞包含任何與 {{domxref("PaymentAddress")}} entry 錯誤相關的描述性解釋字串。
+
{{domxref("PayerErrors")}}
+
此字詞包含任何與 {{domxref("PaymentResponse")}} 的 email、電話、名字屬性(name attribute)錯誤相關之描述性解釋字串。
+
{{domxref("PaymentDetailsUpdate")}}
+
此物件描述伺服器在用戶開始互動前、實例化支付界面後,針對行為需要修改的付款資訊。
+
+ + + + +
+
{{domxref("BasicCardChangeDetails")}}
+
An object providing redacted address information that is provided as the {{domxref("PaymentMethodChangeEvent.methodDetails", "methodDetails")}} on the {{event("paymentmethodchange")}} event sent to the {{domxref("PaymentRequest")}} when the user changes payment information.
+
{{domxref("BasicCardErrors")}}
+
An object providing any error messages associated with the fields in the {{domxref("BasicCardResponse")}} object that are not valid. This is used as the value of the {{domxref("PaymentValidationErrors.paymentMethod", "paymentMethod")}} property on the {{domxref("PaymentValidationErrors")}} object sent to the {{domxref("PaymentRequest")}} when an error occurs.
+
{{domxref('BasicCardRequest')}}
+
Defines an object structure for containing payment request details such as card type.
+
{{domxref('BasicCardResponse')}}
+
Defines an object structure for payment response details such as the number/expiry date of the card used to make the payment, and the billing address.
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + +
規範狀態註解
{{SpecName('Payment')}}{{Spec2('Payment')}}初始定義。
{{SpecName('Basic Card Payment')}}{{Spec2('Basic Card Payment')}}定義 {{domxref("BasicCardRequest")}} 與 {{domxref("BasicCardResponse")}},提供處理信用卡付款所需的事務。
{{SpecName('Payment Method Identifiers')}}{{Spec2('Payment Method Identifiers')}}提供付款方法標識、驗證方法、還有 where applicable, minted and formally registered with the W3C。
+ +

瀏覽器相容性

+ +

PaymentRequest 介面

+ +

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

+ +

參見

+ + diff --git a/files/zh-tw/web/api/paymentrequest/index.html b/files/zh-tw/web/api/paymentrequest/index.html new file mode 100644 index 0000000000..033ce47312 --- /dev/null +++ b/files/zh-tw/web/api/paymentrequest/index.html @@ -0,0 +1,80 @@ +--- +title: PaymentRequest +slug: Web/API/PaymentRequest +translation_of: Web/API/PaymentRequest +--- +
{{securecontext_header}}{{APIRef("Payment Request API")}}
+ +

PaymentRequest 介面是 Payment Request API 的主要切入點,它能讓網頁或 app 接受終端用戶的付款。

+ +

建構子

+ +
+
{{domxref('PaymentRequest.PaymentRequest()','PaymentRequest()')}} {{securecontext_inline}}
+
建立新的 PaymentRequest 物件。
+
+ +

屬性

+ +
+
{{domxref('PaymentRequest.id')}} {{readonlyinline}}{{securecontext_inline}}
+
個別 PaymentRequest 的唯一標識符(unique identifier),可透過 details.id 設定之。若尚未指定,預設為 UUID。
+
{{domxref('PaymentRequest.shippingAddress')}} {{readonlyinline}} {{securecontext_inline}}
+
若透過付款設定(payment options)請求的話,回傳用戶指定的運送地址,以便計算運輸事宜。只有在呼叫的建構子 requestShipping flag 為 true 時,此屬性才能作動。另外,部份瀏覽器會出於隱私上的理由而只節錄部分地址,除非用戶表示交易手續即將完成(例如按下「付款」鈕)。
+
{{domxref('PaymentRequest.shippingOption')}} {{readonlyinline}} {{securecontext_inline}}
+
回傳的運送選項的標識符。只有在呼叫的建構子 requestShipping flag 為 true 時,此屬性才能作動。
+
{{domxref('PaymentRequest.shippingType')}} {{readonlyinline}} {{securecontext_inline}}
+
回傳用於完成交易的運送類型。可以是 shipping, delivery, pickup, 或在建構子未提供的情形下:null
+
+ +

事件處理器

+ +
+
{{domxref('PaymentRequest.onshippingaddresschange')}} {{securecontext_inline}}
+
用戶修改運送地址時觸發之。
+
{{domxref('PaymentRequest.onshippingoptionchange')}} {{securecontext_inline}}
+
用戶修改運送選項時觸發之。
+
{{domxref('PaymentRequest.onpaymentmethodchange')}} {{securecontext_inline}}
+
針對付款方法(如 Apple Pay),用戶修改支付方式時觸發之,比方說從信用卡改為簽帳卡。
+
{{domxref('PaymentRequest.onmerchantvalidation')}} {{securecontext_inline}}
+
針對付款方法(如 Apple Pay),本事件會呼叫 {{event("merchantvalidation")}} 事件,在用戶代理要求驗證付款商家或供應商是否合法時觸發之。
+
+ +

方法

+ +
+
{{domxref('PaymentRequest.canMakePayment()')}} {{securecontext_inline}}
+
在呼叫 show() 前告訴 PaymentRequest 物件能不能付款。
+
+ +
+
{{domxref('PaymentRequest.show()')}} {{securecontext_inline}}
+
讓用戶代理開始付款請求的用戶交互。
+
{{domxref('PaymentRequest.abort()')}} {{securecontext_inline}}
+
讓用戶代理結束付款請求並刪除可能顯示的任何用戶界面。
+
+ +

規範

+ + + + + + + + + + + + + + +
規範狀態註解
{{SpecName('Payment','#paymentrequest-interface','PaymentRequest')}}{{Spec2('Payment')}}初始定義。
+ +

瀏覽器相容性

+ +
+ + +

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

+
diff --git a/files/zh-tw/web/api/performance.timing/index.html b/files/zh-tw/web/api/performance.timing/index.html new file mode 100644 index 0000000000..33d0a54171 --- /dev/null +++ b/files/zh-tw/web/api/performance.timing/index.html @@ -0,0 +1,56 @@ +--- +title: Performance.timing +slug: Web/API/Performance.timing +tags: + - API + - Navigation Timing + - Performance + - Property + - Read-only + - 唯讀 + - 屬性 + - 效能 +translation_of: Web/API/Performance/timing +--- +

{{APIRef("Performance")}}

+ +

摘要

+ +

Performance.timing 是唯讀的屬性,傳回的 {{domxref("PerformanceTiming")}} 物件當中包含了效能與時間延遲相關的資訊。

+ +

語法

+ +
timingInfo = performance.timing;
+ +

規格

+ + + + + + + + + + + + + + +
規格狀態備註
{{SpecName('Navigation Timing', '#sec-window.performance-attribute', 'Performance.timing')}}{{Spec2('Navigation Timing')}}初步定義
+ +

瀏覽器支援狀況

+ +
+
+ + +

{{Compat("api.Performance.timing")}}

+
+
+ +

參照

+ + diff --git a/files/zh-tw/web/api/performance/index.html b/files/zh-tw/web/api/performance/index.html new file mode 100644 index 0000000000..017efb71e1 --- /dev/null +++ b/files/zh-tw/web/api/performance/index.html @@ -0,0 +1,140 @@ +--- +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 provides access to performance-related information for the current page. It's part of the High Resolution Time API, but is enhanced by the Performance Timeline API, the Navigation Timing API, the User Timing API, and the Resource Timing API.

+ +

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

+ +
+
{{deprecated_inline}} {{domxref("Performance.navigation")}} {{readonlyInline}}
+
A {{domxref("PerformanceNavigation")}} object that provides useful context about the operations included in the times listed in timing, including whether the page was a load or a refresh, how many redirections occurred, and so forth.
+
{{deprecated_inline}}  {{domxref("Performance.timing")}} {{readonlyInline}}
+
A {{domxref("PerformanceTiming")}} object containing latency-related performance information. Not available in workers.
+
{{domxref("Performance.memory", "performance.memory")}} {{Non-standard_inline}}
+
A non-standard extension added in Chrome, this property provides an object with basic memory usage information. You should not use this non-standard API.
+
{{domxref("Performance.timeOrigin")}} {{readonlyInline}} {{Non-standard_inline}}
+
Returns the high resolution timestamp of the start time of the performance measurement.
+
+ +
+
+

Event handlers

+
+
{{domxref("Performance.onresourcetimingbufferfull")}}
+
An {{domxref("EventTarget")}} which is a callback that will be called when the {{event("resourcetimingbufferfull")}} event is fired.
+
+ +

Methods

+ +

The Performance interface doesn't inherit any methods.

+ +
+
{{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 number of milliseconds elapsed since a reference instant.
+
{{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 3', '#dom-performance-timeorigin','timeOrigin')}}{{Spec2('Highres Time Level 3')}}Defines timeOrigin property.
{{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.
+ +

Browser compatibility

+ +
+ + +

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

+
diff --git a/files/zh-tw/web/api/pointer_lock_api/index.html b/files/zh-tw/web/api/pointer_lock_api/index.html new file mode 100644 index 0000000000..e37e5ceea5 --- /dev/null +++ b/files/zh-tw/web/api/pointer_lock_api/index.html @@ -0,0 +1,285 @@ +--- +title: Pointer Lock API +slug: Web/API/Pointer_Lock_API +translation_of: Web/API/Pointer_Lock_API +--- +

{{ SeeCompatTable() }}

+ +

Pointer lock (之前稱為 Mouse lock) 提供「隨時間經過所產生的滑鼠位移資訊 (即 deltas)」的輸入方法,而不只是滑鼠游標的絕對位置而已。此函式可存取基本的滑鼠位移、將滑鼠事件的目標鎖定至單一元素、讓滑鼠單一方向的位移距離不再受限、將游標移除到視點之外。

+ +

若 App 需要大量的滑鼠輸入以控制位移、旋轉物件、更改輸入項,那此 API 就特別有用。另對特別注重視覺效果的 App 尤其必要,如第一人稱視角、3D 視圖、模型建構等。

+ +

舉例來說,你可讓消費者不需點擊任何按鈕,只要透過滑鼠即可控制視角。而按鈕可用於其他動作。對於查看地圖、衛星圖像、第一人稱場景類 (如遊戲或虛擬實境影片) 的 App 來說,這種滑鼠輸入方式特別方便易用。

+ +

即使滑鼠游標移出瀏覽器或螢幕之外,Pointer lock 還是能讓你存取滑鼠事件。舉例來說,消費者還是可繼續移動滑鼠以旋轉或操作 3D 模型。若沒有 Pointer lock,則只要指標移出瀏覽器或螢幕之外,旋轉或操作隨即停止。遊戲玩家會特別喜歡此功能。他們現在可以隨便亂按按鈕並隨意滑動滑鼠;不再擔心滑鼠游標滑出遊戲區域而點到其他應用程式,結果退出遊戲發生慘案!

+ +

基本概念

+ +

Pointer lock 與 mouse capture 相關。在拖曳滑鼠時,Mouse capture 可持續向目標元素傳遞事件,且只要放開滑鼠按鈕隨即跟著停止。Pointer lock 與 mouse capture 不同之處在於:

+ + + +

範例

+ +

下列範例可讓你設定自己網頁上的 Pointer lock。

+ +
<button onclick="lockPointer();">Lock it!</button>
+<div id="pointer-lock-element"></div>
+<script>
+// Note: at the time of writing, only Mozilla and WebKit support Pointer Lock.
+
+// The element we'll make fullscreen and pointer locked.
+var elem;
+
+document.addEventListener("mousemove", function(e) {
+  var movementX = e.movementX       ||
+                  e.mozMovementX    ||
+                  e.webkitMovementX ||
+                  0,
+      movementY = e.movementY       ||
+                  e.mozMovementY    ||
+                  e.webkitMovementY ||
+                  0;
+
+  // Print the mouse movement delta values
+  console.log("movementX=" + movementX, "movementY=" + movementY);
+}, false);
+
+function fullscreenChange() {
+  if (document.webkitFullscreenElement === elem ||
+      document.mozFullscreenElement === elem ||
+      document.mozFullScreenElement === elem) { // Older API upper case 'S'.
+    // Element is fullscreen, now we can request pointer lock
+    elem.requestPointerLock = elem.requestPointerLock    ||
+                              elem.mozRequestPointerLock ||
+                              elem.webkitRequestPointerLock;
+    elem.requestPointerLock();
+  }
+}
+
+document.addEventListener('fullscreenchange', fullscreenChange, false);
+document.addEventListener('mozfullscreenchange', fullscreenChange, false);
+document.addEventListener('webkitfullscreenchange', fullscreenChange, false);
+
+function pointerLockChange() {
+  if (document.mozPointerLockElement === elem ||
+      document.webkitPointerLockElement === elem) {
+    console.log("Pointer Lock was successful.");
+  } else {
+    console.log("Pointer Lock was lost.");
+  }
+}
+
+document.addEventListener('pointerlockchange', pointerLockChange, false);
+document.addEventListener('mozpointerlockchange', pointerLockChange, false);
+document.addEventListener('webkitpointerlockchange', pointerLockChange, false);
+
+function pointerLockError() {
+  console.log("Error while locking pointer.");
+}
+
+document.addEventListener('pointerlockerror', pointerLockError, false);
+document.addEventListener('mozpointerlockerror', pointerLockError, false);
+document.addEventListener('webkitpointerlockerror', pointerLockError, false);
+
+function lockPointer() {
+  elem = document.getElementById("pointer-lock-element");
+  // Start by going fullscreen with the element. Current implementations
+  // require the element to be in fullscreen before requesting pointer
+  // lock--something that will likely change in the future.
+  elem.requestFullscreen = elem.requestFullscreen    ||
+                           elem.mozRequestFullscreen ||
+                           elem.mozRequestFullScreen || // Older API upper case 'S'.
+                           elem.webkitRequestFullscreen;
+  elem.requestFullscreen();
+}
+</script>
+
+ +

函式/屬性概述

+ +

Pointer lock API 與 Fullscreen API 類似,可添增 requestPointerLock 新函式 (目前尚未標準化) 而擴充 DOM 元素。可為下列:

+ +
element.webkitRequestPointerLock(); // Chrome
+element.mozRequestPointerLock(); // Firefox
+element.requestPointerLock(); // Standard
+ +

目前在建置 requestPointerLock 時,還是必須緊密結合 requestFullScreen 與 Fullscreen API。在指標鎖定某一元素之前,必須先進入全螢幕模式。如同上方的 Demo,指標鎖定屬於非同步程序,並透過 pointerlockchangepointerlockerror 事件,指出該請求是否成功。此與 Fullscreen API 的運作方式相同 (使用其 requestFullScreen 函式,另搭配 fullscreenchangefullscreenerror 事件)。

+ +

Pointer lock API 另擴充了 Document 介面,同時添增了新的屬性與函式。如果目前有鎖定的元素,則新的屬性可存取該所訂元素,並命名為 pointerLockElement (目前尚未標準化)。Document 上的新函式則為 exitPointerLock;顧名思義,此函式可退出 Pointer lock。

+ +

pointerLockElement 屬性可確定指標目前是否鎖定了任何元素 (例如進行 Boolean 檢查)。若確實有鎖定的元素,則可取得參考。以下為此二種用法的範例:

+ +
document.pointerLockElement = document.pointerLockElement    ||
+                              document.mozPointerLockElement ||
+                              document.webkitPointerLockElement;
+
+// 1) Used as a boolean check: are we pointer locked?
+if (!!document.pointerLockElement) {
+  // pointer is locked
+} else {
+  // pointer is not locked
+}
+
+// 2) Used to access the pointer locked element
+if (document.pointerLockElement === someElement) {
+  // someElement is currently pointer locked
+}
+
+ +

Document.exitPointerLock 函式則用以退出 Pointer lock。且和 requestPointerLock 一樣,Document.exitPointerLock 是使用 pointerlockchangepointerlockerror 事件,以非同步方式作業:

+ +
document.exitPointerLock = document.exitPointerLock    ||
+                           document.mozExitPointerLock ||
+                           document.webkitExitPointerLock;
+
+function pointerLockChange() {
+  document.pointerLockElement = document.pointerLockElement    ||
+                                document.mozPointerLockElement ||
+                                document.webkitPointerLockElement;
+
+  if (!!document.pointerLockElement) {
+    console.log("Still locked.");
+  } else {
+    console.log("Exited lock.");
+  }
+}
+
+document.addEventListener('pointerlockchange', pointerLockChange, false);
+document.addEventListener('mozpointerlockchange', pointerLockChange, false);
+document.addEventListener('webkitpointerlockchange', pointerLockChange, false);
+
+// Attempt to unlock
+document.exitPointerLock();
+
+ +

pointerlockchange 事件

+ +

若 Pointer lock 狀態改變,如呼叫 requestPointerLockexitPointerLock,或使用者按下 ESC 鍵等。則 pointerlockchange 事件隨即傳送至 document。此簡單事件不包含額外資料。

+ +
此事件目前在 Firefox 中的前綴為 mozpointerlockchange;在 Chrome 中的前綴為 webkitpointerlockchange
+ +

pointerlockerror 事件

+ +

當呼叫 requestPointerLockexitPointerLock 而發生錯誤時,隨即傳送 pointerlockerror 事件至 document。此簡單事件不包含額外資料。

+ +
此事件在 Firefox 中的前綴為 mozpointerlockerror;在 Chrome 中的前綴為 webkitpointerlockerror
+ +

擴充至滑鼠事件

+ +

Pointer lock API 可透過位移屬性而擴充標準的 MouseEvent 介面。

+ +
partial interface MouseEvent {
+    readonly attribute long movementX;
+    readonly attribute long movementY;
+};
+ +
位移屬性目前在 Firefox 中的前綴為 .mozMovementX.mozMovementY;在 Chrome 中的前綴為.webkitMovementX.webkitMovementY
+ +

滑鼠事件的二個新參數 (即 movementXmovementY) 將提供滑鼠位置的變化情形。此二項參數的值,等於 MouseEvent 屬性值 (即 screenXscreenY) 之間的變化;而 MouseEvent 屬性另儲存於二項連續的 mousemove 事件 (即 eNow 與 ePrevious) 之內。換句話說,Pointer lock 參數 movementX = eNow.screenX - ePrevious.screenX

+ +

鎖定狀態

+ +

在啟動 Pointer lock 之後,標準的 MouseEvent 屬性 clientXclientYscreenXscreenY 均維持不變,如同滑鼠沒有移動。movementXmovementY 屬性將持續提供滑鼠的位置變化。如果滑鼠朝單一方向持續移動,movementXmovementY 的值也就不受限。此時「滑鼠游標」的概念不存在,游標無法移出視窗之外,也不會受限於螢幕邊界。

+ +

未鎖定狀態

+ +

無論滑鼠的鎖定狀態為何,movementXmovementY 參數均保持有效;另為了方便起見,甚至在未鎖定狀態下仍可保持有效。

+ +

在解鎖滑鼠之後,系統游標可退出並重新進入瀏覽器視窗,且 movementXmovementY 此時可能設定為零。

+ +

iframe 限制

+ +

Pointer lock 一次僅能鎖定一組 iframe。在鎖定一組 iframe 之後,就無法鎖定另一組 iframe 並轉移目標至該 iframe 之上;Pointer lock 將發生錯誤。為擺脫此限制,必須先將鎖定的 iframe 解鎖,再鎖定另一組 iframe。

+ +

由於 iframes 是根據預設值運作,因此預設為「沙箱式 (sandboxed)」的 iframes 將阻擋 Pointer lock。為擺脫此限制,Chrome 應該很快就會推出 <iframe sandbox="allow-pointer-lock"> 的「屬性/值」整合形式。

+ +

規格

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Pointer Lock')}}{{Spec2('Pointer Lock')}}Initial specification.
+ +

瀏覽器相容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support +

Targeting 23{{ property_prefix("webkit") }}*

+ +

See CR/72574

+
+

{{ CompatGeckoDesktop("14.0") }}

+ +

{{bug("633602") }}

+
{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +

* 需啟動 about:flags 中的功能;或以 --enable-pointer-lock 旗標啟動 Chrome。

+ +

另可參閱

+ + diff --git a/files/zh-tw/web/api/positionoptions/enablehighaccuracy/index.html b/files/zh-tw/web/api/positionoptions/enablehighaccuracy/index.html new file mode 100644 index 0000000000..8437f37fe6 --- /dev/null +++ b/files/zh-tw/web/api/positionoptions/enablehighaccuracy/index.html @@ -0,0 +1,93 @@ +--- +title: PositionOptions.enableHighAccuracy +slug: Web/API/PositionOptions/enableHighAccuracy +translation_of: Web/API/PositionOptions/enableHighAccuracy +--- +
{{APIRef("Geolocation API")}}
+ +

PositionOptions.enableHighAccuracy 是一個 {{domxref("Boolean")}} 的值。此值指出方法是否需要回傳最佳的結果。如果值為真且該裝置是具備提供精準位置的能力,則方法會回傳最佳結果。必須注意的是最佳結果會導致較長的回應時間或者需要更多的電力耗損 (舉例來說擁有GPS晶片的手機)。相反來說,如果值為偽,機器會因為回應時間較短以及消耗較少的電力達到資源節省。預設值:偽。

+ +

語法

+ +
positionOptions.enableHighAccuracy = booleanValue
+
+ +

規格

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Geolocation', '#enablehighaccuracy', 'PositionOptions.enableHighAccuracy')}}{{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}}
+
+ +

請參考

+ + diff --git a/files/zh-tw/web/api/positionoptions/index.html b/files/zh-tw/web/api/positionoptions/index.html new file mode 100644 index 0000000000..fc27485e65 --- /dev/null +++ b/files/zh-tw/web/api/positionoptions/index.html @@ -0,0 +1,105 @@ +--- +title: PositionOptions +slug: Web/API/PositionOptions +translation_of: Web/API/PositionOptions +--- +
{{APIRef("Geolocation API")}}
+ +

PositionOptions 是一個當作 {{domxref("Geolocation.getCurrentPosition()")}} 以及 {{domxref("Geolocation.watchPosition()")}} 參數的物件,此物件含有幾種可以設定的屬性。

+ +

屬性

+ +

PositionOptions 介面沒有繼承任何屬性

+ +
+
{{domxref("PositionOptions.enableHighAccuracy")}}
+
是一個 {{domxref("Boolean")}} 的值。此值指出方法是否需要回傳最佳的結果。如果值為真且該裝置具備提供精準位置的能力,則方法會回傳最佳結果。必須注意的是最佳結果會導致較長的回應時間或者需要更多的電力耗損 (舉例來說擁有GPS晶片的手機)。相反來說,如果值為偽,機器會因為回應時間較短以及消耗較少的電力達到資源節省。預設值:偽。
+
{{domxref("PositionOptions.timeout")}}
+
這是一個正值,它代表機器能夠等待方法回傳位置的最長時間(單位是毫秒)。預設值是 Infinity,代表 getCurrentPosition() 此方法在沒有可用的位置前不會有任何回覆。
+
{{domxref("PositionOptions.maximumAge")}}
+
這是一個正值,它代表可以接受暫存位置的最長時限(單位是毫秒)。如果設定為 0,代表機器必須回傳實際的當前位置而不能使用暫存位置。如果設定為 Infinity,機器必定會回傳暫存位置而不考慮他的時限。預設值:0。
+
+ +

方法

+ +

PositionOptions 介面沒有實現也沒有繼承任何方法。

+ +

規格

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

請參考

+ + diff --git a/files/zh-tw/web/api/positionoptions/maximumage/index.html b/files/zh-tw/web/api/positionoptions/maximumage/index.html new file mode 100644 index 0000000000..2f9d1cf48e --- /dev/null +++ b/files/zh-tw/web/api/positionoptions/maximumage/index.html @@ -0,0 +1,93 @@ +--- +title: PositionOptions.maximumAge +slug: Web/API/PositionOptions/maximumAge +translation_of: Web/API/PositionOptions/maximumAge +--- +
{{APIRef("Geolocation API")}}
+ +

PositionOptions.maximumAge 是一個正值,它代表可以接受暫存位置的最長期限(單位是毫秒)。如果設定為 0,代表機器必須回傳實際的當前位置而不能使用暫存位置。如果設定為 Infinity, 機器必定會回傳暫存位置而不考慮他的期限。預設值:0。

+ +

語法

+ +
positionOptions.maximumAge = timeLength
+
+ +

規格

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Geolocation', '#maximumage', 'PositionOptions.maximumAge')}}{{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}}
+
+ +

請參考

+ + diff --git a/files/zh-tw/web/api/positionoptions/timeout/index.html b/files/zh-tw/web/api/positionoptions/timeout/index.html new file mode 100644 index 0000000000..f963a28764 --- /dev/null +++ b/files/zh-tw/web/api/positionoptions/timeout/index.html @@ -0,0 +1,93 @@ +--- +title: PositionOptions.timeout +slug: Web/API/PositionOptions/timeout +translation_of: Web/API/PositionOptions/timeout +--- +
{{APIRef("Geolocation API")}}
+ +

是一個正值,它代表機器能夠等待方法回傳位置的最長時間(單位是毫秒)。預設值是Infinity,代表 getCurrentPosition() 此方法在沒有可用的位置前不會有任何回覆。

+ +

語法

+ +
positionOptions.timeout = timeLength
+
+ +

規格

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Geolocation', '#timeout', 'PositionOptions.timeout')}}{{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}}
+
+ +

請參考

+ + diff --git a/files/zh-tw/web/api/progressevent/index.html b/files/zh-tw/web/api/progressevent/index.html new file mode 100644 index 0000000000..250df9b338 --- /dev/null +++ b/files/zh-tw/web/api/progressevent/index.html @@ -0,0 +1,161 @@ +--- +title: ProgressEvent +slug: Web/API/ProgressEvent +translation_of: Web/API/ProgressEvent +--- +

{{APIRef("DOM Events")}}

+ +

The ProgressEvent interface represents events measuring progress of an underlying process, like an HTTP request (for an XMLHttpRequest, or the loading of the underlying resource of an {{HTMLElement("img")}}, {{HTMLElement("audio")}}, {{HTMLElement("video")}}, {{HTMLElement("style")}} or {{HTMLElement("link")}}).

+ +

建構式

+ +
+
{{domxref("ProgressEvent.ProgressEvent", "ProgressEvent()")}}
+
Creates a ProgressEvent event with the given parameters.
+
+ +

屬性

+ +

Also inherits properties from its parent {{domxref("Event")}}.

+ +
+
{{domxref("ProgressEvent.lengthComputable")}} {{readonlyInline}}
+
Is a {{domxref("Boolean")}} flag indicating if the total work to be done, and the amount of work already done, by the underlying process is calculable. In other words, it tells if the progress is measurable or not.
+
{{domxref("ProgressEvent.loaded")}} {{readonlyInline}}
+
Is an unsigned long long representing the amount of work already performed by the underlying process. The ratio of work done can be calculated with the property and ProgressEvent.total. When downloading a resource using HTTP, this only represent the part of the content itself, not headers and other overhead.
+
{{domxref("ProgressEvent.total")}} {{readonlyInline}}
+
Is an unsigned long long representing the total amount of work that the underlying process is in the progress of performing. When downloading a resource using HTTP, this only represent the content itself, not headers and other overhead.
+
+ +

方法

+ +
+
+ +

Also inherits methods from its parent {{domxref("Event")}}.

+ +
+
{{domxref("ProgressEvent.initProgressEvent()")}} {{deprecated_inline}}{{non-Standard_inline}}
+
Initializes a ProgressEvent created using the deprecated {{domxref("Document.createEvent()", "Document.createEvent(\"ProgressEvent\")")}} method.
+
+ +

範例

+ +

The following example adds a ProgressEvent to a new {{domxref("XMLHTTPRequest")}} and uses it to display the status of the request.

+ +
  var progressBar = document.getElementById("p"),
+      client = new XMLHttpRequest()
+  client.open("GET", "magical-unicorns")
+  client.onprogress = function(pe) {
+    if(pe.lengthComputable) {
+      progressBar.max = pe.total
+      progressBar.value = pe.loaded
+    }
+  }
+  client.onloadend = function(pe) {
+    progressBar.value = pe.loaded
+  }
+  client.send()
+ +

規格

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Progress Events', '#interface-progressevent', 'ProgressEvent')}}{{Spec2('Progress Events')}}Initial definition.
+ +

瀏覽器相容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1.0{{CompatGeckoDesktop("1.9.1")}}10.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}
initProgressEvent() {{non-standard_inline}}{{deprecated_inline}}{{CompatNo}}[1]{{CompatNo}}[2]10.0{{CompatNo}}[4]{{CompatNo}}[3]
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.9.1")}}10.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
initProgressEvent() {{non-standard_inline}}{{deprecated_inline}}{{CompatNo}}[3]{{CompatNo}}{{CompatNo}}[2]10.0{{CompatNo}}[4]{{CompatNo}}[3]{{CompatNo}}
+
+ +

[1] This feature was implemented in Chrome 1.0, but removed in Chrome 17.0.

+ +

[2] This feature was implemented in Gecko 1.9.1 {{geckoRelease("1.9.1")}}, but removed in Gecko 22 {{geckoRelease("22")}}.

+ +

[3] This feature was removed at some point.

+ +

[4] This feature was removed in Opera 15.0.

+ +

參見

+ + diff --git a/files/zh-tw/web/api/proximity_events/index.html b/files/zh-tw/web/api/proximity_events/index.html new file mode 100644 index 0000000000..f6464480f8 --- /dev/null +++ b/files/zh-tw/web/api/proximity_events/index.html @@ -0,0 +1,118 @@ +--- +title: Proximity +slug: Web/API/Proximity_Events +translation_of: Web/API/Proximity_Events +--- +

{{ SeeCompatTable }}

+

摘要

+

近距 (Proximity) 事件可迅速感測出使用者靠近裝置,並迅速做出反應。舉例來說,當使用者接通來電並將裝置靠近耳朵時,智慧型手機隨即關閉螢幕。

+
+

注意:顯然裝置必須具備近距感測器 (Proximity sensor),此 API 才能發揮作用。而目前幾乎只有行動裝置搭載接近感測器。若裝置並未搭載感測器,則雖同樣可支援,但永遠不會觸發此類事件。

+
+

近距事件

+

只要近距感測器測得「裝置」與「物體」之間的距離改變時,就會通知瀏覽器這項變化。而只要瀏覽器獲得通知,隨即啟動 DeviceProximityEvent 以因應任何變化;或啟動 UserProximityEvent 以因應簡單的變化。

+

透過 addEventListener 函式 (使用 {{event("deviceproximity")}} 或 {{event("userproximity")}} 事件名稱);或將事件處理器 (Event handler) 附掛至 window.ondeviceproximitywindow.onuserproximity 屬性,均可於 window 物件層級就擷取到此事件。

+

在擷取事件之後,事件物件將可存取不同的資訊:

+ +

範例

+
window.addEventListener('userproximity', function(event) {
+  if (event.near) {
+    // let's power off the screen
+    navigator.mozPower.screenEnabled = false;
+  } else {
+    // Otherwise, let's power on the screen
+    navigator.mozPower.screenEnabled = true;
+  }
+});
+

規格

+ + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('Proximity Events', '', 'Proximity Events') }}{{ Spec2('Proximity Events') }}Initial specification
+

瀏覽器相容性

+

{{ CompatibilityTable() }}

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
{{domxref("DeviceProximityEvent")}}{{CompatNo()}}{{CompatVersionUnknown()}}{{CompatNo()}}{{CompatNo()}}{{CompatNo()}}
{{domxref("UserProximityEvent")}}{{CompatNo()}}{{CompatVersionUnknown()}}{{CompatNo()}}{{CompatNo()}}{{CompatNo()}}
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
{{domxref("DeviceProximityEvent")}}{{CompatNo()}}{{CompatNo()}}{{ CompatGeckoMobile("15.0") }}{{CompatNo()}}{{CompatNo()}}{{CompatNo()}}
{{domxref("UserProximityEvent")}}{{CompatNo()}}{{CompatNo()}}{{CompatVersionUnknown()}}{{CompatNo()}}{{CompatNo()}}{{CompatNo()}}
+
+

另可參閱

+ diff --git a/files/zh-tw/web/api/range/index.html b/files/zh-tw/web/api/range/index.html new file mode 100644 index 0000000000..35307c4628 --- /dev/null +++ b/files/zh-tw/web/api/range/index.html @@ -0,0 +1,249 @@ +--- +title: Range +slug: Web/API/Range +translation_of: Web/API/Range +--- +

{{ APIRef("DOM") }}

+ +

Range 介面代表一個文件的片段(fragment),可以包含節點及部分的文字節點。

+ +

A range can be created using the {{ domxref("Document.createRange", "createRange()") }} method of the {{ domxref("Document") }} object. Range objects can also be retrieved by using the {{ domxref("Selection/getRangeAt", "getRangeAt()") }} method of the {{ domxref("Selection") }} object or the {{domxref("Document/caretRangeFromPoint", "caretRangeFromPoint()")}} method of the {{domxref("Document")}} object.

+ +

There also is the {{domxref("Range.Range()", "Range()")}} constructor available.

+ +

屬性

+ +

There are no inherited properties.

+ +
+
{{domxref("Range.collapsed")}} {{readonlyInline}}
+
Returns a {{domxref("Boolean")}} indicating whether the range's start and end points are at the same position.
+
{{domxref("Range.commonAncestorContainer")}} {{readonlyInline}}
+
Returns the deepest {{ domxref("Node") }} that contains the startContainer and endContainer nodes.
+
{{domxref("Range.endContainer")}} {{readonlyInline}}
+
Returns the {{ domxref("Node") }} within which the Range ends.
+
{{domxref("Range.endOffset")}} {{readonlyInline}}
+
Returns a number representing where in the endContainer the Range ends.
+
{{domxref("Range.startContainer")}} {{readonlyInline}}
+
Returns the {{ domxref("Node") }} within which the Range starts.
+
{{domxref("Range.startOffset")}} {{readonlyInline}}
+
Returns a number representing where in the startContainer the Range starts.
+
+ +

建構式

+ +
+
{{ domxref("Range.Range()", "Range()") }} {{experimental_inline}}
+
Returns a Range object with the global {{domxref("Document")}} as its start and end.
+
+ +

方法

+ +

There are no inherited methods.

+ +
+
{{ domxref("Range.setStart()")}}
+
Sets the start position of a Range.
+
{{ domxref("Range.setEnd()")}}
+
Sets the end position of a Range.
+
{{ domxref("Range.setStartBefore()")}}
+
Sets the start position of a Range relative to another {{ domxref("Node") }}.
+
{{ domxref("Range.setStartAfter()")}}
+
Sets the start position of a Range relative to another {{ domxref("Node") }}.
+
{{ domxref("Range.setEndBefore()")}}
+
Sets the end position of a Range relative to another {{ domxref("Node") }}.
+
{{ domxref("Range.setEndAfter()")}}
+
Sets the end position of a Range relative to another {{ domxref("Node") }}.
+
{{ domxref("Range.selectNode()")}}
+
Sets the Range to contain the {{ domxref("Node") }} and its contents.
+
{{ domxref("Range.selectNodeContents()")}}
+
Sets the Range to contain the contents of a {{ domxref("Node") }}.
+
{{ domxref("Range.collapse()")}}
+
Collapses the Range to one of its boundary points.
+
{{ domxref("Range.cloneContents()")}}
+
Returns a {{ domxref("DocumentFragment") }} copying the nodes of a Range.
+
{{ domxref("Range.deleteContents()")}}
+
Removes the contents of a Range from the {{ domxref("Document") }}.
+
{{ domxref("Range.extractContents()")}}
+
Moves contents of a Range from the document tree into a {{ domxref("DocumentFragment") }}.
+
{{ domxref("Range.insertNode()")}}
+
Insert a {{ domxref("Node") }} at the start of a Range.
+
{{ domxref("Range.surroundContents()")}}
+
Moves content of a Range into a new {{ domxref("Node") }}.
+
{{ domxref("Range.compareBoundaryPoints()")}}
+
Compares the boundary points of the Range with another Range.
+
{{ domxref("Range.cloneRange()")}}
+
Returns a Range object with boundary points identical to the cloned Range.
+
{{ domxref("Range.detach()")}}
+
Releases the Range from use to improve performance.
+
{{ domxref("Range.toString()")}}
+
Returns the text of the Range.
+
{{ domxref("Range.compareNode()")}} {{ Obsolete_inline }}{{non-standard_inline}}
+
Returns a constant representing whether the {{domxref("Node")}} is before, after, inside, or surrounding the range.
+
{{ domxref("Range.comparePoint()")}} {{experimental_inline}}
+
Returns -1, 0, or 1 indicating whether the point occurs before, inside, or after the Range.
+
{{ domxref("Range.createContextualFragment()")}}{{experimental_inline}}
+
Returns a {{ domxref("DocumentFragment") }} created from a given string of code.
+
{{ domxref("Range.getBoundingClientRect()") }} {{experimental_inline}}
+
Returns a {{ domxref("DOMRect") }} object which bounds the entire contents of the Range; this would be the union of all the rectangles returned by {{ domxref("range.getClientRects()") }}.
+
{{ domxref("Range.getClientRects()") }} {{experimental_inline}}
+
Returns a list of {{ domxref("DOMRect") }} objects that aggregates the results of {{ domxref("Element.getClientRects()") }} for all the elements in the Range.
+
{{ domxref("Range.intersectsNode()")}} {{experimental_inline}}
+
Returns a boolean indicating whether the given node intersects the Range.
+
{{ domxref("Range.isPointInRange()")}} {{experimental_inline}}
+
Returns a boolean indicating whether the given point is in the Range.
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#interface-range', 'Range')}}{{Spec2('DOM WHATWG')}}Do not use RangeException anymore, use DOMException instead.
+ Made the second parameter of collapse() optional.
+ Added the methods isPointInRange(), comparePoint(), and intersectsNode().
+ Added the constructor Range().
{{SpecName('DOM Parsing', '#extensions-to-the-range-interface', 'Extensions to Range')}}{{Spec2('DOM Parsing')}}Added the method createContextualFragment().
{{SpecName('CSSOM View', '#extensions-to-the-range-interface', 'Extensions to Range')}}{{Spec2('CSSOM View')}}Added the methods getClientRects() and getBoundingClientRect().
{{SpecName('DOM2 Traversal_Range', 'ranges.html#Level-2-Range-Interface', 'Range')}}{{Spec2('DOM2 Traversal_Range')}}Initial specification.
+ +

瀏覽器相容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.0")}} [1]9.09.0{{CompatVersionUnknown}}
Range() constructor {{experimental_inline}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop("24.0")}}{{CompatNo}}15.0{{CompatVersionUnknown}}
compareNode() {{obsolete_inline}}{{non-standard_inline()}}{{CompatNo}}{{CompatUnknown}}{{CompatGeckoDesktop("1.0")}}
+ Removed in {{CompatGeckoDesktop("1.9")}}
{{CompatNo}}{{CompatNo}}{{CompatNo}}
isPointInRange(), and comparePoint(){{experimental_inline}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatNo}}15.0{{CompatUnknown}}
intersectsNode() {{experimental_inline}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop("17.0")}} [2]{{CompatNo}}15.0{{CompatUnknown}}
getClientRects() and getBoundingClientRect(){{experimental_inline}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("2.0")}}915.05
createContextualFragment(){{experimental_inline}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}1115.0{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}} [1]9.09.0{{CompatVersionUnknown}}
+
+ +

[1] Starting with Gecko 13.0 {{ geckoRelease("13.0") }} the Range object throws a {{ domxref("DOMException") }} as defined in DOM 4, instead of a RangeException defined in prior specifications.

+ +

[2] Gecko supported it up to Gecko 1.9, then removed it until Gecko 17 where it was reimplemented, matching the spec.

+ +

參見

+ + diff --git a/files/zh-tw/web/api/response/index.html b/files/zh-tw/web/api/response/index.html new file mode 100644 index 0000000000..8899c22fa5 --- /dev/null +++ b/files/zh-tw/web/api/response/index.html @@ -0,0 +1,120 @@ +--- +title: Response +slug: Web/API/Response +translation_of: Web/API/Response +--- +
{{APIRef("Fetch API")}}
+ +

Fetch API  的 Response 介面代表了一個請求會返回的回應。

+ +

你可以用 {{domxref("Response.Response()")}} 建構子創建一個新的 Response物件。但實務上碰到 Response 物件的時機,比較常出現在進行了一個 API 操作後,得到返回的 Response 物件。舉例而言,使用 service worker {{domxref("Fetchevent.respondWith")}} 或是使用單純的{{domxref("GlobalFetch.fetch()")}}。

+ +

建構子

+ +
+
{{domxref("Response.Response","Response()")}}
+
創建一個新的  Response 物件。
+
+ +

屬性

+ +
+
{{domxref("Response.headers")}} {{readonlyinline}}
+
包含與此 response 相關的 {{domxref("Headers")}} 物件。
+
{{domxref("Response.ok")}} {{readonlyinline}}
+
無論此 response 是不是成功 ( 狀態碼 200-299 ) 都會包含一個 boolean 狀態。
+
{{domxref("Response.redirected")}} {{ReadOnlyInline}}
+
指出此 response 是不是個重新導向的結果,如果是的話,代表此 URL 具有一個以上的入口。
+
{{domxref("Response.status")}} {{readonlyinline}}
+
包含此  response  的狀態碼(例如:成功時為 200 )。
+
{{domxref("Response.statusText")}} {{readonlyinline}}
+
包含狀態碼所對應的狀態文字 (例如: OK 對應 200)。
+
{{domxref("Response.type")}} {{readonlyinline}}
+
包含此 response 的類型 (例如: basic, cors)。
+
{{domxref("Response.url")}} {{readonlyinline}}
+
包含此 response 的 URL。
+
{{domxref("Response.useFinalURL")}}
+
包含一個 boolean 狀態,指出此 URL 是否為此 response 的最後一步。
+
+ +

Response 實做了{{domxref("Body")}}, 所以它另有以下可用的屬性:

+ +
+
{{domxref("Body.body")}} {{readonlyInline}}
+
A simple getter used to expose a {{domxref("ReadableStream")}} of the body contents.
+
{{domxref("Body.bodyUsed")}} {{readonlyInline}}
+
Stores a {{domxref("Boolean")}} that declares whether the body has been used in a response yet.
+
+ +

方法

+ +
+
{{domxref("Response.clone()")}}
+
建立一份  Response 的複製物件。
+
{{domxref("Response.error()")}}
+
Returns a new Response object associated with a network error.
+
{{domxref("Response.redirect()")}}
+
Creates a new response with a different URL.
+
+ +

Response implements {{domxref("Body")}}, so it also has the following methods available to it:

+ +
+
{{domxref("Body.arrayBuffer()")}}
+
Takes a {{domxref("Response")}} stream and reads it to completion. It returns a promise that resolves with an {{domxref("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).
+
+ +

範例

+ +

基本 fetch 範例 (run example live) 中,我們使用 fetch() 呼叫來得到圖片,並使用 {{htmlelement("img")}} tag 顯示。 這裡的fetch() 呼叫返回了一個 promise,它使用與資源 fetch 操作有關的 Response 進行解析。你可能有發現,由於我們要求的是一張圖片,所以需要用 {{domxref("Body.blob")}} ({{domxref("Response")}} 時做了 body) 讓 response 有正確的 MIME 類型。

+ +
const image = document.querySelector('.my-image');
+fetch('flowers.jpg').then(function(response) {
+  return response.blob();
+}).then(function(blob) {
+  const objectURL = URL.createObjectURL(blob);
+  image.src = objectURL;
+});
+ +

除此之外,你也能用 {{domxref("Response.Response()")}} 建構子去建立自己的客製化 Response 物件:

+ +
const response = new Response();
+ +

規範

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Fetch','#response-class','Response')}}{{Spec2('Fetch')}}Initial definition
+ +

瀏覽器相容性

+ + + +

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

+ +

參考

+ + diff --git a/files/zh-tw/web/api/screen/index.html b/files/zh-tw/web/api/screen/index.html new file mode 100644 index 0000000000..089203003f --- /dev/null +++ b/files/zh-tw/web/api/screen/index.html @@ -0,0 +1,89 @@ +--- +title: Screen +slug: Web/API/Screen +translation_of: Web/API/Screen +--- +
{{APIRef("CSSOM View")}}
+ +

Screen 介面表示了一個用戶端螢幕,通常是指呈現目前頁面的視窗。

+ +

一般來說為顯示目前網頁的視窗,可以透過 window.screen 取得物件實體。

+ +

屬性

+ +
+
{{domxref("Screen.availTop")}}
+
Specifies the y-coordinate of the first pixel that is not allocated to permanent or semipermanent user interface features.
+
{{domxref("Screen.availLeft")}}
+
Returns the first available pixel available from the left side of the screen.
+
{{domxref("Screen.availHeight")}}
+
Specifies the height of the screen, in pixels, minus permanent or semipermanent user interface features displayed by the operating system, such as the Taskbar on Windows.
+
{{domxref("Screen.availWidth")}}
+
Returns the amount of horizontal space in pixels available to the window.
+
{{domxref("Screen.colorDepth")}}
+
Returns the color depth of the screen.
+
{{domxref("Screen.height")}}
+
Returns the height of the screen in pixels.
+
{{domxref("Screen.left")}}
+
Returns the distance in pixels from the left side of the main screen to the left side of the current screen.
+
{{domxref("Screen.orientation")}}
+
Returns the current orientation of the screen.
+
{{domxref("Screen.pixelDepth")}}
+
Gets the bit depth of the screen.
+
{{domxref("Screen.top")}}
+
Returns the distance in pixels from the top side of the current screen.
+
{{domxref("Screen.width")}}
+
Returns the width of the screen.
+
{{domxref("Screen.mozEnabled")}} {{gecko_minversion_inline("12.0")}}
+
Boolean. Setting to false will turn off the device's screen.
+
{{domxref("Screen.mozBrightness")}} {{gecko_minversion_inline("12.0")}}
+
Controls the brightness of a device's screen. A double between 0 and 1.0 is expected.
+
+ +

事件處理器

+ +
+
{{domxref("Screen.onorientationchange")}}
+
A handler for the {{event("orientationchange")}} events.
+
+ +

方法

+ +
+
{{domxref("Screen.lockOrientation")}}
+
Lock the screen orientation (only works in fullscreen or for installed apps)
+
{{domxref("Screen.unlockOrientation")}}
+
Unlock the screen orientation (only works in fullscreen or for installed apps)
+
+ +

Methods inherit from {{domxref("EventTarget")}}

+ +

{{page("/en-US/docs/Web/API/EventTarget","Methods")}}

+ +

範例

+ +
if (screen.pixelDepth < 8) {
+  // use low-color version of page
+} else {
+  // use regular, colorful page
+}
+
+ +

規範

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSSOM View', '#the-screen-interface', 'Screen') }}{{ Spec2('CSSOM View') }} 
diff --git a/files/zh-tw/web/api/screen/orientation/index.html b/files/zh-tw/web/api/screen/orientation/index.html new file mode 100644 index 0000000000..eafa89a703 --- /dev/null +++ b/files/zh-tw/web/api/screen/orientation/index.html @@ -0,0 +1,114 @@ +--- +title: Screen.orientation +slug: Web/API/Screen/orientation +translation_of: Web/API/Screen/orientation +--- +
{{APIRef("CSSOM View")}}{{SeeCompatTable}}
+ +

Screen.orientation 屬性可以取得螢幕目前的方向。

+ +

語法

+ +
var orientation = window.screen.orientation.type;
+
+ +

回傳值

+ +

回傳值為一個代表螢幕方向的字串,可能是 portrait-primaryportrait-secondarylandscape-primarylandscape-secondary(請參考 {{domxref("window.screen.lockOrientation","lockOrientation")}} 以瞭解更多資訊)。

+ +

範例

+ +
var orientation = screen.orientation || screen.mozOrientation || screen.msOrientation;
+
+if (orientation.type === "landscape-primary") {
+  console.log("That looks good.");
+} else if (orientation.type === "landscape-secondary") {
+  console.log("Mmmh... the screen is upside down!");
+} else if (orientation.type === "portrait-secondary" || orientation.type === "portrait-primary") {
+  console.log("Mmmh... you should rotate your device to landscape");
+}
+
+ +

規範

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Screen Orientation', '', 'Screen Orientation')}}{{Spec2('Screen Orientation')}}Initial definition
+ +

瀏覽器相容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support38{{CompatVersionUnknown}} {{property_prefix("moz")}}[1]11{{property_prefix("ms")}}[2]25{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}39{{CompatVersionUnknown}} {{property_prefix("moz")}}[1]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] This API is only implemented as a prefixed method (mozOrientation) in B2G and Firefox for Android.

+ +

[2] This API is implemented using a prefix (msOrientation) in Internet Explorer for Windows 8.1 and Windows RT 8.1. It is not supported on Windows 7.

+ +

參見

+ + diff --git a/files/zh-tw/web/api/server-sent_events/index.html b/files/zh-tw/web/api/server-sent_events/index.html new file mode 100644 index 0000000000..bb72cb3f93 --- /dev/null +++ b/files/zh-tw/web/api/server-sent_events/index.html @@ -0,0 +1,115 @@ +--- +title: Server-sent events +slug: Web/API/Server-sent_events +translation_of: Web/API/Server-sent_events +--- +

網頁一般來說是由客戶端向伺服器請求資料. 藉由 server-sent 事件, 伺服器在任何時候都可以向客戶端推送資料. 即將推送進來的訊息可以自客戶端上做 Events + data 處理.

+ + + + + + + + +
+

文件

+ +
+
使用 server-sent events
+
有關如何在伺服器端和客戶端使用 server-sent 事件的教學文章.
+
參考 EventSource
+
關於客戶端的 EventSource API.
+
+ +

瀏覽全部...

+
+

工具

+ + + + + + +
+ +

參見

+ + + +

規範

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Server-sent events')}}{{Spec2('Server-sent events')}}Initial definition.
+ +

瀏覽器相容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
EventSource support9{{CompatGeckoDesktop("6.0")}}{{CompatUnknown}}115
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
EventSource support{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
diff --git a/files/zh-tw/web/api/server-sent_events/using_server-sent_events/index.html b/files/zh-tw/web/api/server-sent_events/using_server-sent_events/index.html new file mode 100644 index 0000000000..92433f4f18 --- /dev/null +++ b/files/zh-tw/web/api/server-sent_events/using_server-sent_events/index.html @@ -0,0 +1,202 @@ +--- +title: 使用 server-sent 事件 +slug: Web/API/Server-sent_events/Using_server-sent_events +tags: + - Advanced + - Communication + - DOM + - EventSource + - Guide + - SSE + - Server Sent Events + - Server-Sent-Event +translation_of: Web/API/Server-sent_events/Using_server-sent_events +--- +

{{DefaultAPISidebar("Server Sent Events")}}

+ +
+

開發一個使用 server-sent 事件的網頁應用程式很簡單。在伺服器端只需要一些的程式碼與網頁串流事件,而客戶端這邊的處理進入事件的部分幾乎跟 websockets 一樣。這是一種單向的連線,所以你無法從客戶端向伺服器傳送事件。

+
+ +

從伺服器端接收事件

+ +

server-sent event API 包含在  {{domxref("EventSource")}} 介面;為了與伺服器端開啟連線並接收事件,需要建立帶有產生事件 script URL 的 {{domxref("EventSource")}} 物件。例如:

+ +
const evtSource = new EventSource("ssedemo.php");
+ +

如果事件產生的 script 在不同源的伺服器上,在建立 {{domxref("EventSource")}} 物件時需要同時提供 URL 和第二個參數作為選項設定。假設客戶端的 script 伺服於 example.com

+ +
const evtSource = new EventSource("//api.example.com/ssedemo.php", { withCredentials: true } );
+ +

當你完成初始化事件來源後,你就可以透過新增 {{event("message")}} 事件的處理器來開始監聽來自伺服器的訊息:

+ +
evtSource.onmessage = function(event) {
+  const newElement = document.createElement("li");
+  const eventList = document.getElementById("list");
+
+  newElement.innerHTML = "message: " + event.data;
+  eventList.appendChild(newElement);
+}
+
+ +

上述的程式碼會監聽進入的訊息(這裡來自伺服器的通知沒有指明 event 欄位,所以統一用 onmessage 處理即可)並且把訊息的文字附加到 document 的清單。

+ +

你也可以利用 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);
+});
+
+ +

上述的程式碼大同小異,不同之處在於若伺服器傳送了 event 欄位值為「ping」的訊息時它就會把 data 欄位的值解析為 JSON 並輸出到畫面上。

+ +
+

當連線不是透過 HTTP/2 時,SSE 會受到最大連線數限制所苦,尤其當開啟多個分頁。每個瀏覽器有自己的限制數而且被限制在很低的數量(6)。這個問題已經被 ChromeFirefox 標註為「Won't fix」(不修復)。限制是基於每個瀏覽器 + 網域,也就是說你可以針對 www.example1.com 網域在所有的分頁中開啟六個 SSE 連線,另一個網域 www.example2.com 也可以開啟六個(根據 Stackoverflow)。當使用 HTTP/2 時最大同時 HTTP streams 連線數是由伺服器和客戶端之間協調(預設 100)。

+
+ +

從伺服器發送事件

+ +

由伺服器端所發送的事件需要使用 text/event-stream 的 MIME 類型回應。每一個通知皆由一組文字組成並由一對換行結尾。如何處理事件串流的格式,請參考 {{ anch("Event stream format") }} 。

+ +

下面是一個 {{Glossary("PHP")}} 範例:

+ +
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();
+
+  // Break the loop if the client aborted the connection (closed the page)
+
+  if ( connection_aborted() ) break;
+
+  sleep(1);
+}
+
+ +

上述的程式碼會在每秒產生一個類型為「ping」的事件。每一個事件的資料是一個 JSON 物件,內容為事件產生時的 ISO 8601 時間戳。同時會隨機發送一個簡易訊息(沒有事件類型)。
+ 迴圈的執行會獨立於連線的狀態,,所以在迴圈裡必須檢查連線的狀態,若斷線了要關閉連線(譬如,客戶端關閉了網頁)。

+ +
+

備註: 你可以從下列的 Github 文章中找到包含本文所使用程式碼的完整範例 —— 參考 Simple SSE demo using PHP.

+
+ +

錯誤處理

+ +

當錯誤發生時(譬如網路逾時或有關存取控制的問題)會產生錯誤事件。你可以透過對 EventSource 物件實作 onerror 回呼的方式採取程式化的處理:

+ +
evtSource.onerror = function(err) {
+  console.error("EventSource failed:", err);
+};
+
+ +

關閉事件串流

+ +

預設的情況下,如果客戶端和伺服器的連線關閉則連線會被重啟。連線的關閉會伴隨著 .close() 方法的執行。

+ +
evtSource.close();
+ +

事件串流(Event Stream)格式

+ +

事件串流是個簡易的文字資料串流,內容必須以 UTF-8 格式編碼。在事件串流中,不同的訊息以一對換行符號做區隔。若要撰寫註解,則要在該行的開頭加上冒號(:)。

+ +
備註: 註解將有助於防止連線逾時;伺服器端可以定時發送註解以維持連線活著。
+ +

每一個訊息是由一到多列的欄位所組成的文字。每個欄位依序由欄位的名稱、冒號、該欄位的文字內容所組合而成。

+ +

欄位

+ +

每隔訊息皆可以由下列的欄位組合而成,每個欄位以換行做為區隔:

+ +
+
event
+
事件的類型。如果有指定則在瀏覽器端會對該事件名稱的監聽器發布事件;網頁的原始碼必須使用 addEventListener() 來監聽已命名的事件。 onmessage 處理器只有在訊息沒有指定事件名稱時才會被呼叫。
+
data
+
訊息的資料欄位。當 EventSource 連續接收到多列以 data: 開頭的內容;它會串接這些內容並為每一列插入一個換行字元。最後的換行會被移除。
+
id
+
{{domxref("EventSource")}} 物件的最新一個事件 ID 。
+
retry
+
當嘗試傳送事件時重新連線的時間。這個值必須是整數,單位是毫秒,作為重新連線的時間。若指定是非整數則這個欄位會被忽略。
+
+ +

除上述的幾個欄位,其他欄位均會被忽略。

+ +
備註:如果某列的內容沒有包含冒號,則該列的內容都會被視為欄位名稱及空字串的欄位值。
+ +

範例

+ +

Data-only 訊息

+ +

在下列的範例中,共發送了三個訊息。第一個是註解,因其以冒號開頭。如之前提到的,對不會持續發送訊息的情境下,這將有助於維持連線的存續。

+ +

第二則訊息包含了 data 欄位及「some text」的值。第三則訊息包含了 data 欄位及「another message\nwith two lines」。注意在內容所出現的換行符號。

+ +
: this is a test stream
+
+data: some text
+
+data: another message
+data: with two lines
+
+ +

命名事件

+ +

這個範例傳送了一些命名的事件。每一個事件都被指定了 event 欄位並且 data 欄位也有相應的 JSON 字串作為客戶端回應事件所需的資料。 data 欄位的內容可以是任何的字串;它並沒有強制必須以 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."}
+
+ +

混合及配對

+ +

你並非一定只能用未命名訊息或已分類的事件;實際上你可以在單一的事件中把它們混合在一起。

+ +
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."}
+ +
+

EventSource

+ +
+ + +

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

+
+
diff --git a/files/zh-tw/web/api/storage/index.html b/files/zh-tw/web/api/storage/index.html new file mode 100644 index 0000000000..b3990bf756 --- /dev/null +++ b/files/zh-tw/web/api/storage/index.html @@ -0,0 +1,106 @@ +--- +title: Storage +slug: Web/API/Storage +translation_of: Web/API/Storage +--- +
 
+ +
{{APIRef("Web Storage API")}}
+ +

Web Storage API 中的 Storage 介面提供了存取特定 domain session 及本機儲存的方法。舉例而言,它能夠對存取的資料進行新增、刪除、修改,

+ +

在操作上,如果是對象是 domain session storage ,會呼叫 {{domxref("Window.sessionStorage")}} 。而若是 local storage,則呼叫 {{domxref("Window.localStorage")}} 。

+ +

屬性

+ +
+
{{domxref("Storage.length")}} {{readonlyInline}}
+
返回一數字,代表儲存在 Storage 中的物件的數量。
+
+ +

方法

+ +
+
{{domxref("Storage.key()")}}
+
當傳入一數字 n, 會返回 storage 裡第 n 個值的 key 值。
+
+ +
+
{{domxref("Storage.getItem()")}}
+
當傳入一 key 值, 會返回 storage 裡此 key 值對應的 value 。
+
{{domxref("Storage.setItem()")}}
+
當傳入 key 及 value 的值, 會在 storage 裡新增此 key 及 value 值,若 key 已存在,則會把值更新成傳入的 value。
+
{{domxref("Storage.removeItem()")}}
+
當傳入一 key 值, 會把此 key 從 storage 裡刪除。
+
{{domxref("Storage.clear()")}}
+
執行此方法,會刪除所有在 storage 裡的 key。
+
+ +

範例

+ +

在這裡,我們藉由呼叫 localStorage 來存取 Storage 物件,首先使用 !localStorage.getItem('bgcolor') 來確認 storage 裡是否有項目存在。

+ +

如果有,則執行函示 setStyles() ,這個函示使用 {{domxref("Storage.getItem()")}} 取得 storage 的值,並且用這些值更新頁面樣式 。

+ +

如果沒有,便執行另一個函示 populateStorage(),他使用 {{domxref("Storage.setItem()")}} 先設定 storage 項目的值,然後才執行setStyles()

+ +
if(!localStorage.getItem('bgcolor')) {
+  populateStorage();
+}
+setStyles();
+
+function populateStorage() {
+  localStorage.setItem('bgcolor', document.getElementById('bgcolor').value);
+  localStorage.setItem('font', document.getElementById('font').value);
+  localStorage.setItem('image', document.getElementById('image').value);
+}
+
+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);
+}
+ +
+

注意: 想要看這個範例完整運行,可以參考我們的  Web Storage Demo.

+
+ +

規範

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'webstorage.html#the-storage-interface', 'Storage')}}{{Spec2('HTML WHATWG')}} 
+ +

瀏覽器相容性

+ + + +

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

+ +

See also

+ + diff --git a/files/zh-tw/web/api/touch/index.html b/files/zh-tw/web/api/touch/index.html new file mode 100644 index 0000000000..3dc1a243b0 --- /dev/null +++ b/files/zh-tw/web/api/touch/index.html @@ -0,0 +1,207 @@ +--- +title: Touch +slug: Web/API/Touch +translation_of: Web/API/Touch +--- +

{{ APIRef("Touch Events") }}

+ +

Touch 介面表示了一個於觸控裝置上接觸的單一觸碰點。觸碰點通常是由手指或觸控筆所接觸,而裝置可能為觸控螢幕或觸控板。

+ +

{{ domxref("Touch.radiusX") }}、{{ domxref("Touch.radiusY") }} 及 {{ domxref("Touch.rotationAngle") }} 描述了使用者與螢幕之間接觸的區域—觸碰區(touch area),這對處理不精確的指向設備(如手指)來說相當有幫助。這些數值被用來描述一個盡可能與整個接觸面積相匹配的橢圓(如使用者的指尖)。{{experimental_inline}}

+ +
+

Note: Many of the properties' values are hardware-dependent; for example, if the device doesn't have a way to detect the amount of pressure placed on the surface, the force value will always be 0. This may also be the case for radiusX and radiusY; if the hardware reports only a single point, these values will be 1.

+
+ +

建構式

+ +
+
{{domxref("Touch.Touch", "Touch()")}} {{experimental_inline}}
+
Creates a Touch object.
+
+ +

屬性

+ +

This interface has no parent, and doesn't inherits or implements any other property.

+ +

基本屬性

+ +
+
{{ domxref("Touch.identifier") }} {{readonlyInline}}
+
Returns a unique identifier for this Touch object. A given touch point (say, by a finger) will have the same identifier for the duration of its movement around the surface. This lets you ensure that you're tracking the same touch all the time.
+
{{ domxref("Touch.screenX") }} {{readonlyInline}}
+
Returns the X coordinate of the touch point relative to the left edge of the screen.
+
{{ domxref("Touch.screenY") }} {{readonlyInline}}
+
Returns the Y coordinate of the touch point relative to the top edge of the screen.
+
{{ domxref("Touch.clientX") }} {{readonlyInline}}
+
Returns the X coordinate of the touch point relative to the left edge of the browser viewport, not including any scroll offset.
+
{{ domxref("Touch.clientY") }} {{readonlyInline}}
+
Returns the Y coordinate of the touch point relative to the top edge of the browser viewport, not including any scroll offset.
+
{{ domxref("Touch.pageX") }} {{readonlyInline}}
+
Returns the X coordinate of the touch point relative to the left edge of the document. Unlike clientX, this value includes the horizontal scroll offset, if any.
+
{{ domxref("Touch.pageY") }} {{readonlyInline}}
+
Returns the Y coordinate of the touch point relative to the top of the document. Unlike clientY, this value includes the vertical scroll offset, if any.
+
{{ domxref("Touch.target") }} {{readonlyInline}}
+
Returns the {{ domxref("Element")}} on which the touch point started when it was first placed on the surface, even if the touch point has since moved outside the interactive area of that element or even been removed from the document.
+
+ +

觸碰區(Touch area)

+ +

{{SeeCompatTable}}

+ +
+
{{ domxref("Touch.radiusX") }} {{readonlyInline}} {{experimental_inline}}
+
Returns the X radius of the ellipse that most closely circumscribes the area of contact with the screen. The value is in pixels of the same scale as screenX.
+
{{ domxref("Touch.radiusY") }} {{readonlyInline}} {{experimental_inline}}
+
Returns the Y radius of the ellipse that most closely circumscribes the area of contact with the screen. The value is in pixels of the same scale as screenY.
+
{{ domxref("Touch.rotationAngle") }} {{readonlyInline}} {{experimental_inline}}
+
Returns the angle (in degrees) that the ellipse described by radiusX and radiusY must be rotated, clockwise, to most accurately cover the area of contact between the user and the surface.
+
{{ domxref("Touch.force") }}{{readonlyInline}} {{experimental_inline}}
+
Returns the amount of pressure being applied to the surface by the user, as a float between 0.0 (no pressure) and 1.0 (maximum pressure).
+
+ +

方法

+ +

This interface has no method and no parent, and doesn't inherits or implements any method.

+ +
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Touch Events 2', '#touch-interface', 'Touch')}}{{Spec2('Touch Events 2')}}Added radiusX, radiusY, rotationAngle, force properties, as well as the Touch() constructor.
{{SpecName('Touch Events', '#touch-interface', 'Touch')}}{{Spec2('Touch Events')}}Initial definition.
+ +

瀏覽器相容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome("22.0")}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("18.0")}}[1]
+ {{CompatGeckoDesktop("52.0")}}[2]
{{CompatNo}}{{CompatNo}}{{CompatNo}}
radiusX, radiusY, rotationAngle, force{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Touch() constructor{{CompatUnknown}}{{CompatNo}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewChrome for AndroidEdgeFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("6.0")}}{{CompatVersionUnknown}}11{{CompatVersionUnknown}}{{CompatVersionUnknown}}
radiusX, radiusY, rotationAngle, force{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("6.0")}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Touch() constructor{{CompatUnknown}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatNo}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Touch events were implemented in Gecko 18.0, but removed again in 24.0 {{geckoRelease("24.0")}} on the desktop version of Firefox due to web compatibility issues ({{bug(888304)}}).

+ +

[2] As of Gecko 52.0, touch events support has been fixed and reenabled in Windows desktop platforms.

+ +

參見

+ + + +
+
diff --git a/files/zh-tw/web/api/touch_events/index.html b/files/zh-tw/web/api/touch_events/index.html new file mode 100644 index 0000000000..c12a14f49c --- /dev/null +++ b/files/zh-tw/web/api/touch_events/index.html @@ -0,0 +1,387 @@ +--- +title: 觸控事件 +slug: Web/API/Touch_events +translation_of: Web/API/Touch_events +--- +
{{DefaultAPISidebar("Touch Events")}}
+ +

為了支援基於觸碰的使用者介面,觸控事件提供了解釋手指或觸控筆於觸控螢幕或觸控板上活動的資訊。

+ +

觸控事件介面為相對低階的 API,可用來支援應用程式特定的多點觸控互動,例如兩指手勢。多點觸控互動起始於手指或觸控筆於平面的第一個觸碰,其它的手指可能於其後伴隨著移動才觸碰到平面。而互動則結束於手指自觸控平面離開。在此互動期間,應用程式會於開始、移動以及結束的階段接收到觸控事件。

+ +

觸控事件類似於滑鼠事件,但觸控事件支援同時間多個觸碰及其於觸控平面的每個不同點位置。{{domxref("TouchEvent")}} 介面封裝了所有當前作用中的觸碰點。{{domxref("Touch")}} 介面則表示個別的觸碰點,包括了如觸碰點於瀏覽器 viewport 中的相對位置資訊。

+ +

定義

+ +
+
平面(Surface)
+
The touch-sensitive surface. This may be a screen or trackpad.
+
+ +
+
觸碰點(Touch point)
+
A point of contact with the surface. This may be a finger (or elbow, ear, nose, whatever, but typically a finger) or stylus.
+
+ +

介面

+ +
+
{{domxref("TouchEvent")}}
+
Represents an event that occurs when the state of touches on the surface changes.
+
{{domxref("Touch")}}
+
Represents a single point of contact between the user and the touch surface.
+
{{domxref("TouchList")}}
+
Represents a group of touches; this is used when the user has, for example, multiple fingers on the surface at the same time.
+
+ +

範例

+ +

This example tracks multiple touch points at a time, allowing the user to draw in a {{HTMLElement("canvas")}} with more than one finger at a time. It will only work on a browser that supports touch events.

+ +
Note: The text below uses the term "finger" when describing the contact with the surface, but it could, of course, also be a stylus or other contact method.
+ +

Create a canvas

+ +
<canvas id="canvas" width="600" height="600" style="border:solid black 1px;">
+  Your browser does not support canvas element.
+</canvas>
+<br>
+<button onclick="startup()">Initialize</button>
+<br>
+Log: <pre id="log" style="border: 1px solid #ccc;"></pre>
+
+ +

Setting up the event handlers

+ +

When the page loads, the startup() function shown below should be called by our {{HTMLElement("body")}} element's onload attribute (but in the example we use a button to trigger it, due to limitations of the MDN live example system).

+ +
function startup() {
+  var el = document.getElementsByTagName("canvas")[0];
+  el.addEventListener("touchstart", handleStart, false);
+  el.addEventListener("touchend", handleEnd, false);
+  el.addEventListener("touchcancel", handleCancel, false);
+  el.addEventListener("touchmove", handleMove, false);
+  log("initialized.");
+}
+
+ +

This simply sets up all the event listeners for our {{HTMLElement("canvas")}} element so we can handle the touch events as they occur.

+ +

Tracking new touches

+ +

We'll keep track of the touches in-progress.

+ +
var ongoingTouches = [];
+
+ +

When a {{event("touchstart")}} event occurs, indicating that a new touch on the surface has occurred, the handleStart() function below is called.

+ +
function handleStart(evt) {
+  evt.preventDefault();
+  log("touchstart.");
+  var el = document.getElementsByTagName("canvas")[0];
+  var ctx = el.getContext("2d");
+  var touches = evt.changedTouches;
+
+  for (var i = 0; i < touches.length; i++) {
+    log("touchstart:" + i + "...");
+    ongoingTouches.push(copyTouch(touches[i]));
+    var color = colorForTouch(touches[i]);
+    ctx.beginPath();
+    ctx.arc(touches[i].pageX, touches[i].pageY, 4, 0, 2 * Math.PI, false);  // a circle at the start
+    ctx.fillStyle = color;
+    ctx.fill();
+    log("touchstart:" + i + ".");
+  }
+}
+
+ +

This calls {{domxref("event.preventDefault()")}} to keep the browser from continuing to process the touch event (this also prevents a mouse event from also being delivered). Then we get the context and pull the list of changed touch points out of the event's {{domxref("TouchEvent.changedTouches")}} property.

+ +

After that, we iterate over all the {{domxref("Touch")}} objects in the list, pushing them onto an array of active touch points and drawing the start point for the draw as a small circle; we're using a 4-pixel wide line, so a 4 pixel radius circle will show up neatly.

+ +

Drawing as the touches move

+ +

Each time one or more fingers moves, a {{event("touchmove")}} event is delivered, resulting in our handleMove() function being called. Its responsibility in this example is to update the cached touch information and to draw a line from the previous position to the current position of each touch.

+ +
function handleMove(evt) {
+  evt.preventDefault();
+  var el = document.getElementsByTagName("canvas")[0];
+  var ctx = el.getContext("2d");
+  var touches = evt.changedTouches;
+
+  for (var i = 0; i < touches.length; i++) {
+    var color = colorForTouch(touches[i]);
+    var idx = ongoingTouchIndexById(touches[i].identifier);
+
+    if (idx >= 0) {
+      log("continuing touch "+idx);
+      ctx.beginPath();
+      log("ctx.moveTo(" + ongoingTouches[idx].pageX + ", " + ongoingTouches[idx].pageY + ");");
+      ctx.moveTo(ongoingTouches[idx].pageX, ongoingTouches[idx].pageY);
+      log("ctx.lineTo(" + touches[i].pageX + ", " + touches[i].pageY + ");");
+      ctx.lineTo(touches[i].pageX, touches[i].pageY);
+      ctx.lineWidth = 4;
+      ctx.strokeStyle = color;
+      ctx.stroke();
+
+      ongoingTouches.splice(idx, 1, copyTouch(touches[i]));  // swap in the new touch record
+      log(".");
+    } else {
+      log("can't figure out which touch to continue");
+    }
+  }
+}
+
+ +

This iterates over the changed touches as well, but it looks in our cached touch information array for the previous information about each touch in order to determine the starting point for each touch's new line segment to be drawn. This is done by looking at each touch's {{domxref("Touch.identifier")}} property. This property is a unique integer for each touch, and remains consistent for each event during the duration of each finger's contact with the surface.

+ +

This lets us get the coordinates of the previous position of each touch and use the appropriate context methods to draw a line segment joining the two positions together.

+ +

After drawing the line, we call Array.splice() to replace the previous information about the touch point with the current information in the ongoingTouches array.

+ +

Handling the end of a touch

+ +

When the user lifts a finger off the surface, a {{event("touchend")}} event is sent. We handle both of these the same way: by calling the handleEnd() function below. Its job is to draw the last line segment for each touch that ended and remove the touch point from the ongoing touch list.

+ +
function handleEnd(evt) {
+  evt.preventDefault();
+  log("touchend");
+  var el = document.getElementsByTagName("canvas")[0];
+  var ctx = el.getContext("2d");
+  var touches = evt.changedTouches;
+
+  for (var i = 0; i < touches.length; i++) {
+    var color = colorForTouch(touches[i]);
+    var idx = ongoingTouchIndexById(touches[i].identifier);
+
+    if (idx >= 0) {
+      ctx.lineWidth = 4;
+      ctx.fillStyle = color;
+      ctx.beginPath();
+      ctx.moveTo(ongoingTouches[idx].pageX, ongoingTouches[idx].pageY);
+      ctx.lineTo(touches[i].pageX, touches[i].pageY);
+      ctx.fillRect(touches[i].pageX - 4, touches[i].pageY - 4, 8, 8);  // and a square at the end
+      ongoingTouches.splice(idx, 1);  // remove it; we're done
+    } else {
+      log("can't figure out which touch to end");
+    }
+  }
+}
+
+ +

This is very similar to the previous function; the only real differences are that we draw a small square to mark the end and that when we call Array.splice(), we simply remove the old entry from the ongoing touch list, without adding in the updated information. The result is that we stop tracking that touch point.

+ +

Handling canceled touches

+ +

If the user's finger wanders into browser UI, or the touch otherwise needs to be canceled, the {{event("touchcancel")}} event is sent, and we call the handleCancel() function below.

+ +
function handleCancel(evt) {
+  evt.preventDefault();
+  log("touchcancel.");
+  var touches = evt.changedTouches;
+
+  for (var i = 0; i < touches.length; i++) {
+    var idx = ongoingTouchIndexById(touches[i].identifier);
+    ongoingTouches.splice(idx, 1);  // remove it; we're done
+  }
+}
+
+ +

Since the idea is to immediately abort the touch, we simply remove it from the ongoing touch list without drawing a final line segment.

+ +

Convenience functions

+ +

This example uses two convenience functions that should be looked at briefly to help make the rest of the code more clear.

+ +

Selecting a color for each touch

+ +

In order to make each touch's drawing look different, the colorForTouch() function is used to pick a color based on the touch's unique identifier. This identifier is an opaque number, but we can at least rely on it differing between the currently-active touches.

+ +
function colorForTouch(touch) {
+  var r = touch.identifier % 16;
+  var g = Math.floor(touch.identifier / 3) % 16;
+  var b = Math.floor(touch.identifier / 7) % 16;
+  r = r.toString(16); // make it a hex digit
+  g = g.toString(16); // make it a hex digit
+  b = b.toString(16); // make it a hex digit
+  var color = "#" + r + g + b;
+  log("color for touch with identifier " + touch.identifier + " = " + color);
+  return color;
+}
+
+ +

The result from this function is a string that can be used when calling {{HTMLElement("canvas")}} functions to set drawing colors. For example, for a {{domxref("Touch.identifier")}} value of 10, the resulting string is "#aaa".

+ +

Copying a touch object

+ +

Some browsers (mobile Safari, for one) re-use touch objects between events, so it's best to copy the bits you care about, rather than referencing the entire object.

+ +
function copyTouch(touch) {
+  return { identifier: touch.identifier, pageX: touch.pageX, pageY: touch.pageY };
+}
+ +

Finding an ongoing touch

+ +

The ongoingTouchIndexById() function below scans through the ongoingTouches array to find the touch matching the given identifier, then returns that touch's index into the array.

+ +
function ongoingTouchIndexById(idToFind) {
+  for (var i = 0; i < ongoingTouches.length; i++) {
+    var id = ongoingTouches[i].identifier;
+
+    if (id == idToFind) {
+      return i;
+    }
+  }
+  return -1;    // not found
+}
+
+ +

Showing what's going on

+ +
function log(msg) {
+  var p = document.getElementById('log');
+  p.innerHTML = msg + "\n" + p.innerHTML;
+}
+ +

If your browser supports it, you can {{LiveSampleLink('Example', 'see it live')}}.

+ +

jsFiddle example

+ +

Additional tips

+ +

This section provides additional tips on how to handle touch events in your web application.

+ +

Handling clicks

+ +

Since calling preventDefault() on a {{event("touchstart")}} or the first {{event("touchmove")}} event of a series prevents the corresponding mouse events from firing, it's common to call preventDefault() on {{event("touchmove")}} rather than {{event("touchstart")}}. That way, mouse events can still fire and things like links will continue to work. Alternatively, some frameworks have taken to refiring touch events as mouse events for this same purpose. (This example is oversimplified and may result in strange behavior. It is only intended as a guide.)

+ +
function onTouch(evt) {
+  evt.preventDefault();
+  if (evt.touches.length > 1 || (evt.type == "touchend" && evt.touches.length > 0))
+    return;
+
+  var newEvt = document.createEvent("MouseEvents");
+  var type = null;
+  var touch = null;
+
+  switch (evt.type) {
+    case "touchstart":
+      type = "mousedown";
+      touch = evt.changedTouches[0];
+      break;
+    case "touchmove":
+      type = "mousemove";
+      touch = evt.changedTouches[0];
+      break;
+    case "touchend":
+      type = "mouseup";
+      touch = evt.changedTouches[0];
+      break;
+  }
+
+  newEvt.initMouseEvent(type, true, true, evt.originalTarget.ownerDocument.defaultView, 0,
+    touch.screenX, touch.screenY, touch.clientX, touch.clientY,
+    evt.ctrlKey, evt.altKey, evt.shiftKey, evt.metaKey, 0, null);
+  evt.originalTarget.dispatchEvent(newEvt);
+}
+
+ +

Calling preventDefault() only on a second touch

+ +

One technique for preventing things like pinchZoom on a page is to call preventDefault() on the second touch in a series. This behavior is not well defined in the touch events spec, and results in different behavior for different browsers (i.e., iOS will prevent zooming but still allow panning with both fingers; Android will allow zooming but not panning; Opera and Firefox currently prevent all panning and zooming.) Currently, it's not recommended to depend on any particular behavior in this case, but rather to depend on meta viewport to prevent zooming.

+ +

規範

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Touch Events 2', '#touch-interface', 'Touch')}}{{Spec2('Touch Events 2')}}Added radiusX, radiusY, rotationAngle, force properties
{{SpecName('Touch Events', '#touch-interface', 'Touch')}}{{Spec2('Touch Events')}}Initial definition.
+ +

瀏覽器相容性

+ +

{{CompatibilityTable}}

+ +

Note that unfortunately touch events may not fire at all on laptops with touch functionality (test page).

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("22.0")}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("18.0")}}[1]
+ {{CompatGeckoDesktop("52.0")}}[2]
{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewChrome for AndroidEdgeFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("6.0")}}{{CompatVersionUnknown}}11{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

[1] The dom.w3c_touch_events.enabled tri-state preference can be used to disable (0), enable (1), and auto-detect (2) support for standard touch events; by default, they're on auto-detect (2).

+ +

As of Gecko 24.0 {{geckoRelease("24.0")}}, the touch events support introduced with Gecko 18.0 {{geckoRelease("18.0")}} has been disabled on the desktop version of Firefox ({{bug(888304)}}), as some popular sites including Google and Twitter were not working properly. Once the bug is fixed, the API will be enabled again. To enable it anyway, open about:config and set the dom.w3c_touch_events.enabled preference to 2. The mobile versions including Firefox for Android and Firefox OS are not affected by this change.

+ +

[2] As of Gecko 52.0, touch events support has been fixed and reenabled in Windows desktop platforms.

+ +
+

Note: Prior to Gecko 6.0 {{geckoRelease("6.0")}}, Gecko offered a proprietary touch event API. That API is now deprecated; you should switch to this one.

+
diff --git a/files/zh-tw/web/api/touchevent/index.html b/files/zh-tw/web/api/touchevent/index.html new file mode 100644 index 0000000000..5c435c008f --- /dev/null +++ b/files/zh-tw/web/api/touchevent/index.html @@ -0,0 +1,201 @@ +--- +title: TouchEvent +slug: Web/API/TouchEvent +translation_of: Web/API/TouchEvent +--- +

{{ APIRef("Touch Events") }}

+ +

TouchEvent 介面表示了一個由觸控平面因觸碰而改變狀態所發出的事件。平面可以是觸控螢幕或是觸控板,TouchEvent 能描述一或多個觸碰點,並且支援偵測其移動、增加或減少觸碰點等等功能。

+ +

觸碰點是由 {{ domxref("Touch") }} 物件表示;每一個觸碰點描述了其位置、大小與形狀、壓力值以及目標元素。觸碰點列表由 {{ domxref("TouchList") }} 所表示。

+ +

建構式

+ +
+
{{domxref("TouchEvent.TouchEvent", "TouchEvent()")}}
+
Creates a TouchEvent object.
+
+ +

屬性

+ +

此介面也繼承了其父介面 {{domxref("UIEvent")}} 與 {{domxref("Event")}} 的屬性

+ +
+
{{ domxref("TouchEvent.altKey") }} {{readonlyInline}}
+
A Boolean value indicating whether or not the alt key was down when the touch event was fired.
+
{{ domxref("TouchEvent.changedTouches") }} {{readonlyInline}}
+
A {{ domxref("TouchList") }} of all the {{ domxref("Touch") }} objects representing individual points of contact whose states changed between the previous touch event and this one.
+
{{ domxref("TouchEvent.ctrlKey") }} {{readonlyInline}}
+
A Boolean value indicating whether or not the control key was down when the touch event was fired.
+
{{ domxref("TouchEvent.metaKey") }} {{readonlyInline}}
+
A Boolean value indicating whether or not the meta key was down when the touch event was fired.
+
{{ domxref("TouchEvent.shiftKey") }} {{readonlyInline}}
+
A Boolean value indicating whether or not the shift key was down when the touch event was fired.
+
{{ domxref("TouchEvent.targetTouches") }}{{readonlyInline}}
+
A {{ domxref("TouchList") }} of all the {{ domxref("Touch") }} objects that are both currently in contact with the touch surface and were also started on the same element that is the target of the event.
+
{{ domxref("TouchEvent.touches") }} {{readonlyInline}}
+
A {{ domxref("TouchList") }} of all the {{ domxref("Touch") }} objects representing all current points of contact with the surface, regardless of target or changed status.
+
+ +

觸控事件類型

+ +

觸控事件有多個種類可以代表觸碰狀態發生了改變。可以藉由 {{ domxref("event.type", "TouchEvent.type") }} 屬性來確認是哪一個種類的觸控事件。

+ +

{{event("touchstart")}}

+ +

Sent when the user places a touch point on the touch surface. The event's target will be the {{ domxref("element") }} in which the touch occurred.

+ +

{{event("touchend")}}

+ +

Sent when the user removes a touch point from the surface (that is, when they lift a finger or stylus from the surface). This is also sent if the touch point moves off the edge of the surface; for example, if the user's finger slides off the edge of the screen.

+ +

The event's target is the same {{ domxref("element") }} that received the touchstart event corresponding to the touch point, even if the touch point has moved outside that element.

+ +

The touch point (or points) that were removed from the surface can be found in the {{ domxref("TouchList") }} specified by the changedTouches attribute.

+ +

{{event("touchmove")}}

+ +

Sent when the user moves a touch point along the surface. The event's target is the same {{ domxref("element") }} that received the touchstart event corresponding to the touch point, even if the touch point has moved outside that element.

+ +

This event is also sent if the values of the radius, rotation angle, or force attributes of a touch point change.

+ +
Note: The rate at which touchmove events is sent is browser-specific, and may also vary depending on the capability of the user's hardware. You must not rely on a specific granularity of these events.
+ +

{{event("touchcancel")}}

+ +

Sent when a touch point has been disrupted in some way. There are several possible reasons why this might happen (and the exact reasons will vary from device to device, as well as browser to browser):

+ + + +

Using with addEventListener() and preventDefault()

+ +

It's important to note that in many cases, both touch and mouse events get sent (in order to let non-touch-specific code still interact with the user). If you use touch events, you should call {{domxref("Event.preventDefault","preventDefault()")}} to keep the mouse event from being sent as well.

+ +

The exception to this is Chrome, starting with version 56 (desktop, Chrome for android, and android webview), where the default value for {{event("touchstart")}} and {{event("touchmove")}} is true and calls to {{domxref("Event.preventDefault","preventDefault()")}} are not needed. To override this behavior, you simply set the passive option to false as shown in the example below. This change prevents the listener from blocking page rendering while a user is scrolling. A demo is available on the Google Developer site.

+ +

GlobalEventHandlers

+ +

{{SeeCompatTable}}

+ +
+
{{ domxref("GlobalEventHandlers.ontouchstart") }} {{experimental_inline}}
+
A {{domxref("GlobalEventHandlers","global event handler")}} for the {{event("touchstart")}} event.
+
{{ domxref("GlobalEventHandlers.ontouchend") }} {{experimental_inline}}
+
A {{domxref("GlobalEventHandlers","global event handler")}} for the {{event("touchend")}} event.
+
{{ domxref("GlobalEventHandlers.ontouchmove") }} {{experimental_inline}}
+
A {{domxref("GlobalEventHandlers","global event handler")}} for the {{event("touchmove")}} event.
+
{{ domxref("GlobalEventHandlers.ontouchcancel") }} {{experimental_inline}}
+
A {{domxref("GlobalEventHandlers","global event handler")}} for the {{event("touchcancel")}} event.
+
+ +

範例

+ +

See the example on the main Touch events article.

+ +

規範

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Touch Events 2','#touchevent-interface', 'TouchEvent')}}{{Spec2('Touch Events 2')}}Added ontouchstart, ontouchend, ontouchmove, ontouchend global attribute handlers
{{SpecName('Touch Events', '#touchevent-interface', 'TouchEvent')}}{{Spec2('Touch Events')}}Initial definition.
+ +

瀏覽器相容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome("22.0")}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("18.0")}}[1]
+ {{CompatGeckoDesktop("52.0")}}[2]
{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidEdgeFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("6.0")}}{{CompatVersionUnknown}}11{{CompatVersionUnknown}}{{CompatVersionUnknown}}
TouchEvent(){{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

[1] Touch events were implemented in Gecko 18.0, but removed again in 24.0 {{geckoRelease("24.0")}} on the desktop version of Firefox due to web compatibility issues ({{bug(888304)}}).

+ +

[2] As of Gecko 52.0, touch events support has been fixed and reenabled in Windows desktop platforms.

+ +

參見

+ + diff --git a/files/zh-tw/web/api/touchlist/index.html b/files/zh-tw/web/api/touchlist/index.html new file mode 100644 index 0000000000..d106b9df7d --- /dev/null +++ b/files/zh-tw/web/api/touchlist/index.html @@ -0,0 +1,120 @@ +--- +title: TouchList +slug: Web/API/TouchList +translation_of: Web/API/TouchList +--- +
+

{{ APIRef("Touch Events") }}

+
+ +

TouchList 介面表示了一個觸控平面上所有觸碰點的列表;舉例來說,假如使用者有三隻手指於觸控平面(如觸控螢幕或是觸控板)上,則其相對應的 TouchList 物件中就會分別有三個 {{domxref("Touch")}} 物件各代表一個手指的觸碰。

+ +

屬性

+ +
+
{{domxref("TouchList.length")}} {{readonlyInline}}
+
The number of {{domxref("Touch")}} objects in the TouchList.
+
+ +

方法

+ +
+
{{domxref("TouchList.identifiedTouch()")}} {{obsolete_inline}}
+
Returns the first {{domxref("Touch")}} item in the list whose identifier matches a specified value.
+
{{domxref("TouchList.item()")}}
+
Returns the {{domxref("Touch")}} object at the specified index in the list.
+
+ +

範例

+ +

See the example on the main Touch events article.

+ +

規範

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Touch Events 2','#touchlist-interface')}}{{Spec2('Touch Events 2')}}Non-stable version.
{{SpecName('Touch Events', '#touchlist-interface')}}{{Spec2('Touch Events')}}Initial definition.
+ +

瀏覽器相容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome("22.0")}}{{CompatGeckoDesktop("18.0")}}[1]
+ {{CompatGeckoDesktop("52.0")}}[2]
{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("6.0")}}{{CompatVersionUnknown}}11{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

[1] Touch events were implemented in Gecko 18.0, but removed again in 24.0 {{geckoRelease("24.0")}} on the desktop version of Firefox due to web compatibility issues ({{bug(888304)}}).

+ +

[2] As of Gecko 52.0, touch events support has been fixed and reenabled in Windows desktop platforms.

+ +

參見

+ + diff --git a/files/zh-tw/web/api/uievent/index.html b/files/zh-tw/web/api/uievent/index.html new file mode 100644 index 0000000000..a5a1228ec8 --- /dev/null +++ b/files/zh-tw/web/api/uievent/index.html @@ -0,0 +1,188 @@ +--- +title: UIEvent +slug: Web/API/UIEvent +tags: + - 待翻譯 +translation_of: Web/API/UIEvent +--- +

{{APIRef("DOM Events")}}

+ +

UIEvent 介面是使用者介面的事件的基本型態。

+ +

UIEvent 是從 {{domxref("Event")}} 衍伸過來。 雖然為了相容性,仍留著 {{domxref("UIEvent.initUIEvent()")}} 方法,建立 UIEvent 物件最好是選擇以 {{domxref("UIEvent.UIEvent", "UIEvent()")}} constructor 建立。

+ +

許多介面直接或間接繼承此介面,例如:{{domxref("MouseEvent")}}、{{domxref("TouchEvent")}}、{{domxref("FocusEvent")}}、{{domxref("KeyboardEvent")}}、{{domxref("WheelEvent")}}、{{domxref("InputEvent")}} 和 {{domxref("CompositionEvent")}}。

+ +

建構式

+ +
+
{{domxref("UIEvent.UIEvent()", "UIEvent()")}}
+
建立一個 UIEvent 物件 。
+
+ +

屬性

+ +

此介面亦繼承其父-- {{domxref("Event")}} 的屬性:

+ +
+
{{domxref("UIEvent.cancelBubble")}} {{Non-standard_inline}} {{Deprecated_inline}}
+
Is a {{jsxref("Boolean")}} indicating whether the bubbling of the event has been canceled or not.
+
+ +
+
{{domxref("UIEvent.detail")}}{{readonlyinline}}
+
Returns a long with details about the event, depending on the event type.
+
{{domxref("UIEvent.isChar")}} {{obsolete_inline}} {{readonlyinline}}
+
Returns a {{jsxref("Boolean")}} indicating whether the event produced a key character or not.
+
{{domxref("UIEvent.layerX")}} {{Non-standard_inline}} {{readonlyinline}}
+
Returns the horizontal coordinate of the event relative to the current layer.
+
{{domxref("UIEvent.layerY")}} {{Non-standard_inline}} {{readonlyinline}}
+
Returns the vertical coordinate of the event relative to the current layer.
+
{{domxref("UIEvent.pageX")}} {{Non-standard_inline}} {{readonlyinline}}
+
Returns the horizontal coordinate of the event relative to the whole document.
+
{{domxref("UIEvent.pageY")}} {{Non-standard_inline}} {{readonlyinline}}
+
Returns the vertical coordinate of the event relative to the whole document.
+
{{domxref("UIEvent.sourceCapabilities")}} {{non-standard_inline}} {{readonlyinline}}
+
Returns an instance of the InputDeviceCapabilities interface which provides information about the physical device responsible for generating a touch event.
+
{{domxref("UIEvent.view")}}{{readonlyinline}}
+
Returns a {{domxref("WindowProxy")}} that contains the view that generated the event.
+
{{domxref("UIEvent.which")}} {{Non-standard_inline}} {{readonlyinline}}
+
Returns the numeric keyCode of the key pressed, or the character code (charCode) for an alphanumeric key pressed.
+
+ +

方法

+ +

此介面亦繼承其父-- {{domxref("Event")}} 的方法:

+ +
+
{{domxref("UIEvent.initUIEvent()")}} {{deprecated_inline}}
+
初始化 UIEvent 物件。若該事件已經觸發的話,此方法就不會執行任何東西。
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('InputDeviceCapabilities')}}{{Spec2('InputDeviceCapabilities')}}Added sourceCapabilities property.
{{SpecName('DOM3 Events', '#interface-UIEvent', 'UIEvent')}}{{Spec2('DOM3 Events')}}Added the UIEvent() constructor, deprecated the initUIEvent() method and changed the type of view from AbstractView to WindowProxy.
{{SpecName('DOM2 Events', '#Events-UIEvent', 'UIEvent')}}{{Spec2('DOM2 Events')}}Initial definition
+ +

瀏覽器相容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}[2]{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
UIEvent(){{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop(11)}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
cancelBubble defined on Event{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop(53)}}[1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}[2]{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
UIEvent(){{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile(11)}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}
cancelBubble defined on Event{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile(53)}}[1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] From Firefox 52, this property is now defined on the {{domxref("Event")}} interface instead. See {{bug(1298970)}} for more details.

+ +

[2] The {{domxref("UIEvent.isChar", "isChar")}} property has never been supported by any browser but Firefox, and even on Firefox it's never worked except on Mac OSX. For that reason, it's been removed in Firefox 55 to align with other browsers.

+ +

參見

+ + diff --git a/files/zh-tw/web/api/uievent/uievent/index.html b/files/zh-tw/web/api/uievent/uievent/index.html new file mode 100644 index 0000000000..d18be6387f --- /dev/null +++ b/files/zh-tw/web/api/uievent/uievent/index.html @@ -0,0 +1,134 @@ +--- +title: UIEvent() +slug: Web/API/UIEvent/UIEvent +translation_of: Web/API/UIEvent/UIEvent +--- +

{{APIRef("DOM Events")}}

+ +

UIEvent() constructor 是用來建立新的 {{domxref("UIEvent")}}。

+ +

語法

+ +
 event = new UIEvent(typeArg, UIEventInit);
+ +

參數

+ +
+
typeArg
+
一個 {{domxref("DOMString")}} ,用來表示事件名稱
+
UIEventInit{{optional_inline}}
+
+ +
+
一個 UIEventInit dictionary ,能接受以下參數: + + + + + + + + + + + + + + + + + + + + + + + + + + + +
參數可選默認值類型說明
"detail"0long定義事件意義的值。關於事件的意義於 {{domxref("UIEvent.detail")}} 已有較詳盡的列表。
"view"null{{domxref("WindowProxy")}}與事件相關的 {{domxref("Window")}} 。
+ +
+

UIEventInit dictionary 亦接受 {{domxref("Event.Event", "EventInit")}} dictionary 所接受的參數。

+
+
+
+ +

規格

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM3 Events','#interface-UIEvent','UIEvent()')}}{{Spec2('DOM3 Events')}}原始定義。
+ +

瀏覽器支援度

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatVersionUnknown() }}{{ CompatGeckoDesktop(11) }}{{ CompatUnknown() }}{{ CompatVersionUnknown() }}{{ CompatUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatGeckoMobile(11) }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

延伸閱讀

+ + diff --git a/files/zh-tw/web/api/url/createobjecturl/index.html b/files/zh-tw/web/api/url/createobjecturl/index.html new file mode 100644 index 0000000000..8760dffaec --- /dev/null +++ b/files/zh-tw/web/api/url/createobjecturl/index.html @@ -0,0 +1,137 @@ +--- +title: URL.createObjectURL() +slug: Web/API/URL/createObjectURL +translation_of: Web/API/URL/createObjectURL +--- +
{{ApiRef("URL API")}}{{SeeCompatTable}}
+ +

摘要

+ +

靜態方法 URL.createObjectURL() 用於建立一個帶有URL的 {{domxref("DOMString")}} 以代表參數中所傳入的物件. 該URL的生命週期與創造它的window中的 {{domxref("document")}}一致. 這個新的物件URL 代表了所指定的 {{domxref("File")}} 物件 或是 {{domxref("Blob")}} 物件.

+ +

{{AvailableInWorkers}}

+ +

語法

+ +
objectURL = URL.createObjectURL(blob);
+
+ +

參數

+ +
+
blob
+
+ +
+
一個用以建立物件URL的 {{domxref("File")}} 物件 或是 {{domxref("Blob")}} 物件.
+
+ + + +

範例

+ +

參見 Using object URLs to display images.(藉由物件URL來顯示圖像)

+ +

注意事項

+ +

每次呼叫 createObjectURL() 都會產生一個新的URL, 不論是否曾以同一物件產生過. 當你不再需要它們的時候必須對每一個都呼叫 {{domxref("URL.revokeObjectURL()")}} 來釋放它們. 瀏覽器會在document被unload時自動釋放它們; 然而, 為了最佳化效能與記憶體用量, 當有安全的時機請務必手動釋放它們.

+ +

規範文件

+ + + + + + + + + + + + + + +
規範文件狀態附註
{{SpecName('File API', '#dfn-createObjectURL', 'URL')}}{{Spec2('File API')}}Initial definition.
+ +

瀏覽器相容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
功能ChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support8 [1]
+ {{CompatChrome(23)}}
{{CompatGeckoDesktop(2)}}{{CompatIE(10)}}{{CompatOpera(15)}}{{CompatSafari(6)}} [1]
+ {{CompatSafari(7)}}
In a {{ domxref("Worker", "Web Worker") }}10 [1]
+ {{CompatChrome(23)}}
{{CompatGeckoDesktop(21)}}{{CompatIE(11)}}{{CompatOpera(15)}}{{CompatSafari(6)}} [1]
+ {{CompatSafari(7)}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChrome for AndroidAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support18 [1]4.0 [1]{{CompatGeckoMobile(14)}}{{CompatUnknown}}{{CompatOpera(15)}} [1]6.0 [1]
In a {{ domxref("Worker", "Web Worker") }}18 [1]{{CompatVersionUnknown}} [1]{{CompatGeckoMobile(14)}}{{CompatUnknown}}{{CompatOpera(15)}} [1]6.0 [1]
+
+ +

[1]  在該瀏覽器中必須使用 webkitURL 而非 URL

+ +

另見

+ + diff --git a/files/zh-tw/web/api/url/index.html b/files/zh-tw/web/api/url/index.html new file mode 100644 index 0000000000..0a7fdb670b --- /dev/null +++ b/files/zh-tw/web/api/url/index.html @@ -0,0 +1,212 @@ +--- +title: URL +slug: Web/API/URL +tags: + - API + - Experimental + - NeedsTranslation + - TopicStub + - URL API +translation_of: Web/API/URL +--- +
{{ApiRef("URL API")}} {{SeeCompatTable}}
+ +

URL 介面提供了建立 URL 物件的靜態方法。

+ +

使用尚未實作此物件的瀏覽器時,可以改用 {{domxref("Window.URL")}} 屬性來呼叫(基於 Webkit 或 Blink 引擎的瀏覽器可使用 Window.webkitURL)。

+ +

{{AvailableInWorkers}}

+ +

屬性

+ +
+
{{domxref("URL.href")}}
+
Is a {{domxref("DOMString")}} containing the whole URL.
+
{{domxref("URL.protocol")}}
+
Is a {{domxref("DOMString")}} containing the protocol scheme of the URL, including the final ':'.
+
{{domxref("URL.host")}}
+
Is a {{domxref("DOMString")}} containing the host, that is the hostname, a ':', and the port of the URL.
+
{{domxref("URL.hostname")}}
+
Is a {{domxref("DOMString")}} containing the domain of the URL.
+
{{domxref("URL.port")}}
+
Is a {{domxref("DOMString")}} containing the port number of the URL.
+
{{domxref("URL.pathname")}}
+
Is a {{domxref("DOMString")}} containing an initial '/' followed by the path of the URL.
+
{{domxref("URL.search")}}
+
Is a {{domxref("DOMString")}} containing a '?' followed by the parameters of the URL.
+
{{domxref("URL.hash")}}
+
Is a {{domxref("DOMString")}} containing a '#' followed by the fragment identifier of the URL.
+
{{domxref("URL.username")}}
+
Is a {{domxref("DOMString")}} containing the username specified before the domain name.
+
{{domxref("URL.password")}}
+
Is a {{domxref("DOMString")}} containing the password specified before the domain name.
+
{{domxref("URL.origin")}} {{readonlyInline}}
+
Returns a {{domxref("DOMString")}} containing the origin of the URL, that is its scheme, its domain and its port.
+
+ +
+
{{domxref("URL.searchParams")}}
+
Returns a {{domxref("URLSearchParams")}} object allowing to access the GET query arguments contained in the URL.
+
+ +

建構式

+ +
+
{{domxref("URL.URL", "URL()")}}
+
Creates and return a URL object composed from the given parameters.
+
+ +

方法

+ +

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

靜態方法

+ +
+
{{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()")}}.
+
+ +

規範

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

瀏覽器相容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support8.0[2]
+ 32
{{CompatUnknown}}{{CompatGeckoDesktop("2.0")}}[1][3]
+ {{CompatGeckoDesktop("19.0")}}
10.015.0[2]
+ 19
6.0[2]
+ 7.0
username, password, and origin32{{CompatUnknown}}{{CompatGeckoDesktop("26.0")}}{{CompatUnknown}}19{{CompatVersionUnknown}}
searchParams{{CompatChrome(49)}}{{CompatUnknown}}{{CompatGeckoDesktop("29.0")}}{{CompatUnknown}}36{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support4[2]
+ 4.4
8.0[2]
+ 32
{{CompatGeckoMobile("14.0")}}[1][3]
+ {{CompatGeckoMobile("19.0")}}
{{CompatVersionUnknown}}15.0[2]6.0[2]
username, password, and origin4.432{{CompatGeckoDesktop("26.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
searchParams{{CompatNo}}{{CompatChrome(49)}}{{CompatGeckoMobile("29.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

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

+ +

[2] This feature is implemented under the non-standard name webkitURL.

+ +

[3] For Firefox, 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.

+ +

參見

+ + diff --git a/files/zh-tw/web/api/validitystate/index.html b/files/zh-tw/web/api/validitystate/index.html new file mode 100644 index 0000000000..8cd2bdd738 --- /dev/null +++ b/files/zh-tw/web/api/validitystate/index.html @@ -0,0 +1,145 @@ +--- +title: ValidityState +slug: Web/API/ValidityState +translation_of: Web/API/ValidityState +--- +
{{APIRef("HTML DOM")}} {{gecko_minversion_header("2.0")}}
+ +

ValidityState 介面表示了一個元素目前在其檢核條件下驗證的正確性狀態(validity states)。同時,它們也可以協助解釋元素值檢核失敗的原因,如果元素值為不合法的。

+ +

屬性

+ +

For each of these Boolean properties, a value of true indicates that the specified reason validation may have failed is true, with the exception of the valid property, which is true if the element's value obeys all constraints.

+ +
+
{{domxref("ValidityState.badInput")}} {{ReadOnlyInline}}
+
Is a {{jsxref("Boolean")}} indicating the user has provided input that the browser is unable to convert.
+
{{domxref("ValidityState.customError")}} {{ReadOnlyInline}}
+
Is a {{jsxref("Boolean")}} indicating the element's custom validity message has been set to a non-empty string by calling the element's setCustomValidity() method.
+
{{domxref("ValidityState.patternMismatch")}} {{ReadOnlyInline}}
+
Is a {{jsxref("Boolean")}} indicating the value does not match the specified {{htmlattrxref("pattern", "input")}}.
+
{{domxref("ValidityState.rangeOverflow")}} {{ReadOnlyInline}}
+
Is a {{jsxref("Boolean")}} indicating the value is greater than the maximum specified by the {{htmlattrxref("max", "input")}} attribute.
+
{{domxref("ValidityState.rangeUnderflow")}} {{ReadOnlyInline}}
+
Is a {{jsxref("Boolean")}} indicating the value is less than the minimum specified by the {{htmlattrxref("min", "input")}} attribute.
+
{{domxref("ValidityState.stepMismatch")}} {{ReadOnlyInline}}
+
Is a {{jsxref("Boolean")}} indicating the value does not fit the rules determined by the {{htmlattrxref("step", "input")}} attribute (that is, it's not evenly divisible by the step value).
+
{{domxref("ValidityState.tooLong")}} {{ReadOnlyInline}}
+
Is a {{jsxref("Boolean")}} indicating the value exceeds the specified maxlength for {{domxref("HTMLInputElement")}} or {{domxref("HTMLTextAreaElement")}} objects. Note: This will never be true in Gecko, because elements' values are prevented from being longer than maxlength.
+
{{domxref("ValidityState.tooShort")}} {{ReadOnlyInline}}
+
Is a {{jsxref("Boolean")}} indicating the value fails to meet the specified minlength for {{domxref("HTMLInputElement")}} or {{domxref("HTMLTextAreaElement")}} objects.
+
{{domxref("ValidityState.typeMismatch")}} {{ReadOnlyInline}}
+
Is a {{jsxref("Boolean")}} indicating the value is not in the required syntax (when {{htmlattrxref("type", "input")}} is email or url).
+
{{domxref("ValidityState.valid")}} {{ReadOnlyInline}}
+
Is a {{jsxref("Boolean")}} indicating the element meets all constraint validations, and is therefore considered to be valid.
+
{{domxref("ValidityState.valueMissing")}} {{ReadOnlyInline}}
+
Is a {{jsxref("Boolean")}} indicating the element has a {{htmlattrxref("required", "input")}} attribute, but no value.
+
+ +

規範

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

瀏覽器相容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatVersionUnknown() }}{{CompatVersionUnknown}}{{ CompatVersionUnknown }}10{{ CompatVersionUnknown() }}10.0.3
badInput{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop(29)}}{{CompatUnknown}}{{CompatUnknown}}10.0.3
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{CompatVersionUnknown}}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
badIndput{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(29)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

參見

+ + diff --git a/files/zh-tw/web/api/vibration_api/index.html b/files/zh-tw/web/api/vibration_api/index.html new file mode 100644 index 0000000000..115020dbda --- /dev/null +++ b/files/zh-tw/web/api/vibration_api/index.html @@ -0,0 +1,113 @@ +--- +title: Vibration API +slug: Web/API/Vibration_API +translation_of: Web/API/Vibration_API +--- +

{{DefaultAPISidebar("Vibration API")}}

+ +

目前大多數的行動裝置均具備振動硬體以搖晃裝置,讓軟體程式碼能對使用者產生實際反饋。Vibration API 即可讓 Web Apps 存取振動硬體。當然,若裝置並未支援振動硬體,就不會產生任何效果。

+ +

振動說明

+ +

振動即如「on-off」脈衝的形式,且持續時間亦有不同的變化。可透過單一整數讓振動持續數個毫秒 (ms);或可由多個整數組成陣列,達到振動與暫停交錯的振動形式。只要單一 window.navigator.vibrate() 函式即可控制振動。

+ +

單次振動

+ +

你可指定單一數值,或用單一數值構成 1 組陣列,讓振動硬體動作 1 次:

+ +
window.navigator.vibrate(200);
+window.navigator.vibrate([200]);
+
+ +

上列 2 個範例均可使裝置振動達 200 ms。

+ +

振動形式

+ +

用數值構成陣列,敘述裝置在一段期間內振動與停止振動的情形。陣列中的所有值均轉換為整數,接著直譯 (Interprete) 成裝置振動與停止振動的毫秒數。範例如下:

+ +
window.navigator.vibrate([200, 100, 200]);
+
+ +

根據此陣列,裝置將振動 200 ms、暫停 100 ms,再振動 200 ms。

+ +

你可照自己喜好而指定多組振動/暫停的變化,且輸入項的數量為奇數或偶數均可。由於振動將在每個振動期間結束時停止,所以不一定要提供暫停數值作為最後 1 組輸入項。

+ +

取消目前振動

+ +

window.navigator.vibrate() 的值為「0」、空白陣列,或陣列全為「0」時呼叫此函式,即可取消目前執行中的振動作業。

+ +

規格

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Vibration API')}}{{Spec2('Vibration API')}}Initial specification.
+ +

瀏覽器相容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}} {{property_prefix("webkit")}}11.0 {{property_prefix("moz")}}
+ 16 (no prefix)
{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}} {{property_prefix("webkit")}}11.0 {{property_prefix("moz")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

另可參閱

+ + diff --git a/files/zh-tw/web/api/web_audio_api/index.html b/files/zh-tw/web/api/web_audio_api/index.html new file mode 100644 index 0000000000..f2eef8f535 --- /dev/null +++ b/files/zh-tw/web/api/web_audio_api/index.html @@ -0,0 +1,119 @@ +--- +title: Web Audio API +slug: Web/API/Web_Audio_API +translation_of: Web/API/Web_Audio_API +--- +

{{SeeCompatTable}}

+

Show the ability of AudioNodes to connect via their inputs and outputs and the channels inside these inputs/outputs.Web Audio API 可於 Web App 或網頁上操作並播放音訊檔案。

+

Web Audio API 是根據模組化路由 (Modular routing) 的概念所設計。所謂的模組化路由,即是以「音訊節點 (Audio nodes)執行基本的音訊作業節點又互相連接而構成「音訊路由圖 (Audio routing graphs)」。在同一環境 (Audio context) 內,又可支援數個音源與多樣的聲道配置。此模組化設計可提供更高的靈活度,並能建立複雜的音訊函式與動態效果。

+

音訊節點均透過其輸出與輸入而相互連結。各個輸入/輸出均具備數個聲道 (Channel),以構成特定的音訊配置。但目前已可支援單聲道、立體聲、四聲道、5.1 聲道等配置,並支援其他的離散配置。

+

音訊有多種來源。可能由特定的音訊節點 (如震盪器、自訂函式,甚或簡易的資料陣列) 直接在 JavaScript 中產生。音源除了可連至 HTML 媒體元素 (如 <video><audio>),亦可能來自於 WebRTCMediaStream (本端裝置的相機或遠方電腦)。

+

特定音訊事件發生的時間點,均達到極高的精確度與極低的潛時,因此亦可用以詳細定義鼓類機器或音序器 (Sequencer) 所需的事件。

+

Web Audio API 亦可控制音訊的空間定位 (Spatialized) 作業:透過 source-listener 模型架構的系統,進而控制所要使用的左右相位 (Panning聲音放置於左右喇叭之間形成的立體音場中,以產生出空間感) 模,進而自動處理因距離遠近所產生的衰減,或是由於音源/聽者移動所發生的都卜勒移頻 (Doppler shift)。

+

參考

+
+ +
+

線上教學

+ +

規格

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

瀏覽器相容性

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

 

diff --git a/files/zh-tw/web/api/web_video_text_tracks_format/index.html b/files/zh-tw/web/api/web_video_text_tracks_format/index.html new file mode 100644 index 0000000000..e565d2d129 --- /dev/null +++ b/files/zh-tw/web/api/web_video_text_tracks_format/index.html @@ -0,0 +1,691 @@ +--- +title: WebVTT +slug: Web/API/Web_Video_Text_Tracks_Format +translation_of: Web/API/WebVTT_API +--- +

WebVTT 是一種 UTF-8 編碼的文字檔案格式,可藉由 {{ HTMLElement("track") }} 元素顯示加註時間資訊之文字軌,其主要設計目的是為 {{ HTMLElement("video") }} 顯示字幕。

+ +

WebVTT 當中可以採用空白或分隔字元(tab)。

+ +

WebVTT 的 MIME Type 為 text/vtt

+ +

 

+ +

WebVTT 文本

+ +

WebVTT 檔的結構中,有兩項必備資訊、四項選用資訊。

+ + + +
範例 1 - 最簡單的 WEBVTT 檔
+ +
  WEBVTT
+
+
+ +
範例 2 - 很簡單的 WebVTT 檔
+ +
  WEBVTT - 這個檔案沒有時間節點
+
+
+ +
範例 3 - 常見的 WebVTT 例子
+ +
  WEBVTT - 這個檔案有時間節點
+
+  14
+  00:01:14.815 --> 00:01:18.114
+  - What?
+  - Where are we now?
+
+  15
+  00:01:18.171 --> 00:01:20.991
+  - This is big bat country.
+
+  16
+  00:01:21.058 --> 00:01:23.868
+  - [ Bats Screeching ]
+  - They won't get in your hair. They're after the bugs.
+
+ +

 

+ +

WebVTT 註解

+ +

Comments are an optional component that can be used to add information to a WebVTT file. Comments are intended for those reading the file and are not seen by users. Comments may contain newlines but it cannot contain a blank line, which is equivalent to two consecutive newlines. A blank line signifies the end of a comment.

+ +

註解中不能包含「-->」字串、「&」符號或「<」符號。如欲使用後兩者,可採跳脫字串「&amp;」或「&lt;」。此外雖規格上允許使用「>」字元,仍然建議跳脫為「&gt;」以避免混淆。

+ +

註解由三個部分組成:

+ + + +
範例 4 - 常見 WebVTT 範例
+ +
  NOTE 這行是註解
+
+ +
範例 5 - 多行註解
+ +
  NOTE
+  這也是註解,
+  只是拆成多行。
+
+  NOTE 當然也可以像這樣
+  來分行寫註解。
+
+ +
範例 6 - 常見註解使用方式
+ +
  WEBVTT - 翻譯我喜歡的影片字幕
+
+  NOTE
+  本字幕由 Kyle 翻譯,
+  希望可以讓我的朋友跟家人一同觀賞。
+
+  1
+  00:02:15.000 --> 00:02:20.000
+  - Ta en kopp varmt te.
+  - Det är inte varmt.
+
+  2
+  00:02:20.000 --> 00:02:25.000
+  - Har en kopp te.
+  - Det smakar som te.
+
+  NOTE This last line may not translate well.
+
+  3
+  00:02:25.000 --> 00:02:30.000
+  -Ta en kopp.
+
+ +

 

+ +

WebVTT 時間節點

+ +

時間節點(cue)是具備單一開始時間、結束時間、文字內容的字幕區段。 Example 6 consists of the header, a blank line, and then five cues separated by blank lines. 時間節點由五個部分組成:

+ + + +
範例7 - Example of a cue
+ +
1 - Title Crawl
+00:00:5.000 --> 00:00:10.000 line:0 position:20% size:60% align:start
+Some time ago in a place rather distant....
+ +

 

+ +

節點 ID

+ +

此 ID 代表時間節點的名稱,可以用以在腳本語言中參照某段特定時間節點。ID 中禁用換行字元,也不可以包括「-->」字串。ID 最後必須以一個換行字元作為結束。

+ +

雖然通常都用數字(1, 2, 3...)作為 ID,但規格上並不要求每個 ID 都是為一值。

+ +
範例 8 - 範例 7 中的時間節點 ID
+ +
1 - Title Crawl
+ +
範例 9 - ID 常見用法
+ +
WEBVTT
+
+1
+00:00:22.230 --> 00:00:24.606
+This is the first subtitle.
+
+2
+00:00:30.739 --> 00:00:34.074
+This is the second.
+
+3
+00:00:34.159 --> 00:00:35.743
+Third
+
+ +

 

+ +

時間資訊

+ +

時間資訊標注了此段節點的出現時機,其中包括開始時間與結束時間。結束時間必須比開始時間晚,而開始時間必須比先前所有的開始時間晚,或至少是同一時間。

+ +

不同時間節點可以設定為同時顯示,但若 WebVTT 檔案是用在 chapters({{ HTMLElement("track") }} 的 {{ htmlattrxref("kind") }} 設定為 chapters),則不允許兩段節點同時出現。

+ +

每項時間資訊都由五個部分組成:

+ + + +

時間的表示方式,可以是以下兩種:

+ + + +

其中的各元素說明如下:

+ + + +
Example 10 - Basic cue timing examples
+ +
00:22.230 --> 00:24.606
+00:30.739 --> 00:00:34.074
+00:00:34.159 --> 00:35.743
+00:00:35.827 --> 00:00:40.122
+ +
Example 11 - Overlapping cue timing examples
+ +
00:00:00.000 --> 00:00:10.000
+00:00:05.000 --> 00:01:00.000
+00:00:30.000 --> 00:00:50.000
+ +
Example 12 - Non-overlapping cue timing examples
+ +
00:00:00.000 --> 00:00:10.000
+00:00:10.000 --> 00:01:00.581
+00:01:00.581 --> 00:02:00.100
+00:02:01.000 --> 00:02:01.000
+ +

 

+ +

Cue Settings

+ +

Cue settings are optional components used to position where the cue payload text will be displayed over the video. This includes whether the text is displayed horizontally or vertically. There can be zero or more of them, and they can be used in any order so long as each setting is used no more than once.

+ +

The cue settings are added to the right of the cue timings. There must be one or more spaces between the cue timing and the first setting and between each setting. A setting's name and value are separated by a colon. The settings are case sensitive so use lower case as shown. There are five cue settings:

+ + + +
Example 13 - Cue setting examples
+ +

The first line demonstrates no settings. The second line might be used to overlay text on a sign or label. The third line might be used for a title. The last line might be used for an Asian language.

+ +
00:00:5.000 --> 00:00:10.000
+00:00:5.000 --> 00:00:10.000 line:63% position:72% align:start
+00:00:5.000 --> 00:00:10.000 line:0 position:20% size:60% align:start
+00:00:5.000 --> 00:00:10.000 vertical:rt line:-1 align:end
+
+ +

 

+ +

文字內容

+ +

The payload is where the main information or content is located. In normal usage the payload contains the subtitles to be displayed. The payload text may contain newlines but it cannot contain a blank line, which is equivalent to two consecutive newlines. A blank line signifies the end of a cue.

+ +

文字內容中不能包含「-->」字串、「&」符號或「<」符號。如欲使用後兩者,可採跳脫字串「&amp;」或「&lt;」。此外雖規格上允許使用「>」字元,仍然建議跳脫為「&gt;」以避免混淆。若您使用 WebVTT 檔作為後設資料,則可不管這些限制。

+ +

除了上述的三個跳脫字串外,還有其他四種跳脫字串,分列如下

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Table 6 - 跳脫字串
名稱字元跳脫字串
「與」&&amp;
小於<&lt;
大於>&gt;
左到右標記 &lrm;
右到左標記 &rlm;
不斷行空白 &nbsp;
+ +

 

+ +

文字內容中的標籤

+ +

有很多標籤(例如 <bold>)可以用在文字內容中,但若 {{ HTMLElement("track") }} 的 {{ htmlattrxref("kind") }} 設定為 chapters 時,其中所用的 WebVTT  檔案裡就不能使用標籤。

+ + + +

 

+ +

以下則需要開頭標籤與結束標籤(例如 <b>text</b>)。

+ + + +

 

+ +

瀏覽器支援

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
基本支援18 以上24 (預設為關閉)10 以上15.0 以上 7 以上
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IChrome for MobileOpera MobileSafari Mobile
基本支援4.4 以上       目前尚不支援         35.0 以上   21.0 以上7 以上
+ +

 

+ +

 

+
+ +

規格

+ + diff --git a/files/zh-tw/web/api/web_workers_api/index.html b/files/zh-tw/web/api/web_workers_api/index.html new file mode 100644 index 0000000000..ba18e065dd --- /dev/null +++ b/files/zh-tw/web/api/web_workers_api/index.html @@ -0,0 +1,215 @@ +--- +title: Web Workers API +slug: Web/API/Web_Workers_API +translation_of: Web/API/Web_Workers_API +--- +

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

+ +

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

+ +

Web Workers concepts and usage

+ +

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

+ +

You can run whatever code you like inside the worker thread, with some exceptions. For example, you can't directly manipulate the DOM from inside a worker, or use some default methods and properties of the {{domxref("window")}} object. But you can use a large number of items available under window, including WebSockets, and data storage mechanisms like IndexedDB and the Firefox OS-only Data Store API.  See Functions and classes available to workers for more details.

+ +

Data is sent between workers and the main thread via a system of messages — both sides send their messages using the postMessage() method, and respond to messages via the onmessage event handler (the message is contained within the {{event("Message")}} event's data attribute.) The data is copied rather than shared.

+ +

Workers may in turn spawn new workers, as long as those workers are hosted within the same origin as the parent page.  In addition, workers may use XMLHttpRequest for network I/O, with the exception that the responseXML and channel attributes on XMLHttpRequest always return null.

+ +

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

+ + + +
+

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

+
+ +

Web Worker interfaces

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

Examples

+ +

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

+ + + +

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

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#toc-workers')}}{{Spec2('HTML WHATWG')}}No change from {{SpecName("Web Workers")}}.
{{SpecName('Web Workers')}}{{Spec2('Web Workers')}}Initial definition.
+ +

Browser compatibility

+ +
{{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[1]
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support4.44{{CompatGeckoMobile(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] As webkitURL.

+ +

See also

+ + diff --git a/files/zh-tw/web/api/web_workers_api/using_web_workers/index.html b/files/zh-tw/web/api/web_workers_api/using_web_workers/index.html new file mode 100644 index 0000000000..82d484f6a2 --- /dev/null +++ b/files/zh-tw/web/api/web_workers_api/using_web_workers/index.html @@ -0,0 +1,791 @@ +--- +title: 使用 Web Workers +slug: Web/API/Web_Workers_API/Using_web_workers +translation_of: Web/API/Web_Workers_API/Using_web_workers +--- +
+

Web Workers 提供簡單的方法讓網頁在背景執行緒 (Thread) 中執行程式,而不干擾使用者介面運行另外,Worker也可以利用 XMLHttpRequest 執行輸出/輸入(但是responseXML 和channel這兩個屬性為null)一個worker可以藉由事件處理器來和 web worker 創造端互相傳送訊息,接下來本文會提供使用 web worker 的詳細說明。

+
+ +

Web Workers API

+ +

透過 worker 建構子 (如 {{domxref("Worker.Worker", "Worker()")}}) 便可以產生 worker 物件,並且執行 JavaScript 檔案。在 worker 中的 JavaScript 運行在不同於 {{domxref("window")}} 的執行緒環境,所以在 worker 中存取全域物件應該要透過 {{domxref("window.self","self")}},如果透過 {{domxref("window")}} 會導致錯誤發生。

+ +

Dedicated worker (專有 worker) 是一般 worker,只能被產生它的檔案存取,{{domxref("DedicatedWorkerGlobalScope")}} 物件代表其執行環境;而Shared worker (共享 worker) 則能夠被不同檔案存取,{{domxref("SharedWorkerGlobalScope")}}) 物件代表其執行環境。

+ +
+

Note: worker 其他文件說明請見 The Web Workers API landing page

+
+ +

基本上 worker 能夠執行任何事情,比如說 WebSocketsIndexedDB、和 Firefox OS 特有的 Data Store API ,然而直接存取 DOM 或是 {{domxref("window")}} 物件的一些方法和屬性則不被允許,更多細節請見 worker 可存取知函數和類別

+ +

主執行緒和 worker 執行緒之間用 postMessage() 方法發送訊息,然後透過 onmessage 事件接受訊息 (訊息存在 {{event("Message")}} 事件的 data 屬性之中),其中被傳送的資料並非共享而是複製一份後傳送。

+ +

worker 可以產生新 worker,只要新 worker 的來源 (origin) 和父頁面相同,也可以利用 XMLHttpRequest 執行輸出/輸入(但是responseXML 和channel這兩個屬性為null)。

+ +

Dedicated workers

+ +

dedicated worker 只能被產生它的檔案存取,下面我們先介紹簡單的 Basic dedicated worker example (run dedicated worker) 範例。這個範例會將兩個數字送入 worker 相乘,然後再於前端頁面顯示相乘結果。

+ +

偵測 Worker 功能

+ +

為了向下相容、避免錯誤,最好是確保 worker 存在後再取用之 (main.js):

+ +
if (window.Worker) {
+
+  ...
+
+}
+ +

產生 dedicated worker

+ +

只要呼叫 {{domxref("Worker.Worker", "Worker()")}} 建構子,傳入 JS 檔案的 URI,便可以生成一個 worker 執行緒 (main.js):

+ +
+
var myWorker = new Worker("worker.js");
+
+
+ +

和 dedicated worker 發送訊息

+ +

{{domxref("Worker.postMessage", "postMessage()")}} 方法以及 {{domxref("Worker.onmessage", "onmessage")}} 事件處理器就是和 worker 發送訊息的關鍵 (main.js):

+ +
first.onchange = function() {
+  myWorker.postMessage([first.value,second.value]);
+  console.log('Message posted to worker');
+}
+
+second.onchange = function() {
+  myWorker.postMessage([first.value,second.value]);
+  console.log('Message posted to worker');
+}
+ +

範例中有兩個 {{htmlelement("input")}} 元素,first 和 second,當元素值改變時,我們會利用 postMessage() 方法告訴 worker 改變的值 (這邊用陣列,也可以用其他類別)。

+ +

然後在 worker 裡我們從 onmessage 接收訊息 (worker.js):

+ +
onmessage = function(e) {
+  console.log('Message received from main script');
+  var workerResult = 'Result: ' + (e.data[0] * e.data[1]);
+  console.log('Posting message back to main script');
+  postMessage(workerResult);
+}
+ +

onmessage 事件物件的 data 屬性存有傳送過來的訊息資料,也就是 input 值;worker 收到後將傳過來的兩個值相乘,再 postMessage 傳回去。

+ +

回到主執行,同樣透過 onmessage 事件,收到 worker 回傳還來的計算值 :

+ +
myWorker.onmessage = function(e) {
+  result.textContent = e.data;
+  console.log('Message received from worker');
+}
+ +

拿到存在事件 data 中的計算值後,我們接著將值以 textContent 顯示出來。

+ +
+

Note : 建構 Worker 的URI必須遵從 same-origin policy。目前各家瀏覽器在這方面存有歧異,Gecko 10.0 {{geckoRelease("10.0")}} 以後允許 data URI 而 Internet Explorer 10 不允許 Blob URI。

+
+ +
Note: 在主執行緒中存取 onmessage 與 postMessage 需要主動掛在 worker 物件上,在 worker 執行緒則不用,這是因為 worker 執行緒的全域物件便是 worker 物件。
+ +
Note: 和 worker 傳送的資料並非共享而是複製一份後傳送,詳細請參照 {{anch("Transferring data to and from workers: further details")}}。
+ +

結束 worker

+ +

在主執行緒裡呼叫 {{domxref("Worker", "terminate")}} 就可結束 worker :

+ +
myWorker.terminate();
+ +

請注意不論 worker 正在執行的運算完成與否,一但呼叫後 worker 便會立刻被終止。

+ +

而在 worker 執行緒裡,worker 可以呼叫自己的 {{domxref("WorkerGlobalScope", "close")}} 方法來結束 :

+ +
close();
+ +

錯誤處理

+ +

當執行時期錯誤發生時,onerror 事件處理器會被呼叫,onerror事件處理器會收到一名為 error 的事件物件 (實作 ErrorEvent Interface),該事件不會 bubble 且可取消,如果要避免事件預設行為,可以呼叫 preventDefault()

+ +

以下三個部分是錯誤事件較關鍵的地方:

+ +
+
message
+
供人閱讀的錯誤訊息
+
filename
+
錯誤發生所在的檔案名稱
+
lineno
+
錯誤發生所在的行數
+
+ +

產生 subworker

+ +

worker 可以產生其他 worker (subworker),subworker 的來源也必須和主頁相同,另外,subworker 的 URI 的解析是相對於父 worker 的位置而非所在頁面,這項特色有助於追蹤 worker 間的相依性。

+ +

引入程式腳本與函式庫 (library)

+ +

Worker執行緒能存取一個全域函數 (global function), importScripts()。importScripts() 可以讓 worker 端引入相同網域的程式碼腳本與 libraries,importScripts()可接收零到數個要被輸入資源的URI,底下為幾個範例:

+ +
importScripts();                        /* imports nothing */
+importScripts('foo.js');                /* imports just "foo.js" */
+importScripts('foo.js', 'bar.js');      /* imports two scripts */
+
+ +

瀏覽器會載入並執行每個程式碼腳本,然後 worker 能夠存取程式碼腳本內定義的全域變數,若是腳本無法載入,會產生一個 NETWORK_ERROR,後續的程式碼不會被執行,但是先前執行過的程式碼或用 window.setTimeout() 延遲執行的程式碼依然有效,而 importScripts() 之後宣告的函數也一樣存在,因為這些程式碼總是在其他程式碼之前就解析過了。

+ +
Note: 雖然程式碼腳本的下載順序不一定,但執行順序會遵照傳入importScripts()的順序,這是同步完成的,importScripts()不會回傳直到所有的程式碼都下載並執行完。
+ +

Shared workers

+ +

shared worker 能夠被多個程式腳本存取,縱使跨越不同 window、iframe 或 worker。這邊的 Basic shared worker example (run shared worker) 範例和 dedicated worker 範例類似,但多了兩個可以讓多個檔案存取的函數:數字相乘以及數字平方

+ +

請注意 dedicated worker 與 shared worker 間的差異處,範例裡會有兩份 HTML 頁面,各自都利用同一個 worker 處理運算。

+ +
+

Note: 所有的瀏覽環境都必需共享相同的來源(相同protocol, host 和 port),shared worker 才能讓不同瀏覽環境存取。

+
+ +
+

Note: 在 Firefox, shared worker 無法在一般和隱私模式間共享 ({{bug(1177621)}})。

+
+ +

產生 shared worker

+ +

和 dedicated worker 做法差不多,只是用另一個 SharedWorker 建構子來產生  shared worker,見 index.htmlindex2.html:

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

相當不 一樣的是和 shared worker 溝通必須要透過 port 物件,其實 dedicated worker 也是如此,只不過一切是在背景後自動完成。

+ +

開啟 port 連線一是在 onmessage 事件下背景完成,二是藉由主動呼叫 start() 好開始傳送訊息。範例 multiply.js 以及 worker.js 因為註冊了 onmessage 事件,所以其實可以省略呼叫 start(),然而若是 message 事件是經由 addEventListener()註冊,那麼便需要呼叫 start() 了。

+ +

當使用 start() 開啟 port 連線,那麼雙向溝通便需要主執行緒和 worker 兩端都呼叫 start()。

+ +
myWorker.port.start();  // called in parent thread
+ +
port.start();  // called in worker thread, assuming the port variable references a port
+ +

和 shared worker 發送訊息

+ +

如同前面,現在可以呼叫 postMessage() 發送訊息,只不過這次需要透過 port 物件 (一樣請參考 multiply.jssquare.js):

+ +
squareNumber.onchange = function() {
+  myWorker.port.postMessage([squareNumber.value,squareNumber.value]);
+  console.log('Message posted to worker');
+}
+ +

worker 方面也增加了一些程式碼 (worker.js):

+ +
onconnect = function(e) {
+  var port = e.ports[0];
+  port.onmessage = function(e) {
+    var workerResult = 'Result: ' + (e.data[0] * e.data[1]);
+    port.postMessage(workerResult);
+  }
+  port.start();  // not necessary since onmessage event handler is being used
+}
+ +

首先,先監聽連線建立的 onconnect 事件,例如當主執行緒建立 onmessage 事件或呼叫 start()

+ +

然後從 onconnect 事件物件,我們可以取得 port 物件使用之。

+ +

取得 port 之後,我們註冊 port 上的 onmessage 事件,當有訊息進來便取回資料進行運算後回傳回去;註冊 onmessage 事件的同時也自動建立連線,所以說不需要呼叫start() 了。

+ +

最後在主執行緒端,我們同樣由 onmessage 事件取回回傳過來的訊息 (一樣請參考 multiply.jssquare.js):

+ +
myWorker.port.onmessage = function(e) {
+  result2.textContent = e.data[0];
+  console.log('Message received from worker');
+}
+ +

 

+ +

執行緒 (Thread) 安全

+ +

{{domxref("Worker")}} 會產生真正 OS 層級的執行緒,細心的開發者或許會擔心同步問題。

+ +

不過 worker 會十分注意和其他執行緒溝通的狀況,不會去存取非執行緒安全的元件,如 DOM ,而且資料的傳遞也都序列化 (serialized) ,所以說很難會發生同步問題。

+ +

和 workers 傳遞資料:更多細節

+ +

和 workers 傳遞的資料會先被複製一份,而非共享;經過序列化後 (serialized) 傳輸,然後在另一端反序列化 (de-serialized) 取出,大部份的瀏覽器都是以 結構化複製 (structured cloning) 實作這項特色.

+ +

下面的 emulateMessage() 會模擬和 worker 傳遞訊息時,複製資料的行為。

+ +
function emulateMessage (vVal) {
+    return eval("(" + JSON.stringify(vVal) + ")");
+}
+
+// Tests
+
+// test #1
+var example1 = new Number(3);
+console.log(typeof example1); // object
+console.log(typeof emulateMessage(example1)); // number
+
+// test #2
+var example2 = true;
+console.log(typeof example2); // boolean
+console.log(typeof emulateMessage(example2)); // boolean
+
+// test #3
+var example3 = new String("Hello World");
+console.log(typeof example3); // object
+console.log(typeof emulateMessage(example3)); // string
+
+// test #4
+var example4 = {
+    "name": "John Smith",
+    "age": 43
+};
+console.log(typeof example4); // object
+console.log(typeof emulateMessage(example4)); // object
+
+// test #5
+function Animal (sType, nAge) {
+    this.type = sType;
+    this.age = nAge;
+}
+var example5 = new Animal("Cat", 3);
+alert(example5.constructor); // Animal
+alert(emulateMessage(example5).constructor); // Object
+ +

所謂的訊息就是經過複製、非共享的資料,到這邊你應該已經知道 postMessage() 負責發送訊息,然後 message 事件 {{domxref("MessageEvent.data", "data")}} 的 attribute 則存有傳送的訊息資料。

+ +

example.html: (the main page):

+ +
var myWorker = new Worker("my_task.js");
+
+myWorker.onmessage = function (oEvent) {
+  console.log("Worker said : " + oEvent.data);
+};
+
+myWorker.postMessage("ali");
+ +

my_task.js (the worker):

+ +
postMessage("I\'m working before postMessage(\'ali\').");
+
+onmessage = function (oEvent) {
+  postMessage("Hi " + oEvent.data);
+};
+ +

結構化複製(structured cloning) 演算法支援 JSON 以及迴圈參照(circular references)。

+ +

資料傳遞範例

+ +

範例 1: 非同步 eval()

+ +

下面透過 data URLeval()示範如何在 worker 非同步執行允許的程式碼:

+ +
// Syntax: asyncEval(code[, listener])
+
+var asyncEval = (function () {
+  var aListeners = [], oParser = new Worker("data:text/javascript;charset=US-ASCII,onmessage%20%3D%20function%20%28oEvent%29%20%7B%0A%09postMessage%28%7B%0A%09%09%22id%22%3A%20oEvent.data.id%2C%0A%09%09%22evaluated%22%3A%20eval%28oEvent.data.code%29%0A%09%7D%29%3B%0A%7D");
+
+  oParser.onmessage = function (oEvent) {
+    if (aListeners[oEvent.data.id]) { aListeners[oEvent.data.id](oEvent.data.evaluated); }
+    delete aListeners[oEvent.data.id];
+  };
+
+  return function (sCode, fListener) {
+    aListeners.push(fListener || null);
+    oParser.postMessage({
+      "id": aListeners.length - 1,
+      "code": sCode
+    });
+  };
+})();
+ +

data URL 相當於網路請求,範例中的 data URL 會在 worker 執行下列程式碼回應訊息:

+ +
onmessage = function (oEvent) {
+  postMessage({
+    "id": oEvent.data.id,
+    "evaluated": eval(oEvent.data.code)
+  });
+}
+ +

應用範例:

+ +
// asynchronous alert message...
+asyncEval("3 + 2", function (sMessage) {
+    alert("3 + 2 = " + sMessage);
+});
+
+// asynchronous print message...
+asyncEval("\"Hello World!!!\"", function (sHTML) {
+    document.body.appendChild(document.createTextNode(sHTML));
+});
+
+// asynchronous void...
+asyncEval("(function () {\n\tvar oReq = new XMLHttpRequest();\n\toReq.open(\"get\", \"http://www.mozilla.org/\", false);\n\toReq.send(null);\n\treturn oReq.responseText;\n})()");
+ +

範例2: JSON 資料進階傳遞與呼叫系統

+ +

下面的範例系統適合需要在主頁面和 worker 傳遞複雜資料和呼叫多個函數的情境。

+ +

example.html (主頁面):

+ +
<!doctype html>
+<html>
+<head>
+<meta charset="UTF-8"  />
+<title>MDN Example - Queryable worker</title>
+<script type="text/javascript">
+  /*
+    QueryableWorker instances methods:
+     * sendQuery(queryable function name, argument to pass 1, argument to pass 2, etc. etc): calls a Worker's queryable function
+     * postMessage(string or JSON Data): see Worker.prototype.postMessage()
+     * terminate(): terminates the Worker
+     * addListener(name, function): adds a listener
+     * removeListener(name): removes a listener
+    QueryableWorker instances properties:
+     * defaultListener: the default listener executed only when the Worker calls the postMessage() function directly
+  */
+  function QueryableWorker (sURL, fDefListener, fOnError) {
+    var oInstance = this, oWorker = new Worker(sURL), oListeners = {};
+    this.defaultListener = fDefListener || function () {};
+    oWorker.onmessage = function (oEvent) {
+      if (oEvent.data instanceof Object && oEvent.data.hasOwnProperty("vo42t30") && oEvent.data.hasOwnProperty("rnb93qh")) {
+        oListeners[oEvent.data.vo42t30].apply(oInstance, oEvent.data.rnb93qh);
+      } else {
+        this.defaultListener.call(oInstance, oEvent.data);
+      }
+    };
+    if (fOnError) { oWorker.onerror = fOnError; }
+    this.sendQuery = function (/* queryable function name, argument to pass 1, argument to pass 2, etc. etc */) {
+      if (arguments.length < 1) { throw new TypeError("QueryableWorker.sendQuery - not enough arguments"); return; }
+      oWorker.postMessage({ "bk4e1h0": arguments[0], "ktp3fm1": Array.prototype.slice.call(arguments, 1) });
+    };
+    this.postMessage = function (vMsg) {
+      //I just think there is no need to use call() method
+      //how about just oWorker.postMessage(vMsg);
+      //the same situation with terminate
+      //well,just a little faster,no search up the prototye chain
+      Worker.prototype.postMessage.call(oWorker, vMsg);
+    };
+    this.terminate = function () {
+      Worker.prototype.terminate.call(oWorker);
+    };
+    this.addListener = function (sName, fListener) {
+      oListeners[sName] = fListener;
+    };
+    this.removeListener = function (sName) {
+      delete oListeners[sName];
+    };
+  };
+
+  // your custom "queryable" worker
+  var oMyTask = new QueryableWorker("my_task.js" /* , yourDefaultMessageListenerHere [optional], yourErrorListenerHere [optional] */);
+
+  // your custom "listeners"
+
+  oMyTask.addListener("printSomething", function (nResult) {
+    document.getElementById("firstLink").parentNode.appendChild(document.createTextNode(" The difference is " + nResult + "!"));
+  });
+
+  oMyTask.addListener("alertSomething", function (nDeltaT, sUnit) {
+    alert("Worker waited for " + nDeltaT + " " + sUnit + " :-)");
+  });
+</script>
+</head>
+<body>
+  <ul>
+    <li><a id="firstLink" href="javascript:oMyTask.sendQuery('getDifference', 5, 3);">What is the difference between 5 and 3?</a></li>
+    <li><a href="javascript:oMyTask.sendQuery('waitSomething');">Wait 3 seconds</a></li>
+    <li><a href="javascript:oMyTask.terminate();">terminate() the Worker</a></li>
+  </ul>
+</body>
+</html>
+ +

my_task.js (worker):

+ +
// your custom PRIVATE functions
+
+function myPrivateFunc1 () {
+  // do something
+}
+
+function myPrivateFunc2 () {
+  // do something
+}
+
+// etc. etc.
+
+// your custom PUBLIC functions (i.e. queryable from the main page)
+
+var queryableFunctions = {
+  // example #1: get the difference between two numbers:
+  getDifference: function (nMinuend, nSubtrahend) {
+      reply("printSomething", nMinuend - nSubtrahend);
+  },
+  // example #2: wait three seconds
+  waitSomething: function () {
+      setTimeout(function() { reply("alertSomething", 3, "seconds"); }, 3000);
+  }
+};
+
+// system functions
+
+function defaultQuery (vMsg) {
+  // your default PUBLIC function executed only when main page calls the queryableWorker.postMessage() method directly
+  // do something
+}
+
+function reply (/* listener name, argument to pass 1, argument to pass 2, etc. etc */) {
+  if (arguments.length < 1) { throw new TypeError("reply - not enough arguments"); return; }
+  postMessage({ "vo42t30": arguments[0], "rnb93qh": Array.prototype.slice.call(arguments, 1) });
+}
+
+onmessage = function (oEvent) {
+  if (oEvent.data instanceof Object && oEvent.data.hasOwnProperty("bk4e1h0") && oEvent.data.hasOwnProperty("ktp3fm1")) {
+    queryableFunctions[oEvent.data.bk4e1h0].apply(self, oEvent.data.ktp3fm1);
+  } else {
+    defaultQuery(oEvent.data);
+  }
+};
+
+ +

移轉資料所有權 - 可移轉物件 (transferable objects)

+ +

Google Chrome 17+ 以及 Firefox 18+ 能夠和 worker 高效能地傳送另外一種特定型態物件 (可移轉物件, transferable objects,這種物件實作了 {{domxref("Transferable")}} 介面),可移轉物件當被傳送到另一端時並不需要複製,因此可以大大提升傳送大型資料物件的效能;這好比像是 C/C++ 的 pass-by-reference,但是不同的是,一旦移轉後原先的環境便失去了持有資料,例如當主頁面傳送 {{domxref("ArrayBuffer")}} 後,主頁面便不再能夠使用這筆資料物件了,這筆資料物件的存取連結已經靜靜地移轉到 worker 端了。

+ +
// Create a 32MB "file" and fill it.
+var uInt8Array = new Uint8Array(1024*1024*32); // 32MB
+for (var i = 0; i < uInt8Array.length; ++i) {
+  uInt8Array[i] = i;
+}
+
+worker.postMessage(uInt8Array.buffer, [uInt8Array.buffer]);
+
+ +
+

Note: 關於更多可移轉物件的資訊, 效能和功能偵測,請參考 HTML5 Rocks 上 Transferable Objects: Lightning Fast! 一文。

+
+ +

Embedded workers

+ +

不像 {{HTMLElement("script")}},並沒有一套正式標準的方法將 worker 的程式碼嵌入到頁面之中,不過沒有 src 屬性而且 mime-type 不屬於可執行程式碼的 {{HTMLElement("script")}} 元素會被視為 javascript 可以取用的資料區塊(data block),資料區塊是一項 HTML5 可用於攜帶文字資料的特色功能,利用資料區塊我們就有辦法嵌入 worker 的程式碼到頁面中:

+ +
<!DOCTYPE html>
+<html>
+<head>
+<meta charset="UTF-8" />
+<title>MDN Example - Embedded worker</title>
+<script type="text/js-worker">
+  // This script WON'T be parsed by JS engines because its mime-type is text/js-worker.
+  var myVar = "Hello World!";
+  // Rest of your worker code goes here.
+</script>
+<script type="text/javascript">
+  // This script WILL be parsed by JS engines because its mime-type is text/javascript.
+  function pageLog (sMsg) {
+    // Use a fragment: browser will only render/reflow once.
+    var oFragm = document.createDocumentFragment();
+    oFragm.appendChild(document.createTextNode(sMsg));
+    oFragm.appendChild(document.createElement("br"));
+    document.querySelector("#logDisplay").appendChild(oFragm);
+  }
+</script>
+<script type="text/js-worker">
+  // This script WON'T be parsed by JS engines because its mime-type is text/js-worker.
+  onmessage = function (oEvent) {
+    postMessage(myVar);
+  };
+  // Rest of your worker code goes here.
+</script>
+<script type="text/javascript">
+  // This script WILL be parsed by JS engines because its mime-type is text/javascript.
+
+  // In the past...:
+  // blob builder existed
+  // ...but now we use Blob...:
+  var blob = new Blob(Array.prototype.map.call(document.querySelectorAll("script[type=\"text\/js-worker\"]"), function (oScript) { return oScript.textContent; }),{type: "text/javascript"});
+
+  // Creating a new document.worker property containing all our "text/js-worker" scripts.
+  document.worker = new Worker(window.URL.createObjectURL(blob));
+
+  document.worker.onmessage = function (oEvent) {
+    pageLog("Received: " + oEvent.data);
+  };
+
+  // Start the worker.
+  window.onload = function() { document.worker.postMessage(""); };
+</script>
+</head>
+<body><div id="logDisplay"></div></body>
+</html>
+ +

Embedded worker 在 document.worker 之中。

+ +

其他範例

+ +

下面介紹其他使用 worker 的範例。

+ +

在背景中執行運算

+ +

worker 主要的用處在避免重度 CPU 運算的任務阻礙到 UI 執行緒運行;這邊我們用 worker 來跑 Fibonacci 數列運算。

+ +

JavaScript

+ +

fibonacci.js 中的程式碼會被另一份 HTML 引用。

+ +
var results = [];
+
+function resultReceiver(event) {
+  results.push(parseInt(event.data));
+  if (results.length == 2) {
+    postMessage(results[0] + results[1]);
+  }
+}
+
+function errorReceiver(event) {
+  throw event.data;
+}
+
+onmessage = function(event) {
+  var n = parseInt(event.data);
+
+  if (n == 0 || n == 1) {
+    postMessage(n);
+    return;
+  }
+
+  for (var i = 1; i <= 2; i++) {
+    var worker = new Worker("fibonacci.js");
+    worker.onmessage = resultReceiver;
+    worker.onerror = errorReceiver;
+    worker.postMessage(n - i);
+  }
+ };
+ +

worker 程式碼中註冊了一個 onmessage 事件處理器用來接收另一端 postMessage 過來的訊息 (請注意這並非定義一個全域變數或函數,var onmessagefunction onmessage 會定義全域變數,但不會註冊事件處理器),然後開始進行遞迴運算。

+ +

HTML

+ +
<!DOCTYPE html>
+<html>
+  <head>
+    <meta charset="UTF-8"  />
+    <title>Test threads fibonacci</title>
+  </head>
+  <body>
+
+  <div id="result"></div>
+
+  <script language="javascript">
+
+    var worker = new Worker("fibonacci.js");
+
+    worker.onmessage = function(event) {
+      document.getElementById("result").textContent = event.data;
+      dump("Got: " + event.data + "\n");
+    };
+
+    worker.onerror = function(error) {
+      dump("Worker error: " + error.message + "\n");
+      throw error;
+    };
+
+    worker.postMessage("5");
+
+  </script>
+  </body>
+</html>
+
+ +

onmessage 事件處理器會接收 worker 回傳的運算結果,然後顯示在頁面上,如果有問題, onerror 事件處理器會 輸出 錯誤訊息。

+ +

和 worker 溝通則是利用 postMessage。

+ +

範例測試

+ +

在背景中執行 web I/O

+ +

範例請見 Using workers in extensions 。

+ +

分割任務到多個 workers

+ +

基於多核 cpu 的普及,分割複雜任務到多個 workers 將可能有助於利用多核心 cpu 的優勢。

+ +

其他類型的 worker

+ +

除了 dedicated 和 shared web workers,還有其他種類:

+ + + +

Worker 可存取之函數與介面

+ +

大多數 Javascript 的功能 workre 皆可以使用,包含:

+ + + +

worker 無法操作主頁面的物件與 DOM,如有相關需求,必須要間接透過 {{domxref("DedicatedWorkerGlobalScope.postMessage")}} 通知主頁面,讓主頁面執行需求。

+ +
+

Note: 所有 worker 可存取功能一覽表,請見 Functions and interfaces available to workers.

+
+ +

標準規範

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#toc-workers')}}{{Spec2('HTML WHATWG')}}No change from {{SpecName("Web Workers")}}.
{{SpecName('Web Workers')}}{{Spec2('Web Workers')}}Initial definition.
+ +

瀏覽器相容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support4[1]{{CompatGeckoDesktop("1.9.1")}}10.010.6[1]4[2]
Shared workers4[1]{{CompatGeckoDesktop(29)}}{{CompatNo}}10.64[2]
Passing data using structured cloning13{{CompatGeckoDesktop(8)}}10.011.56
Passing data using transferable objects17 {{property_prefix("webkit")}}
+ 21
{{CompatGeckoDesktop(18)}}{{CompatNo}}156
Global {{domxref("window.URL", "URL")}}10[3]
+ 23
{{CompatGeckoDesktop(21)}}11156[3]
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome MobileFirefox Mobile (Gecko)Firefox OS (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support4.44[1]3.51.0.110.011.5[1]5.1[2]
Shared workers{{CompatNo}}4[1]81.0.1{{CompatNo}}{{CompatNo}}{{CompatNo}}
Passing data using structured cloning{{CompatNo}}481.0.1{{CompatNo}}{{CompatNo}}{{CompatNo}}
Passing data using transferable objects{{CompatNo}}{{CompatNo}}181.0.1{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] Chrome 和 Opera 會丟出錯誤:"Uncaught SecurityError: Failed to construct 'Worker': Script at 'file:///Path/to/worker.js' cannot be accessed from origin 'null'.",當從 local 端而非網域執行 worker。

+ +

[2] Safari 7.1.2 可以從 worker 呼叫 console.log,但並不會任何效果,而更早的版本則是不允許呼叫 console.log。

+ +

[3] 會有前綴 webkitURL.

+ +

延伸閱讀

+ + diff --git a/files/zh-tw/web/api/webgl_api/index.html b/files/zh-tw/web/api/webgl_api/index.html new file mode 100644 index 0000000000..561594474c --- /dev/null +++ b/files/zh-tw/web/api/webgl_api/index.html @@ -0,0 +1,255 @@ +--- +title: WebGL +slug: Web/API/WebGL_API +tags: + - WebGL +translation_of: Web/API/WebGL_API +--- +

{{WebGLSidebar}}

+ +

WebGL (Web Graphics Library) 是一個透過瀏覽器渲染3D及2D圖像的 JavaScript API ,且不需要安裝任何插件。 WebGL 透過與OpenGL ES 2.0緊密連結的API,將3D圖像帶入HTML5中,並可透過canvas元素呈現於瀏覽器中

+ +

Support for WebGL is present in Firefox 4+, Google Chrome 9+, Opera 12+, Safari 5.1+ 以及 Internet Explorer 11+; 然而,使用者的 GPU 也必須支援。

+ +
+
+

Development topics

+ +
+
從 WebGL 開始吧
+
如何設立一個 WebGL 環境。
+
增加 2D 的東西到 WebGL 環境
+
如何使用 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.
+
WebGL best practices
+
Tips and suggestions to improve your WebGL content.
+
Cross-domain textures
+
Information about loading textures from domains other than the one from which your content was loaded.
+
Using extensions
+
How to use extensions that are available in WebGL.
+
+
+ +
+ + +
+
WebGL Specification
+
The WebGL specification.
+
Khronos WebGL site
+
The main web site for WebGL at the Khronos Group.
+
Learning WebGL
+
A site with tutorials on how to use WebGL.
+
WebGL Fundamentals
+
A basic tutorial with fundamentals of WebGL.
+
WebGL Matrices
+
An introduction to matrices' use in 2D WebGL. This series also goes on to explain the math behind perspective 3D.
+
The WebGL Cookbook
+
A web site with handy recipes for writing WebGL code.
+
Planet WebGL
+
A feed aggregator for people involved in the WebGL community.
+
ewgl-matrices
+
A blazing fast matrix library for WebGL
+
glMatrix
+
JavaScript Matrix and Vector library for High Performance WebGL apps
+
mjs
+
A JavaScript vector and matrix math library, optimized for WebGL usage.
+
Sylvester
+
An open source library for manipulating vectors and matrices. Not optimized for WebGL but extremely robust.
+
WebGL playground
+
An online tool for creating and sharing WebGL projects. Good for quick prototyping and experimenting.
+
WebGL Academy
+
An HTML/Javascript editor with tutorials to learn basics of webgl programming.
+
 
+
+
+
+ +

瀏覽器相容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureFirefox (Gecko)ChromeInternet ExplorerOperaSafari
基本支援{{CompatGeckoDesktop("2.0")}}91112 (experiment)5.1 (experiment)
OES_texture_float{{CompatGeckoDesktop("6.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_standard_derivatives{{CompatGeckoDesktop("10.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_texture_filter_anisotropic{{CompatGeckoDesktop("13.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_s3tc{{CompatGeckoDesktop("15.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
drawingBufferWidth and drawingBufferHeight attributes{{CompatGeckoDesktop("9.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureFirefox Mobile (Gecko)Chrome for AndroidIE MobileOpera MobileSafari Mobile
Basic support425 (experiment){{CompatNo}}12 (experiment){{CompatNo}}
drawingBufferWidth and drawingBufferHeight attributes{{CompatGeckoMobile("9.0")}}25{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_texture_float{{CompatGeckoMobile("6.0")}}25{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_standard_derivatives{{CompatGeckoMobile("10.0")}}25{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
EXT_texture_filter_anisotropic{{CompatGeckoMobile("13.0")}}25{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_element_index_uint{{CompatUnknown}}25{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
OES_vertex_array_object{{CompatUnknown}}25{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBGL_compressed_texture_s3tc{{CompatGeckoMobile("15.0")}}25
+ prefixed with WEBKIT_
{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
WEBKIT_EXT_texture_filter_nisotropic{{CompatNo}}25{{CompatNo}}{{CompatNo}}{{CompatUnknown}}
+
+ +

相容性小記

+ +

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

+ +

Gecko 小記

+ +

WebGL debugging and testing

+ +

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

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

你也可以看看

+ +

Raw WebGL: a talk by Nick Desaulniers:

+ +

{{EmbedYouTube("H4c8t6myAWU")}}

diff --git a/files/zh-tw/web/api/webgl_api/tutorial/adding_2d_content_to_a_webgl_context/index.html b/files/zh-tw/web/api/webgl_api/tutorial/adding_2d_content_to_a_webgl_context/index.html new file mode 100644 index 0000000000..45de8b801f --- /dev/null +++ b/files/zh-tw/web/api/webgl_api/tutorial/adding_2d_content_to_a_webgl_context/index.html @@ -0,0 +1,280 @@ +--- +title: 增加一個 2D 物件到 WebGL 環境 +slug: Web/API/WebGL_API/Tutorial/Adding_2D_content_to_a_WebGL_context +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")}}
+ +

當你建立了WebGL的context後,便可開始渲染。最簡單的例子就是加入一個普通的正方形。接下來,我們會介紹如何畫一個正方形。

+ +

畫場景

+ +

首先我們需要知道雖然這個範例只是要畫一個正方形,但我們還是在3D的空間裡作圖。基本上,我們就是畫一個正方形並把它放在相機前面,使正方形與使用者的視角垂直。我們要定義一個 shader,透過它來渲染我們的物件。接下來,我們會展示如何在螢幕前顯示一個正方形。

+ +

Shader

+ +

WebGL Shader使用 OpenGL ES Shading Language。 這邊不討論 shader 的細節的,但簡而言之,我們需要定義兩個shader (GPU上可執行的函數): vertex shader 和 fragment shader。這兩個 shader 會以字串的形式傳入WebGL,編譯後在GPU上執行。

+ +

Vertex shader

+ +

Vertex shader是用來定義一個變數 gl_Position 的值來控制畫布空間的值(-1到+1),下面的範例,我們設了一個變數aVertexPosition用來記錄 vertex 的位置。接下來我們將該位置乘上兩個4x4的矩陣(uProjectionMatrixuModelMatrix),並將結果設定為 gl_Position 的值。如果想要了解更多關於 Projection 和其他矩陣可以參閱這篇文件

+ +
  // Vertex shader program
+
+  const vsSource = `
+    attribute vec4 aVertexPosition;
+
+    uniform mat4 uModelViewMatrix;
+    uniform mat4 uProjectionMatrix;
+
+    void main() {
+      gl_Position = uProjectionMatrix * uModelViewMatrix * aVertexPosition;
+    }
+  `;
+
+ +

Fragment shader

+ +

每次 vertex shader 給 gl_Position 1到3個值的時候,它會分別畫出點、線、三角形。畫圖的時候,會呼叫 fragment shader 來詢問每個 pixel 的顏色。在這個範例中,我們對於每次詢問都回傳白色。

+ +

gl_FragColor 是GL預設的變數用來定義每個 fragment 的顏色,透過設定該變數的值來定義每個 pixel 的顏色,如下:

+ +
  const fsSource = `
+    void main() {
+      gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);
+    }
+  `;
+
+ +

初始化 shader

+ +

現在我們已經定義了兩個 shader ,我們接下來要將它們傳入WebGL,編譯並連結。下面的程式碼呼叫了 loadShader 來建立兩個shader。接下來,我們要新增一個程式,並將 shader 加入該程式,並將程式連結起來。如果編譯或連接失敗,程式碼會顯示錯誤訊息。

+ +

 

+ +
//
+// 初始化 shader 來告知WebGL怎麼畫
+//
+function initShaderProgram(gl, vsSource, fsSource) {
+  const vertexShader = loadShader(gl, gl.VERTEX_SHADER, vsSource);
+  const fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, fsSource);
+
+  // 建立 shader 程式
+
+  const shaderProgram = gl.createProgram();
+  gl.attachShader(shaderProgram, vertexShader);
+  gl.attachShader(shaderProgram, fragmentShader);
+  gl.linkProgram(shaderProgram);
+
+  // 錯誤處理
+
+  if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
+    alert('Unable to initialize the shader program: ' + gl.getProgramInfoLog(shaderProgram));
+    return null;
+  }
+
+  return shaderProgram;
+}
+
+//
+// creates a shader of the given type, uploads the source and
+// compiles it.
+//
+function loadShader(gl, type, source) {
+  const shader = gl.createShader(type);
+
+  // Send the source to the shader object
+
+  gl.shaderSource(shader, source);
+
+  // Compile the shader program
+
+  gl.compileShader(shader);
+
+  // See if it compiled successfully
+
+  if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
+    alert('An error occurred compiling the shaders: ' + gl.getShaderInfoLog(shader));
+    gl.deleteShader(shader);
+    return null;
+  }
+
+  return shader;
+}
+
+ +

 

+ +

我們可以透過呼叫 initShaderProgram 來建立 shader 程式

+ +
  const shaderProgram = initShaderProgram(gl, vsSource, fsSource);
+
+ +

接下來我們需要找到 WebGL 生成出的位置。這個例子中我們有一個 attribute、兩個 uniform。 Attributes 從 buffer 獲得值。每次迭代時,vertex shader 從 buffer 得到下一個值並傳入到 attribute。 Uniform 則像是 Javascript 的全域變數。每次迭代,他們的值不會改變。為了之後方便,我們將 shader 程式與 attribute 和 uniform 存放在同一個物件中。

+ +
  const programInfo = {
+    program: shaderProgram,
+    attribLocations: {
+      vertexPosition: gl.getAttribLocation(shaderProgram, 'aVertexPosition'),
+    },
+    uniformLocations: {
+      projectionMatrix: gl.getUniformLocation(shaderProgram, 'uProjectionMatrix'),
+      modelViewMatrix: gl.getUniformLocation(shaderProgram, 'uModelViewMatrix'),
+    },
+  };
+
+ +

建立正方形平面

+ +

在我們渲染前,我們要建立一個 buffer 用來儲存頂點的座標。在此我們宣告一個函數 initBuffers() ,隨著之後建立更多複雜的物件,這個動作會重複見到很多次。

+ +
function initBuffers(gl) {
+
+  // 建立一個 buffer 來儲存正方形的座標
+
+  const positionBuffer = gl.createBuffer();
+
+  // Select the positionBuffer as the one to apply buffer
+  // operations to from here out.
+
+  gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
+
+  // Now create an array of positions for the square.
+
+  const positions = [
+     1.0,  1.0,
+    -1.0,  1.0,
+     1.0, -1.0,
+    -1.0, -1.0,
+  ];
+
+  // Now pass the list of positions into WebGL to build the
+  // shape. We do this by creating a Float32Array from the
+  // JavaScript array, then use it to fill the current buffer.
+
+  gl.bufferData(gl.ARRAY_BUFFER,
+                new Float32Array(positions),
+                gl.STATIC_DRAW);
+
+  return {
+    position: positionBuffer,
+  };
+}
+
+ +

這個步驟非常簡單,一開始呼叫gl物件的函數 {{domxref("WebGLRenderingContext.createBuffer()", "createBuffer()")}} 來產生一個儲存座標的 buffer,並將將該 buffer 綁定 WebGL 的 context。

+ +

完成後,我們宣告一個陣列來儲存正方形平面各頂點的座標,並轉型為浮點數陣列並用{{domxref("WebGLRenderingContext.bufferData()", "bufferData()")}}函數傳入 gl 物件。

+ +

渲染場景

+ +

Shader 建立好了、位置也確定好了、正方形平面頂點的位置也已經放到 buffer後,我們就可以實際來渲染場景了。因為這個例子沒有任何的動畫,drawScene()函數非常單純。

+ +
function drawScene(gl, programInfo, buffers) {
+  gl.clearColor(0.0, 0.0, 0.0, 1.0);  // 設定為全黑
+  gl.clearDepth(1.0);                 // 清除所有東西
+  gl.enable(gl.DEPTH_TEST);           // Enable 深度測試
+  gl.depthFunc(gl.LEQUAL);            // Near things obscure far things
+
+  // 開始前先初始化畫布
+
+  gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
+
+  // Create a perspective matrix, a special matrix that is
+  // used to simulate the distortion of perspective in a camera.
+  // Our field of view is 45 degrees, with a width/height
+  // ratio that matches the display size of the canvas
+  // and we only want to see objects between 0.1 units
+  // and 100 units away from the camera.
+
+  const fieldOfView = 45 * Math.PI / 180;   // in radians
+  const aspect = gl.canvas.clientWidth / gl.canvas.clientHeight;
+  const zNear = 0.1;
+  const zFar = 100.0;
+  const projectionMatrix = mat4.create();
+
+  // note: glmatrix.js always has the first argument
+  // as the destination to receive the result.
+  mat4.perspective(projectionMatrix,
+                   fieldOfView,
+                   aspect,
+                   zNear,
+                   zFar);
+
+  // Set the drawing position to the "identity" point, which is
+  // the center of the scene.
+  const modelViewMatrix = mat4.create();
+
+  // Now move the drawing position a bit to where we want to
+  // start drawing the square.
+
+  mat4.translate(modelViewMatrix,     // destination matrix
+                 modelViewMatrix,     // matrix to translate
+                 [-0.0, 0.0, -6.0]);  // amount to translate
+
+  // Tell WebGL how to pull out the positions from the position
+  // buffer into the vertexPosition attribute.
+  {
+    const numComponents = 2;  // pull out 2 values per iteration
+    const type = gl.FLOAT;    // the data in the buffer is 32bit floats
+    const normalize = false;  // don't normalize
+    const stride = 0;         // how many bytes to get from one set of values to the next
+                              // 0 = use type and numComponents above
+    const offset = 0;         // how many bytes inside the buffer to start from
+    gl.bindBuffer(gl.ARRAY_BUFFER, buffers.position);
+    gl.vertexAttribPointer(
+        programInfo.attribLocations.vertexPosition,
+        numComponents,
+        type,
+        normalize,
+        stride,
+        offset);
+    gl.enableVertexAttribArray(
+        programInfo.attribLocations.vertexPosition);
+  }
+
+  // Tell WebGL to use our program when drawing
+
+  gl.useProgram(programInfo.program);
+
+  // Set the shader uniforms
+
+  gl.uniformMatrix4fv(
+      programInfo.uniformLocations.projectionMatrix,
+      false,
+      projectionMatrix);
+  gl.uniformMatrix4fv(
+      programInfo.uniformLocations.modelViewMatrix,
+      false,
+      modelViewMatrix);
+
+  {
+    const offset = 0;
+    const vertexCount = 4;
+    gl.drawArrays(gl.TRIANGLE_STRIP, offset, vertexCount);
+  }
+}
+
+
+ +

第一步,我們先將畫布背景設定為黑色,並設定相機的視角。我們將角度設為45°,並設定成與畫布的長寬比相同。另外我們指定我們只要渲染離相機 0.1 ~ 100 單位遠的物件。

+ +

接下來,我們讀入正方形的位置,並把它擺在離相機6單位遠的位置。然後我們將正方形頂點的 buffer 綁定到 gl 上。最後我們呼叫{{domxref("WebGLRenderingContext.drawArrays()", "drawArrays()")}}函數來渲染物件。

+ +

{{EmbedGHLiveSample('webgl-examples/tutorial/sample2/index.html', 670, 510) }}

+ +

檢視完整程式碼 | 開啟新頁面來檢視結果

+ +

矩陣運算

+ +

矩陣的運算看起來很複雜,但其實一步一步運算其實不會那麼困難。大部分使用者不會寫自己的運算函數,多半是使用現成的矩陣函數庫,這個例子中我們用的是 glMatrix library

+ +

可參考以下資料

+ + + +

{{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/zh-tw/web/api/webgl_api/tutorial/animating_objects_with_webgl/index.html b/files/zh-tw/web/api/webgl_api/tutorial/animating_objects_with_webgl/index.html new file mode 100644 index 0000000000..cea74d65cf --- /dev/null +++ b/files/zh-tw/web/api/webgl_api/tutorial/animating_objects_with_webgl/index.html @@ -0,0 +1,55 @@ +--- +title: 利用 WebGL 產生動畫 +slug: Web/API/WebGL_API/Tutorial/Animating_objects_with_WebGL +translation_of: Web/API/WebGL_API/Tutorial/Animating_objects_with_WebGL +--- +

{{WebGLSidebar("Tutorial")}} {{PreviousNext("Web/API/WebGL_API/Tutorial/Using_shaders_to_apply_color_in_WebGL", "Web/API/WebGL_API/Tutorial/Creating_3D_objects_using_WebGL") }}

+ +

這個章節中,我們將示範如何旋轉之前的正方形平面。

+ +

旋轉正方形

+ +

首先我們需要宣告一個變數來追蹤現在正方形旋轉的角度:

+ +
var squareRotation = 0.0;
+
+ +

Now we need to update the drawScene() function to apply the current rotation to the square when drawing it. After translating to the initial drawing position for the square, we apply the rotation like this:

+ +
  mat4.rotate(modelViewMatrix,  // destination matrix
+              modelViewMatrix,  // matrix to rotate
+              squareRotation,   // amount to rotate in radians
+              [0, 0, 1]);       // axis to rotate around
+
+ +

This rotates the modelViewMatrix by the current value of squareRotation, around the Z axis.

+ +

To actually animate, we need to add code that changes the value of squareRotation over time. We can do that by creating a new variable to track the time at which we last animated (let's call it then), then adding the following code to the end of the main function

+ +
  var then = 0;
+
+  // Draw the scene repeatedly
+  function render(now) {
+    now *= 0.001;  // convert to seconds
+    const deltaTime = now - then;
+    then = now;
+
+    drawScene(gl, programInfo, buffers, deltaTime);
+
+    requestAnimationFrame(render);
+  }
+  requestAnimationFrame(render);
+
+ +

This code uses requestAnimationFrame to ask the browser call the function "render" each frame. requestAnimationFrame passes us the time in milliseconds since the page loaded. We convert that to seconds and then subtract it from the last time to compute deltaTime which is the number of second since the last frame was rendered. At the end of drawscene we add the code to update squareRotation.

+ +
  squareRotation += deltaTime;
+
+ +

This code uses the amount of time that's passed since the last time we updated the value of squareRotation to determine how far to rotate the square.

+ +

{{EmbedGHLiveSample('webgl-examples/tutorial/sample4/index.html', 670, 510) }}

+ +

View the complete code | Open this demo on a new page

+ +

{{PreviousNext("Web/API/WebGL_API/Tutorial/Using_shaders_to_apply_color_in_WebGL", "Web/API/WebGL_API/Tutorial/Creating_3D_objects_using_WebGL") }}

diff --git a/files/zh-tw/web/api/webgl_api/tutorial/getting_started_with_webgl/index.html b/files/zh-tw/web/api/webgl_api/tutorial/getting_started_with_webgl/index.html new file mode 100644 index 0000000000..ef5e910f93 --- /dev/null +++ b/files/zh-tw/web/api/webgl_api/tutorial/getting_started_with_webgl/index.html @@ -0,0 +1,73 @@ +--- +title: WebGL 入門 +slug: Web/API/WebGL_API/Tutorial/Getting_started_with_WebGL +tags: + - 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 讓網頁內容能藉由一種基於 OpenGL ES 2.0 的 API 的幫助,於支援此 API 的瀏覽器環境中,不需使用外掛程式就能在HTML的 canvas 元素中實現二維及三維渲染。 WebGL 程式包含了由 JavaSrcipt 及著色器(GLSL)撰寫的控制碼以及在電腦的圖形處理器( GPU )上執行的特效程式碼(著色器程式碼)。WebGL 元素可以加入其他 HTML 元素之中並與網頁或網頁背景的其他部分混合。

+ +

這篇文章將會向您介紹 WebGL 的基礎。這篇文章假設您已經對於三維圖學涉及的數學有所了解,並且它將不會被佯裝為三維圖學的教材。在我們的學習區域內有初學者指南讓你完成編程任務:Learn WebGL for 2D and 3D graphics.

+ +

在此教學文件中的程式碼範例都能在 webgl-examples GitHub repository 之中找到。

+ +

準備三維渲染

+ +

首先你需要一個 canvas 元素讓WebGL進行渲染。下面的 HTML 定義的 canvas 元素供後續的範例繪製。

+ +
<body>
+  <canvas id="glCanvas" width="640" height="480"></canvas>
+</body>
+ +

準備 WebGL背景資料

+ +
+

背景資料為Context翻譯而來

+
+ +

在下面的JavaScript 程式碼,當指令完成讀取後會執行 main() 函式。目的是為了設定 WebGL 背景資料並且開始渲染內容。

+ +
main();
+
+// 從這開始
+function main() {
+  const canvas = document.querySelector("#glCanvas");
+  // 初始化 GL context
+  const gl = canvas.getContext("webgl");
+
+  // 當 WebGL 有效才繼續執行
+  if (gl === null) {
+    alert("無法初始化 WebGL,您的瀏覽器不支援。");
+    return;
+  }
+
+  // 設定清除色彩為黑色,完全不透明
+  gl.clearColor(0.0, 0.0, 0.0, 1.0);
+  // 透過清除色來清除色彩緩衝區
+  gl.clear(gl.COLOR_BUFFER_BIT);
+}
+ +

在此我們做的第一件事是取得 canvas 元素的參考,並存入 canvas 變數中。

+ +

一旦我們取得了 canvas ,我們透過呼叫 getContext 並傳入 "webgl" 字串來取得 WebGLRenderingContext。若瀏覽器不支援 webgl getContext 會回傳 null 同時會顯示訊息給使用者並且離開。

+ +

如果成功初始化, gl 就會成為一個 WebGL背景資料的參考。在這裡我們設置清除色為黑色,並透過該色清除 context (用背景色重新繪製 canvas )。

+ +

至此,您已經有足夠初始化 WebGL 背景資料的程式碼,並且準備好了等待接收內容的容器。

+ +

{{EmbedGHLiveSample('webgl-examples/tutorial/sample1/index.html', 670, 510) }}

+ +

檢視完整程式碼 | 開啟新頁面來檢視結果

+ +

亦可參考

+ + + +

{{Next("Web/API/WebGL_API/Tutorial/Adding_2D_content_to_a_WebGL_context")}}

diff --git a/files/zh-tw/web/api/webgl_api/tutorial/index.html b/files/zh-tw/web/api/webgl_api/tutorial/index.html new file mode 100644 index 0000000000..549c3f40ba --- /dev/null +++ b/files/zh-tw/web/api/webgl_api/tutorial/index.html @@ -0,0 +1,41 @@ +--- +title: WebGL tutorial +slug: Web/API/WebGL_API/Tutorial +tags: + - TopicStub + - Tutorial + - WebGL +translation_of: Web/API/WebGL_API/Tutorial +--- +
{{WebGLSidebar}}
+ +
+

WebGL 讓網頁內容可以使用一個基於 OpenGL ES 2.0 的API以在HTML {{HTMLElement("canvas")}}中執行3D渲染,且瀏覽器無需使用任何plug-in。WebGL programs 由JavaScript撰寫的指令碼以及透過電腦的Graphics Processing Unit (GPU)上運行的特殊效果程式碼(shader code)組成。WebGL元件可與其他HTML元件混合,並與該頁的其他部分或該頁背景組合使用。 

+
+ +

本教學描述如何使用 <canvas> 元件描繪 WebGL 圖像/圖形, 從基礎開始。提供的範例將讓你對於可以用WebGL做到什麼有清楚的概念,並提供程式碼片段讓你可以著手建立自己的內容。

+ +

開始之前

+ +

使用<canvas> 元件不會非常困難,但你需要有對HTML 與 JavaScript 的基礎認識。<canvas> 元件跟WebGL在某些舊瀏覽器中不支援,但近來的每個主流瀏覽器都有支援。我們用 JavaScript context object 在canvas繪製圖形,這樣圖形就能動態(on the fly)產生。

+ +

教學文件

+ +
+
WebGL新手上路
+
如何建置 WebGL 環境
+
加入2D內容至WebGL環境
+
如何用 WebGL 渲染簡單平面的形狀
+
使用 shaders 在 WebGL 上色
+
示範如何使用 shaders 在圖形上上色
+
WebGL 產生動畫
+
示範如何旋轉與移動物件以製作簡單的動畫
+
建立三維物件
+
示範如何創造並讓 3D 物件(立方體)有動畫
+
在物件表面貼上材質
+
示範如何在物件的表面上貼上材質圖
+
模擬打光
+
如何在 WebGL 環境模擬打光效果
+
讓材質產生動畫
+
如何移動材質圖,在範例中是將 Ogg 影片 貼到一個旋轉中的立方體
+
diff --git a/files/zh-tw/web/api/webgl_api/tutorial/using_shaders_to_apply_color_in_webgl/index.html b/files/zh-tw/web/api/webgl_api/tutorial/using_shaders_to_apply_color_in_webgl/index.html new file mode 100644 index 0000000000..b234bd013e --- /dev/null +++ b/files/zh-tw/web/api/webgl_api/tutorial/using_shaders_to_apply_color_in_webgl/index.html @@ -0,0 +1,123 @@ +--- +title: 使用 shaders 在 WebGL 上色 +slug: Web/API/WebGL_API/Tutorial/Using_shaders_to_apply_color_in_WebGL +translation_of: Web/API/WebGL_API/Tutorial/Using_shaders_to_apply_color_in_WebGL +--- +

{{WebGLSidebar("Tutorial")}} {{PreviousNext("Web/API/WebGL_API/Tutorial/Adding_2D_content_to_a_WebGL_context", "Web/API/WebGL_API/Tutorial/Animating_objects_with_WebGL")}}

+ +

上一篇我們建立了一個正方形平面,接下來我們要透過修改 shakder 來加入顏色。

+ +

指定頂點顏色

+ +

WebGL中物件是由許多頂點來組成,每個頂點有自己的座標、顏色。其他像素的屬性(顏色、位置)預設是透過計算多頂點的內差值來得到的。之前的例子,vertex shader 並沒有指定頂點任何顏色。

+ +

In WebGL, objects are built using sets of vertices, each of which has a position and a color; by default, all other pixels' colors (and all its other attributes, including position) are computed using interpolation, automatically creating smooth gradients. Previously, our vertex shader didn't apply any specific colors to the vertices; between this and the fragment shader assigning the fixed color of white to each pixel, the entire square was rendered as solid white.

+ +

Let's say we want to render a gradient in which each corner of the square is a different color: red, blue, green, and white. The first thing to do is to establish these colors for the four vertices. To do this, we first need to create an array of vertex colors, then store it into a WebGL buffer; we'll do that by adding the following code to our initBuffers() function:

+ +
  const colors = [
+    1.0,  1.0,  1.0,  1.0,    // white
+    1.0,  0.0,  0.0,  1.0,    // red
+    0.0,  1.0,  0.0,  1.0,    // green
+    0.0,  0.0,  1.0,  1.0,    // blue
+  ];
+
+  const colorBuffer = gl.createBuffer();
+  gl.bindBuffer(gl.ARRAY_BUFFER, colorBuffer);
+  gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW);
+
+  return {
+    position: positionBuffer,
+    color: colorBuffer,
+  };
+}
+
+ +

這段程式碼一開始先宣告一個陣列來存放四個四維向量,分別為四個頂點的顏色。接下來,將陣列轉型為浮點數並存入一個新的 WebGL buffer 。

+ +

為了使用這些顏色,我們需要修改 vertex shader,讓他可以從 buffer 中取得正確的顏色。

+ +
  const vsSource = `
+    attribute vec4 aVertexPosition;
+    attribute vec4 aVertexColor;
+
+    uniform mat4 uModelViewMatrix;
+    uniform mat4 uProjectionMatrix;
+
+    varying lowp vec4 vColor;
+
+    void main(void) {
+      gl_Position = uProjectionMatrix * uModelViewMatrix * aVertexPosition;
+      vColor = aVertexColor;
+    }
+  `;
+
+ +

The key difference here is that for each vertex, we pass its color using a varying to the fragment shader.

+ +

替 fragment 上色

+ +

我們重新回顧一下,之前我們的 fragment shader 如下:

+ +
  const fsSource = `
+    void main() {
+      gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);
+    }
+  `;
+
+ +

為了要讓每個 pixel 使用內插的顏色,我們讓 gl_FragColor 取得 vColor的值。

+ +
  const fsSource = `
+    varying lowp vec4 vColor;
+
+    void main(void) {
+      gl_FragColor = vColor;
+    }
+  `;
+
+ +

這樣的改變可以使每個 fragment 得到利用相對位置內插法所產生顏色,而不是得到一個固定的值。

+ +

畫出顏色

+ +

接下來我們要

+ +

Next, it's necessary to add the code look up the attribute location for the colors and setup that attribute for the shader program:

+ +
  const programInfo = {
+    program: shaderProgram,
+    attribLocations: {
+      vertexPosition: gl.getAttribLocation(shaderProgram, 'aVertexPosition'),
+      vertexColor: gl.getAttribLocation(shaderProgram, 'aVertexColor'),
+    },
+    ...
+ +

Then, drawScene() can be revised to actually use these colors when drawing the square:

+ +
  // Tell WebGL how to pull out the colors from the color buffer
+  // into the vertexColor attribute.
+  {
+    const numComponents = 4;
+    const type = gl.FLOAT;
+    const normalize = false;
+    const stride = 0;
+    const offset = 0;
+    gl.bindBuffer(gl.ARRAY_BUFFER, buffers.color);
+    gl.vertexAttribPointer(
+        programInfo.attribLocations.vertexColor,
+        numComponents,
+        type,
+        normalize,
+        stride,
+        offset);
+    gl.enableVertexAttribArray(
+        programInfo.attribLocations.vertexColor);
+  }
+
+ +

{{EmbedGHLiveSample('webgl-examples/tutorial/sample3/index.html', 670, 510) }}

+ +

View the complete code | Open this demo on a new page

+ +

{{PreviousNext("Web/API/WebGL_API/Tutorial/Adding_2D_content_to_a_WebGL_context", "Web/API/WebGL_API/Tutorial/Animating_objects_with_WebGL")}}

diff --git a/files/zh-tw/web/api/webrtc_api/index.html b/files/zh-tw/web/api/webrtc_api/index.html new file mode 100644 index 0000000000..1731f23739 --- /dev/null +++ b/files/zh-tw/web/api/webrtc_api/index.html @@ -0,0 +1,193 @@ +--- +title: WebRTC API +slug: Web/API/WebRTC_API +translation_of: Web/API/WebRTC_API +--- +
{{APIRef("WebRTC")}}
+ +

WebRTC(網路即時通訊技術)是一個提供 Web 應用程式及網站進行錄影或隨選播放串流音訊與影像的技術,可以直接使用瀏覽器進行資料交換而無須透過中介服務。作為一個標準規格,WebRTC 可以提供任何瀏覽器在不需要安裝外掛程式或第三方軟體下,分享應用程式的資料和進行電話會議。

+ +

WebRTC 由數個相關而互相協作的API以及網路協定組成。

+ +

這裡的技術文件會幫助你了解 :

+ +

WebRTC的基本構成,如何設置並同時使用其資料與媒體傳輸連線,以及更多有關資訊。

+ +

WebRTC 概念與使用

+ +

WebRTC 有許多服務目的,基本涵括了媒體獲取與串流API,他們為網頁提供了強大的多媒體功能,包括: 音視訊會議,檔案傳輸,身分識別管理,以及提供以傳輸{{Glossary("DTMF")}}訊號來與現存電話系統交互的介面。

+ +

建立端點與端點間的連線完全不需要特定驅動程式抑或者第三方插件,在通常情況下也不需要任何中介伺服器

+ +

WebRTC serves multiple purposes, and overlaps substantially with the Media Capture and Streams API. Together, they provide powerful multimedia capabilities to the Web, including support for audio and video conferencing, file exchange, identity management, and interfacing with legacy telephone systems by sending {{Glossary("DTMF")}} signals. Connections between peers can be made without requiring any special drivers or plug-ins, and can often be made without any intermediary servers.

+ +

Connections between two peers are created using—and represented by—the {{domxref("RTCPeerConnection")}} interface. Once a connection has been established and opened, media streams ({{domxref("MediaStream")}}s) and/or data channels ({{domxref("RTCDataChannel")}}s) can be added to the connection.

+ +

Media streams can consist of any number of tracks of media information; tracks, which are represented by objects based on the {{domxref("MediaStreamTrack")}} interface, may contain one of a number of types of media data, including audio, video, and text (such as subtitles or even chapter names). Most streams consist of at least one audio track and likely also a video track, and can be used to send and receive both live media or stored media information (such as a streamed movie).

+ +

You can also use the connection between two peers to exchange arbitrary binary data using the {{domxref("RTCDataChannel")}} interface. This can be used for back-channel information, metadata exchange, game status packets, file transfers, or even as a primary channel for data transfer.

+ +

more details and links to relevant guides and tutorials needed

+ +

WebRTC interfaces

+ +

Because WebRTC provides interfaces that work together to accomplish a variety of tasks, we have divided up the interfaces in the list below by category. Please see the sidebar for an alphabetical list.

+ +

Connection setup and management

+ +

These interfaces are used to set up, open, and manage WebRTC connections.

+ +
+
{{domxref("RTCPeerConnection")}}
+
Represents a WebRTC connection between the local computer and a remote peer. It is used to handle efficient streaming of data between the two peers.
+
{{domxref("RTCDataChannel")}}
+
Represents a bi-directional data channel between two peers of a connection.
+
{{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.
+
+ +

教學

+ +
+
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.
+
一個簡單的 RTCDataChannel 範例
+
{{domxref("RTCDataChannel")}} 介面用於讓兩端點間建立起資料的通道,你可以利用通道來收發資料。這組 API 被設計成與 WebSocket API 相似,所以可以利用同樣的程式模型套用在這兩套 API 之上。
+
+ +

資源

+ +

Protocols

+ +

WebRTC-proper protocols

+ + + + + + + +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
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/zh-tw/web/api/webvr_api/index.html b/files/zh-tw/web/api/webvr_api/index.html new file mode 100644 index 0000000000..926a1c3b25 --- /dev/null +++ b/files/zh-tw/web/api/webvr_api/index.html @@ -0,0 +1,246 @@ +--- +title: WebVR API +slug: Web/API/WebVR_API +translation_of: Web/API/WebVR_API +--- +
{{SeeCompatTable}}{{APIRef("WebVR API")}}
+ +

WebVR 可以讓穿戴的VR裝置 (如頭戴裝置 Oculus Rift 或 HTC Vive) 與 web 應用程式結合。開發人員可以將VR裝置所提供的位置與動作資訊轉移到3D的場景中。利用 WebVR可以創造出很多有趣的應用程式: 包含虛擬導覽、互動訓練軟體等等。

+ +

用法與基本觀念

+ +

透過呼叫 {{domxref("Navigator.getVRDisplays()")}} 函數可以得到與電腦連接的VR裝置,每個裝置會回傳一個 {{domxref("VRDisplay")}} 物件

+ +

Sketch of a person in a chair with wearing goggles labelled "Head mounted display (HMD)" facing a monitor with a webcam labelled "Position sensor"

+ +

{{domxref("VRDisplay")}} 是 WebVR API 的核心,提供以下功能:

+ + + +

A typical (simple) WebVR app would work like so:

+ +
    +
  1. 呼叫 {{domxref("Navigator.getVRDisplays()")}} 來取得 VR 顯示器的 reference。
  2. +
  3. 呼叫 {{domxref("VRDisplay.requestPresent()")}} 來啟動 VR顯示器。
  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 ({{domxref("VRDisplay.submitFrame()")}}).
  8. +
+ +

In addition, WebVR 1.1 adds a number of events on the {{domxref("Window")}} object to allow JavaScript to respond to changes to the status of the display.

+ +
+

Note: You can find a lot more out about how the API works in our Using the WebVR API and WebVR Concepts articles.

+
+ +

Using controllers: Combining WebVR with the Gamepad API

+ +

Many WebVR hardware setups feature controllers that go along with the headset. These can be used in WebVR apps via the Gamepad API, and specifically the Gamepad Extensions API that adds API features for accessing controller pose, haptic actuators, and more.

+ +
+

Note: Our Using VR controllers with WebVR article explains the basics of how to use VR controllers with WebVR apps.

+
+ +

WebVR Interfaces

+ +
+
{{domxref("VRDisplay")}}
+
Represents any VR device supported by this API. It includes generic information such as device IDs and descriptions, as well as methods for starting to present a VR scene, retrieving eye parameters and display capabilities, and other important functionality.
+
{{domxref("VRDisplayCapabilities")}}
+
Describes the capabilities of a {{domxref("VRDisplay")}} — it's features can be used to perform VR device capability tests, for example can it return position information.
+
{{domxref("VRDisplayEvent")}}
+
Represents the event object of WebVR-related events (see the {{anch("Window", "window object extensions")}} listed below).
+
{{domxref("VRFrameData")}}
+
Represents all the information needed to render a single frame of a VR scene; constructed by {{domxref("VRDisplay.getFrameData()")}}.
+
{{domxref("VRPose")}}
+
Represents the position state at a given timestamp (which includes orientation, position, velocity, and acceleration.)
+
{{domxref("VREyeParameters")}}
+
Provides access to all the information required to correctly render a scene for each given eye, including field of view information.
+
{{domxref("VRFieldOfView")}}
+
Represents a field of view defined by 4 different degree values describing the view from a center point.
+
{{domxref("VRLayerInit")}}
+
Represents a layer to be presented in a {{domxref("VRDisplay")}}.
+
{{domxref("VRStageParameters")}}
+
Represents the values describing the the stage area for devices that support room-scale experiences.
+
+ +

Extensions to other interfaces

+ +

The WebVR API extends the following APIs, adding the listed features.

+ +

Gamepad

+ +
+
{{domxref("Gamepad.displayId")}} {{readonlyInline}}
+
Returns the {{domxref("VRDisplay.displayId")}} of the associated {{domxref("VRDisplay")}} — the VRDisplay that the gamepad is controlling the displayed scene of.
+
+ + + +
+
{{domxref("Navigator.activeVRDisplays")}} {{readonlyInline}}
+
Returns an array containing every {{domxref("VRDisplay")}} object that is currently presenting ({{domxref("VRDisplay.ispresenting")}} is true).
+
{{domxref("Navigator.getVRDisplays()")}}
+
Returns a promise that resolves to an array of {{domxref("VRDisplay")}} objects representing any available VR displays connected to the computer.
+
+ +

Window events

+ +
+
{{domxref("Window.onvrdisplaypresentchange")}}
+
Represents an event handler that will run when the presenting state of a VR display changes — i.e. goes from presenting to not presenting, or vice versa (when the {{event("vrdisplaypresentchange")}} event fires).
+
{{domxref("Window.onvrdisplayconnect")}}
+
Represents an event handler that will run when a compatible VR display has been connected to the computer (when the {{event("vrdisplayconnect")}} event fires).
+
{{domxref("Window.onvrdisplaydisconnect")}}
+
Represents an event handler that will run when a compatible VR display has been disconnected from the computer (when the {{event("vrdisplaydisconnect")}} event fires).
+
{{domxref("Window.onvrdisplayactivate")}}
+
Represents an event handler that will run when a display is able to be presented to (when the {{event("vrdisplayactivate")}} event fires), for example if an HMD has been moved to bring it out of standby, or woken up by being put on.
+
{{domxref("Window.onvrdisplaydeactivate")}}
+
Represents an event handler that will run when a display can no longer be presented to (when the {{event("vrdisplaydeactivate")}} event fires), for example if an HMD has gone into standby or sleep mode due to a period of inactivity.
+
+ +

Unimplemented window events

+ +

The following events are listed in the spec, but do not currently seem to be implemented anywhere as yet.

+ +
+
{{domxref("Window.onvrdisplayblur")}}
+
Represents an event handler that will run when presentation to a display has been paused for some reason by the browser, OS, or VR hardware (when the {{event("vrdisplayblur")}} event fires) — for example, while the user is interacting with a system menu or browser, to prevent tracking or loss of experience.
+
{{domxref("Window.onvrdisplayfocus")}}
+
Represents an event handler that will run when presentation to a display has resumed after being blurred (when the {{event("vrdisplayfocus")}} event fires).
+
+ +

Examples

+ +

You can find a number of examples at these locations:

+ + + +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("GamepadExtensions")}}{{Spec2("GamepadExtensions")}}Defines the Experimental Gamepad extensions.
{{SpecName('WebVR 1.1')}}{{Spec2('WebVR 1.1')}}Initial definition
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatNo}}[1]{{CompatVersionUnknown}}{{CompatGeckoDesktop(55)}}[2]{{CompatNo}}{{CompatNo}}{{CompatNo}}
Gamepad extensions{{CompatNo}}{{CompatNo}}{{CompatNo}}[4]{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileChrome for AndroidSamsung Internet for GearVR
Basic support{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile(55)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}[3]{{CompatVersionUnknown}}
+  
Gamepad extensions{{CompatNo}}{{CompatNo}}{{CompatNo}}[4]{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

[1] API Available on all platforms behind a flag, but currently only works on desktop in an experimental version of Chrome (other builds won't return any devices when {{domxref("Navigator.getVRDisplays()")}} is invoked).

+ +

[2] Currently only Windows support is enabled by default. Mac support is available in Firefox Nightly.

+ +

[3] Currently supported only by Google Daydream.

+ +

[4] Enabled in Firefox Nightly and Beta, versions 55 and above. Enabled/disabled by the dom.gamepad-extensions.enabled pref.

+ +

See also

+ + diff --git a/files/zh-tw/web/api/wheelevent/index.html b/files/zh-tw/web/api/wheelevent/index.html new file mode 100644 index 0000000000..e7446cc044 --- /dev/null +++ b/files/zh-tw/web/api/wheelevent/index.html @@ -0,0 +1,196 @@ +--- +title: WheelEvent +slug: Web/API/WheelEvent +translation_of: Web/API/WheelEvent +--- +

{{APIRef("DOM Events")}}

+ +

WheelEvent DOM事件會在用戶滚动滑鼠滚轮或操作其它類似滑鼠的設備時觸發。

+ +
該事件爲標準規定的事件介面。早期的瀏覽器實現過{{ domxref("MouseWheelEvent") }}和{{domxref("MouseScrollEvent")}}兩種滾輪事件介面,但這兩種介面皆非標準,加之各瀏覽器間對其相容性極差。因而開發者應用該標準事件介面取代這兩個非標準介面。
+ +
注意事項: 請勿想當然依據滾輪方向(即該事件的各delta屬性值)來推斷文檔內容的滾動方向,因標準未定義滾輪事件具體會引發什麼樣的行爲,引發的行爲實際上是各瀏覽器自行定義的。即便滾輪事件引發了文檔內容的滾動行爲,也不表示滾輪方向和文檔內容的滾動方向一定相同。因而通過該滾輪事件獲知文檔內容滾動方向的方法並不可靠。要獲取文檔內容的滾動方向,可在文檔內容滾動事件({{event("scroll")}})中監視{{domxref("Element.scrollLeft", "scrollLeft")}}和{{domxref("Element.scrollTop", "scrollTop")}}二值變化情況,即可推斷出滾動方向了。
+ +

{{InheritanceDiagram}}

+ +

建構式

+ +
+
{{domxref("WheelEvent.WheelEvent", "WheelEvent()")}}
+
建立一個WheelEvent物件。
+
+ +

屬性

+ +

該介面繼承了父介面{{domxref("MouseEvent")}}、{{domxref("UIEvent")}}、{{domxref("Event")}}的屬性。

+ +
+
{{domxref("WheelEvent.deltaX")}} {{readonlyinline}}
+
返回double值,該值表示滾輪的橫向滾動量。
+
{{domxref("WheelEvent.deltaY")}} {{readonlyinline}}
+
返回double值,該值表示滾輪的縱向滾動量。
+
{{domxref("WheelEvent.deltaZ")}} {{readonlyinline}}
+
返回double值,該值表示滾輪的z軸方向上的滾動量。
+
{{domxref("WheelEvent.deltaMode")}} {{readonlyinline}}
+
返回unsigned long值,該值表示上述各delta的值的單位。該值及所表示的單位如下: + + + + + + + + + + + + + + + + + + + + + + + +
常數描述
DOM_DELTA_PIXEL0x00滾動量單位爲像素。
DOM_DELTA_LINE0x01滾動量單位爲行。
DOM_DELTA_PAGE0x02滾動量單位爲頁。
+
+
+ +

方法

+ +

該介面本身未定義方法,但繼承了父介面{{domxref("MouseEvent")}}、{{domxref("UIEvent")}}、{{domxref("Event")}}的方法。

+ +

規範

+ + + + + + + + + + + + + + +
規範狀態註解
{{SpecName('DOM3 Events','#interface-wheelevent','WheelEvent')}}{{Spec2('DOM3 Events')}}Initial definition.
+ +

瀏覽器相容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
功能ChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
基本功能31{{ CompatVersionUnknown }}{{ CompatGeckoDesktop("17.0") }}{{ CompatIE("9.0") }}187.0
window.WheelEvent{{CompatVersionUnknown}}{{ CompatVersionUnknown }}{{ CompatGeckoDesktop("17.0") }}{{ CompatIE("9.0") }}{{CompatVersionUnknown}}{{CompatVersionUnknown}} [1]
WheelEvent + Ctrl[2]實現按住縮放功能{{CompatVersionUnknown}}{{CompatUnknown}}{{ CompatGeckoDesktop("55.0") }}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
功能AndroidAndroid WebviewEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
基本功能{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{ CompatGeckoMobile("17.0") }}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown}}
window.WheelEvent{{CompatNo}}{{CompatVersionUnknown}}{{CompatUnknown}}{{ CompatGeckoMobile("17.0") }}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
WheelEvent + Ctrl[2]實現按住縮放功能{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{ CompatGeckoMobile("55.0") }}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
+
+ +

[1] 嚴格說,Safari並非真正支援WheelEvent,只不過會返回window.WheelEvent物件。

+ +

[2] 這樣在觸控平面上,比如觸控螢幕或是觸控板上,開發者就可根據用戶按住縮放手勢來實現簡單的縮放功能 (滑鼠滾輪 + Ctrl 習慣上用於縮放)。

+ +

參見

+ + diff --git a/files/zh-tw/web/api/window.history/index.html b/files/zh-tw/web/api/window.history/index.html new file mode 100644 index 0000000000..67b79c5f82 --- /dev/null +++ b/files/zh-tw/web/api/window.history/index.html @@ -0,0 +1,51 @@ +--- +title: Window.history +slug: Web/API/Window.history +translation_of: Web/API/Window/history +--- +

{{ APIRef }}

+ +

Window.history 唯讀屬性會回傳一個 {{domxref("History")}} 物件,其提供了一個介面來操控瀏覽器的 session history 紀錄(為當前面頁所在分頁中訪問、或於當前面頁中透過頁面框架(frame)所載入的頁面)。

+ +

相關範例及細節請參考操控瀏覽器歷史紀錄一文。文章中解釋了在使用 pushState()replaceState() 方法前應該要知道的安全性功能。

+ +

語法

+ +
var historyObj = window.history;
+
+ +

範例

+ +
history.back();     // 相當於按下上一頁按鈕
+history.go(-1);     // 相當於 history.back();
+
+ +

備註

+ +

For top-level pages you can see the list of pages in the session history, accessible via the History object, in the browser's dropdowns next to the back and forward buttons.

+ +

For security reasons the History object doesn't allow the non-privileged code to access the URLs of other pages in the session history, but it does allow it to navigate the session history.

+ +

There is no way to clear the session history or to disable the back/forward navigation from unprivileged code. The closest available solution is the location.replace() method, which replaces the current item of the session history with the provided URL.

+ +

規範

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{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/zh-tw/web/api/window.onpopstate/index.html b/files/zh-tw/web/api/window.onpopstate/index.html new file mode 100644 index 0000000000..d98464d356 --- /dev/null +++ b/files/zh-tw/web/api/window.onpopstate/index.html @@ -0,0 +1,57 @@ +--- +title: window.onpopstate +slug: Web/API/Window.onpopstate +translation_of: Web/API/WindowEventHandlers/onpopstate +--- +
{{ApiRef}} {{gecko_minversion_header("2")}}
+ +

摘要

+ +

視窗上 popstate 事件的事件處理器。

+ +

在同一文件的當前歷史紀錄變動時,如果其變動介於兩個歷史紀錄間,popstate 就會被呼叫。如果當前的歷史紀錄是藉由呼叫 history.pushState() 建立,或曾被 history.replaceState() 修改過,popstate 事件的 state 屬性,將包含一份歷史紀錄的 state 物件。

+ +

請注意:直接呼叫 history.pushState()history.replaceState() 不會驅動 popstate 事件。popstate 事件只會被瀏覽器的行為驅動,例如點擊上一頁按鈕(或透過 JavaScript 呼叫 history.back())。且此事件只會在用戶於同文件的兩個歷史紀錄間瀏覽時作動。

+ +

在頁面載入時,不同瀏覽器具有不同的 popstate 行為。Chrome 與 Safari 會在頁面載入時觸發 popstate 事件,但 Firefox 則不會。

+ +

語法

+ +
window.onpopstate = funcRef;
+
+ + + +

popstate 事件

+ +

以下範例,位於 http://example.com/example.html 並執行下列程式的頁面,將會產生如標示的對話框:

+ +
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(); // 跳出 "location: http://example.com/example.html?page=1, state: {"page":1}"
+history.back(); // 跳出 "location: http://example.com/example.html, state: null
+history.go(2);  // 跳出 "location: http://example.com/example.html?page=3, state: {"page":3}
+
+ +

請注意,雖然原始的歷史紀錄(http://example.com/example.html)沒有關聯的 state 物件,在我們第二次呼叫 hitsory.back() 時仍然會觸發 popstate 事件

+ +

標準

+ + + +

請參照

+ + diff --git a/files/zh-tw/web/api/window.requestanimationframe/index.html b/files/zh-tw/web/api/window.requestanimationframe/index.html new file mode 100644 index 0000000000..55aa85d292 --- /dev/null +++ b/files/zh-tw/web/api/window.requestanimationframe/index.html @@ -0,0 +1,94 @@ +--- +title: Window.requestAnimationFrame() +slug: Web/API/Window.requestAnimationFrame +translation_of: Web/API/window/requestAnimationFrame +--- +
{{APIRef}}
+ +

window.requestAnimationFrame()方法通知瀏覽器我們想要產生動畫,並且要求瀏覽器在下次重繪畫面前呼叫特定函數更新動畫。這個方法接受一個引數作為下次重繪前調用的回呼函數。

+ +
Note: 若是想要在下次重繪時產生另一個動畫,這個回呼函數內必須自行呼叫 requestAnimationFrame()。
+ +

當準備好更新頁面上的動畫時應當呼叫這個方法。這表示向瀏覽器請求在下次重繪前呼叫這個動畫函數。回呼的次數通常落在每秒 60 次,但通常會根據 W3C 的建議符合多數瀏覽器重新整理的頻率。當頁面處於背景或隱藏狀態時 {{ HTMLElement("iframe") }} ,多數的瀏覽器會暫停 requestAnimationFrame() 的呼叫,從而改善效能表現及電池壽命。

+ +

回呼方法會得到一個 {{domxref("DOMHighResTimeStamp")}} 的引數,作為指示目前的時間(基於 time origin 之後經過的毫秒數)。當 requestAnimationFrame() 佇列了數個回呼並且在同一幀開始觸發多個回呼時,儘管每一個之前的回呼在運作時會消耗一定的時間,但它們都會取得同樣的時間戳記。時間戳記是由十進位數字表示的毫秒且最小的精準度為 1 毫秒(1000 µs)。

+ +

語法

+ +
window.requestAnimationFrame(callback);
+
+ +

參數

+ +
+
回呼
+
當下次重新繪製時用於呼叫並更新動畫。回呼函數會得到一個引數—— {{domxref("DOMHighResTimeStamp")}} ——類似於由 {{domxref('performance.now()')}} 回傳的結果,其用於指示當 requestAnimationFrame() 開始執行回呼函數的時間。
+
+ +

回傳值

+ +

long 型別的整數值表示請求的 id,作為其進入回呼清單中的唯一識別。雖然回傳值是一個非零值,但不應該對其有其他任何的假設。將這個值傳遞給 {{domxref("window.cancelAnimationFrame()")}} 可以取消重新整理頁面回呼的請求

+ +

範例

+ +
var start = null;
+var element = document.getElementById('SomeElementYouWantToAnimate');
+
+function step(timestamp) {
+  if (!start) start = timestamp;
+  var progress = timestamp - start;
+  element.style.transform = 'translateX(' + Math.min(progress / 10, 200) + 'px)';
+  if (progress < 2000) {
+    window.requestAnimationFrame(step);
+  }
+}
+
+window.requestAnimationFrame(step);
+
+ +

備註

+ +

Edge 低於 17 的版本和 Internet Explorer 無法保證在繪製循環前觸發 requestAnimationFrame

+ +

規格

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#animation-frames', 'requestAnimationFrame')}}{{Spec2('HTML WHATWG')}}No change, supersedes the previous one.
{{SpecName('RequestAnimationFrame', '#dom-windowanimationtiming-requestanimationframe', 'requestAnimationFrame')}}{{Spec2('RequestAnimationFrame')}}Initial definition
+ +

瀏覽器相容性

+ +
+

{{Compat("api.Window.requestAnimationFrame")}}

+
+ +

其他參考

+ + diff --git a/files/zh-tw/web/api/window/getcomputedstyle/index.html b/files/zh-tw/web/api/window/getcomputedstyle/index.html new file mode 100644 index 0000000000..8dd0f24bad --- /dev/null +++ b/files/zh-tw/web/api/window/getcomputedstyle/index.html @@ -0,0 +1,200 @@ +--- +title: Window.getComputedStyle() +slug: Web/API/Window/getComputedStyle +translation_of: Web/API/Window/getComputedStyle +--- +

{{APIRef()}}

+ +

概要

+ +

Window.getComputedStyle() 方法可以得到元素於套用啟用之樣式表以及解析其中可能包含的任何基本運算後的所有 CSS 屬性值。

+ +

語法

+ +
var style = window.getComputedStyle(element[, pseudoElt]);
+
+ +
+
element
+
The {{domxref("Element")}} for which to get the computed style.
+
pseudoElt {{optional_inline}}
+
A string specifying the pseudo-element to match. Must be omitted (or null) for regular elements.
+
+ +
Note: Prior to Gecko 2.0 {{geckoRelease("2.0")}}, the pseudoElt parameter was required. No other major browser required this parameter be specified if null. Gecko has been changed to match the behavior of other browsers.
+ +

The returned style is a live {{domxref("CSSStyleDeclaration")}} object, which updates itself automatically when the element's style is changed.

+ +

範例

+ +
var elem1 = document.getElementById("elemId");
+var style = window.getComputedStyle(elem1, null);
+
+// this is equivalent:
+// var style = document.defaultView.getComputedStyle(elem1, null);
+
+ +
<style>
+ #elem-container{
+   position: absolute;
+   left:     100px;
+   top:      200px;
+   height:   100px;
+ }
+</style>
+
+<div id="elem-container">dummy</div>
+<div id="output"></div>
+
+<script>
+  function getTheStyle(){
+    var elem = document.getElementById("elem-container");
+    var theCSSprop = window.getComputedStyle(elem,null).getPropertyValue("height");
+    document.getElementById("output").innerHTML = theCSSprop;
+   }
+  getTheStyle();
+</script>
+
+ +
function dumpComputedStyles(elem,prop) {
+
+  var cs = window.getComputedStyle(elem,null);
+  if (prop) {
+    console.log(prop+" : "+cs.getPropertyValue(prop));
+    return;
+  }
+  var len = cs.length;
+  for (var i=0;i<len;i++) {
+
+    var style = cs[i];
+    console.log(style+" : "+cs.getPropertyValue(style));
+  }
+
+}
+
+ +

說明

+ +

The returned object is of the same type that the object returned from the element's {{domxref("HTMLElement.style", "style")}} property; however, the two objects have different purposes. The object returned from getComputedStyle is read-only and can be used to inspect the element's style (including those set by a <style> element or an external stylesheet). The elt.style object should be used to set styles on a specific element.

+ +

The first argument must be an Element (passing a non-Element Node, like a #text Node, will throw an error). Starting in Gecko 1.9.2 {{geckoRelease("1.9.2")}}, returned URL values now have quotes around the URL, like this: url("http://foo.com/bar.jpg").

+ +

defaultView

+ +

In many code samples online, getComputedStyle is used from the document.defaultView object. In nearly all cases, this is needless, as getComputedStyle exists on the window object as well. It's likely the defaultView pattern was some combination of (1) folks not wanting to write a spec for window and (2) making an API that was also usable in Java. However, there is a single case where the defaultView's method must be used: when using Firefox 3.6 to access framed styles.

+ +

Use with pseudo-elements

+ +

getComputedStyle can pull style info from pseudo-elements (for example, ::after, ::before, ::marker, ::line-marker—see spec here).

+ +
<style>
+ h3::after {
+   content: ' rocks!';
+ }
+</style>
+
+<h3>generated content</h3>
+
+<script>
+  var h3       = document.querySelector('h3'),
+      result   = getComputedStyle(h3, ':after').content;
+
+  console.log('the generated content is: ', result); // returns ' rocks!'
+</script>
+
+ +

備註

+ +

The values returned by getComputedStyle are known as {{cssxref("resolved_value", "resolved values")}}. These are usually the same as the CSS 2.1 {{cssxref("computed_value","computed values")}}, but for some older properties like width, height or padding, they are instead the {{cssxref("used_value","used values")}}. Originally, CSS 2.0 defined the computed values to be the "ready to be used" final values of properties after cascading and inheritance, but CSS 2.1 redefined computed values as pre-layout, and used values as post-layout. For CSS 2.0 properties, the getComputedStyle function returns the old meaning of computed values, now called used values. An example of difference between pre- and post-layout values includes the resolution of percentages that represent the width or the height of an element (also known as its layout), as those will be replaced by their pixel equivalent only in the used value case.

+ +

The returned value is, in certain known cases, expressly inaccurate by deliberate intent. In particular, to avoid the so called CSS History Leak security issue, browsers may expressly "lie" about the used value for a link and always return values as if a user has never visited the linked site. See http://blog.mozilla.com/security/2010/03/31/plugging-the-css-history-leak/ and http://hacks.mozilla.org/2010/03/privacy-related-changes-coming-to-css-vistited/ for details of the examples of how this is implemented. Most other modern browsers have applied similar changes to the application of pseudo-selector styles and the values returned by getComputedStyle.

+ +

During a CSS transition, getComputedStyle returns the original property value in Firefox, but the final property value in WebKit.

+ +

In Firefox, properties with the value auto return the used value, not the value auto. So if you apply top:auto; and bottom:0; on an element with height:30px and its containing block is height:100px;, upon requesting the computed style for top, Firefox will return top:70px, as 100px-30px=70px.

+ +

瀏覽器相容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}9{{CompatVersionUnknown}}{{CompatVersionUnknown}}
pseudo-element support{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}915{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}WP7 Mango{{CompatVersionUnknown}}{{CompatVersionUnknown}}
pseudo-element support{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

規範

+ + + +

參見

+ + diff --git a/files/zh-tw/web/api/window/index.html b/files/zh-tw/web/api/window/index.html new file mode 100644 index 0000000000..276dcc96e2 --- /dev/null +++ b/files/zh-tw/web/api/window/index.html @@ -0,0 +1,468 @@ +--- +title: Window +slug: Web/API/Window +translation_of: Web/API/Window +--- +

{{APIRef}}

+ +

window 物件代表了一個包含 DOM 文件的視窗,其中的 document 屬性指向了視窗中載入的 {{domxref("Document")}} 物件。而使用 document {{Domxref("Document.defaultView", "defaultView")}} 屬性,則可取得該 Document 物件所在的視窗 window 物件。

+ +

本節提供了 DOM window 物件的所有方法、屬性以及事件的說明。window 物件實作了 Window 介面,而 Window 介面則繼承自 AbstractView 介面。一些額外、與 window 物件沒有直接關係,但卻置於 window 物件中的全域函式、命名空間、物件、介面以及建構式,將會在 JavaScript 參考文件文件物件模型(DOM)中說明。

+ +

在支援分頁的瀏覽器中(如 Firefox),每一個分頁標籤都擁有自己的 window 物件(如果你正在撰寫瀏覽器附加元件,瀏覽器視窗本身也是一個個別的 window-請參閱 Working with windows in chrome code),分頁不會於同一個瀏覽器視窗中共享 window 物件。但有部分的方法,如 {{Domxref("window.resizeTo()")}} 或 {{Domxref("window.resizeBy()")}} 會套用至整個視窗,而不只是該 window 物件所屬的分頁標籤。一般來說,若無法適當的應用於分頁,便會套用至瀏覽器視窗。

+ +

{{InheritanceDiagram}}

+ +

屬性

+ +

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

+ +

請注意,指向物件的屬性(例如覆蓋了內建物件原型的元素)會在另外的列表中說明。

+ +
+
{{domxref("Window.applicationCache")}} {{readOnlyInline}} {{gecko_minversion_inline("1.9")}}
+
指向 {{domxref("OfflineResourceList")}} 物件,此物件提供了視窗的離線資源。
+
{{domxref("Window.closed")}} {{Non-standard_inline}}{{readOnlyInline}}
+
This property indicates whether the current window is closed or not.
+
{{domxref("Window.Components")}} {{Non-standard_inline}}
+
The entry point to many XPCOM features. Some properties, e.g. classes, are only available to sufficiently privileged code. Web code should not use this property.
+
{{domxref("Window.console")}} {{ReadOnlyInline}}
+
Returns a reference to the console object which provides access to the browser's debugging console.
+
{{domxref("Window.content")}} and Window._content {{Non-standard_inline}} {{obsolete_inline}}{{ReadOnlyInline}}
+
Returns a reference to the content element in the current window. The obsolete variant with underscore is no longer available from Web content.
+
{{domxref("Window.controllers")}}{{non-standard_inline}}{{ReadOnlyInline}}
+
Returns the XUL controller objects for the current chrome window.
+
{{domxref("Window.crypto")}} {{readOnlyInline}}
+
Returns the browser crypto object.
+
{{domxref("Window.defaultStatus")}} {{Obsolete_inline("gecko23")}}
+
Gets/sets the status bar text for the given window.
+
{{domxref("Window.devicePixelRatio")}} {{non-standard_inline}}{{ReadOnlyInline}}
+
Returns the ratio between physical pixels and device independent pixels in the current display.
+
{{domxref("Window.dialogArguments")}} {{Fx_minversion_inline(3)}} {{ReadOnlyInline}}
+
Gets the arguments passed to the window (if it's a dialog box) at the time {{domxref("window.showModalDialog()")}} was called. This is an {{Interface("nsIArray")}}.
+
{{domxref("Window.directories")}} {{obsolete_inline}}
+
Synonym of {{domxref("window.personalbar")}}
+
{{domxref("Window.document")}} {{ReadOnlyInline}}
+
指向此 window 中的 document 物件。
+
{{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")}}
+
此屬性表示目前視窗是否為全螢幕顯示。
+
{{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}}
+
指向 history 物件。
+
{{domxref("Window.innerHeight")}} {{readOnlyInline}}
+
取得視窗內的網頁內容高度,包含水平捲軸。
+
{{domxref("Window.innerWidth")}} {{readOnlyInline}}
+
取得視窗內的網頁內容寬度,包含垂直捲軸。
+
{{domxref("Window.isSecureContext")}} {{readOnlyInline}}
+
Indicates whether a context is capable of using features that require secure contexts.
+
{{domxref("Window.length")}} {{readOnlyInline}}
+
Returns the number of frames in the window. See also {{domxref("window.frames")}}.
+
{{domxref("Window.location")}}
+
Gets/sets the location, or current URL, of the window object.
+
{{domxref("Window.locationbar")}} {{ReadOnlyInline}}
+
Returns the locationbar object, whose visibility can be toggled in the window.
+
{{domxref("Window.localStorage")}} {{readOnlyInline}}{{gecko_minversion_inline("1.9.1")}}
+
Returns a reference to the local storage object used to store data that may only be accessed by the origin that created it.
+
{{domxref("Window.menubar")}} {{ReadOnlyInline}}
+
Returns the menubar object, whose visibility can be toggled in the window.
+
{{domxref("Window.messageManager")}} {{gecko_minversion_inline("2.0")}}
+
Returns the message manager object for this window.
+
{{domxref("Window.mozAnimationStartTime")}} {{ReadOnlyInline}}{{gecko_minversion_inline("2.0")}} {{Deprecated_inline}}
+
The time in milliseconds since epoch at which the current animation cycle began.
+
{{domxref("Window.mozInnerScreenX")}} {{ReadOnlyInline}}{{non-standard_inline}}{{gecko_minversion_inline("1.9.2")}}
+
Returns the horizontal (X) coordinate of the top-left corner of the window's viewport, in screen coordinates. This value is reported in CSS pixels. See mozScreenPixelsPerCSSPixel in {{interface("nsIDOMWindowUtils")}} for a conversion factor to adapt to screen pixels if needed.
+
{{domxref("Window.mozInnerScreenY")}} {{ReadOnlyInline}} {{non-standard_inline}}{{gecko_minversion_inline("1.9.2")}}
+
Returns the vertical (Y) coordinate of the top-left corner of the window's viewport, in screen coordinates. This value is reported in CSS pixels. See mozScreenPixelsPerCSSPixel for a conversion factor to adapt to screen pixels if needed.
+
{{domxref("Window.mozPaintCount")}} {{non-standard_inline}}{{ReadOnlyInline}} {{gecko_minversion_inline("2.0")}}
+
Returns the number of times the current document has been rendered to the screen in this window. This can be used to compute rendering performance.
+
{{domxref("Window.name")}}
+
Gets/sets the name of the window.
+
{{domxref("Window.navigator")}} {{readOnlyInline}}
+
Returns a reference to the navigator object.
+
{{domxref("Window.opener")}}
+
Returns a reference to the window that opened this current window.
+
{{domxref("Window.orientation")}}{{non-standard_inline}}{{deprecated_inline}}{{readOnlyInline}}
+
Returns the orientation in degrees (in 90 degree increments) of the viewport relative to the device's natural orientation.
+
{{domxref("Window.outerHeight")}} {{readOnlyInline}}
+
取得瀏覽器視窗的高度。
+
{{domxref("Window.outerWidth")}} {{readOnlyInline}}
+
取得瀏覽器視窗的寬度。
+
{{domxref("Window.scrollX","Window.pageXOffset")}} {{readOnlyInline}}
+
An alias for {{domxref("window.scrollX")}}.
+
{{domxref("Window.scrollY","Window.pageYOffset")}}{{readOnlyInline}}
+
An alias for {{domxref("window.scrollY")}}
+
{{domxref("Window.sessionStorage")}} {{readOnlyInline}}
+
Returns a reference to the session storage object used to store data that may only be accessed by the origin that created it.
+
{{domxref("Window.parent")}} {{readOnlyInline}}
+
Returns a reference to the parent of the current window or subframe.
+
{{domxref("Window.performance")}} {{readOnlyInline}}
+
Returns a {{domxref("Performance")}} object, which includes the {{domxref("Performance.timing", "timing")}} and {{domxref("Performance.navigation", "navigation")}} attributes, each of which is an object providing performance-related data. See also Using Navigation Timing for additional information and examples.
+
{{domxref("Window.personalbar")}} {{readOnlyInline}}
+
Returns the personalbar object, whose visibility can be toggled in the window.
+
{{domxref("Window.pkcs11")}} {{obsolete_inline(29)}}
+
Formerly provided access to install and remove PKCS11 modules.
+
{{domxref("Window.returnValue")}} {{Fx_minversion_inline(3)}}
+
The return value to be returned to the function that called {{domxref("window.showModalDialog()")}} to display the window as a modal dialog.
+
{{domxref("Window.screen")}} {{readOnlyInline}}
+
回傳一個與 window 關聯的 screen 物件。
+
{{domxref("Window.screenX")}} {{readOnlyInline}}
+
Returns the horizontal distance of the left border of the user's browser from the left side of the screen.
+
{{domxref("Window.screenY")}} {{readOnlyInline}}
+
Returns the vertical distance of the top border of the user's browser from the top side of the screen.
+
{{domxref("Window.scrollbars")}} {{readOnlyInline}}
+
Returns the scrollbars object, whose visibility can be toggled in the window.
+
{{domxref("Window.scrollMaxX")}}{{non-standard_inline}}{{ReadOnlyInline}}
+
The maximum offset that the window can be scrolled to horizontally, that is the document width minus the viewport width.
+
{{domxref("Window.scrollMaxY")}}{{non-standard_inline}}{{ReadOnlyInline}}
+
The maximum offset that the window can be scrolled to vertically (i.e., the document height minus the viewport height).
+
{{domxref("Window.scrollX")}} {{readOnlyInline}}
+
Returns the number of pixels that the document has already been scrolled horizontally.
+
{{domxref("Window.scrollY")}} {{readOnlyInline}}
+
Returns the number of pixels that the document has already been scrolled vertically.
+
{{domxref("Window.self")}} {{ReadOnlyInline}}
+
Returns an object reference to the window object itself.
+
{{domxref("Window.sessionStorage")}} {{Fx_minversion_inline("2.0")}}
+
Returns a storage object for storing data within a single page session.
+
{{domxref("Window.sidebar")}} {{non-standard_inline}}{{ReadOnlyInline}}
+
Returns a reference to the window object of the sidebar.
+
{{domxref("Window.speechSynthesis")}} {{ReadOnlyInline}}
+
Returns a {{domxref("SpeechSynthesis")}} object, which is the entry point into using Web Speech API speech synthesis functionality.
+
{{domxref("Window.status")}}
+
Gets/sets the text in the statusbar at the bottom of the browser.
+
{{domxref("Window.statusbar")}} {{readOnlyInline}}
+
Returns the statusbar object, whose visibility can be toggled in the window.
+
{{domxref("Window.toolbar")}} {{readOnlyInline}}
+
Returns the toolbar object, whose visibility can be toggled in the window.
+
{{domxref("Window.top")}} {{readOnlyInline}}
+
Returns a reference to the topmost window in the window hierarchy. This property is read only.
+
{{domxref("Window.window")}} {{ReadOnlyInline}}
+
Returns a reference to the current window.
+
window[0], window[1], etc.
+
Returns a reference to the window object in the frames. See {{domxref("Window.frames")}} for more details.
+
+ +

Properties implemented from elsewhere

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

方法

+ +

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

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

Methods implemented from elsewhere

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

Obsolete methods

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

事件處理器

+ +

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

+ +

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

+ +
+

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

建構式

+ +

See also the DOM Interfaces.

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

相關介面

+ +

請參閱 {{domxref("Document_Object_Model", "DOM Reference")}}

+ +

參見

+ + diff --git a/files/zh-tw/web/api/window/localstorage/index.html b/files/zh-tw/web/api/window/localstorage/index.html new file mode 100644 index 0000000000..1733a325bd --- /dev/null +++ b/files/zh-tw/web/api/window/localstorage/index.html @@ -0,0 +1,82 @@ +--- +title: Window.localStorage +slug: Web/API/Window/localStorage +translation_of: Web/API/Window/localStorage +--- +

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

+ +

localStorage 為一唯讀屬性, 此屬性允許您存取目前文件({{DOMxRef("Document")}})隸屬網域來源的 {{DOMxRef("Storage")}} 物件; 與 sessionStorage 不同的是其儲存資料的可存取範圍為跨瀏覽頁狀態(Browser Sessions). localStorage 的應用與 {{DOMxRef("Window.sessionStorage", "sessionStorage")}} 相似, 除了 localStorage 的儲存資料並無到期的限制, 而 sessionStorage 的儲存資料於目前瀏覽頁狀態結束的同時將一併被清除 — 也就是目前瀏覽器頁面被關閉的同時.

+ +

值得注意的是不論 localStorage 或者 sessionStorage 皆為專屬於目前瀏覽器頁面的通訊協定(Protocol).

+ +

鍵值名稱和值皆為字串型式(請留意, 當其為物件, 整數等將自動轉換為字串型式).

+ +

Syntax

+ +
myStorage = window.localStorage;
+ +

Value

+ +

{{DOMxRef("Storage")}} 物件 which can be used to access the current origin's local storage space.

+ +

Exceptions

+ +
+
SecurityError
+
The request violates a policy decision, or the origin is not a valid scheme/host/port tuple (this can happen if the origin uses the file: or data: scheme, for example). 舉例來說,使用者 may have their browser configured to deny permission to persist data for the specified origin.
+
+ +

Example

+ +

下列的程式碼片段讀取了目前域名內的 local {{DOMxRef("Storage")}} 物件 ,並用{{DOMxRef("Storage.setItem()")}},增加一個資料物件 item 到其中

+ +
localStorage.setItem('myCat', 'Tom');
+ +

讀取 localStorage 內物件的語法如下:

+ +
var cat = localStorage.getItem('myCat');
+ +

移除 localStorage 內物件的語法如下:

+ +
localStorage.removeItem('myCat');
+ +

刪除 localStorage 內所有物件的語法如下:

+ +
// Clear all items
+localStorage.clear();
+
+ +
+

Note: Please refer to the Using the Web Storage API article for a full example.

+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("HTML WHATWG", "webstorage.html#dom-localstorage", "localStorage")}}{{Spec2("HTML WHATWG")}}
+ +

瀏覽器相容性

+ + + +

{{Compat("api.Window.localStorage")}}

+ +

See also

+ + diff --git a/files/zh-tw/web/api/window/location/index.html b/files/zh-tw/web/api/window/location/index.html new file mode 100644 index 0000000000..a887f88ee0 --- /dev/null +++ b/files/zh-tw/web/api/window/location/index.html @@ -0,0 +1,373 @@ +--- +title: window.location +slug: Web/API/Window/location +translation_of: Web/API/Window/location +--- +

{{ ApiRef() }}

+

Summary

+

Returns a Location object, which contains information about the URL of the document and provides methods for changing that URL. You can also assign to this property to load another URL.

+

語法

+
var locationObj = window.location;
+window.location = newLocation;
+
+

where

+ +

Location object

+

This section describes the properties and methods of the location object.

+

Use as a string

+

Location objects have a toString method returning the current URL. You can also assign a string to window.location. This means that you can work with window.location as if it were a string in most cases. Sometimes, for example when you need to call a String method on it, you have to explicitly call toString:

+
alert(window.location.toString().charAt(17));
+
+

Properties

+

All of the following properties are strings. You can read them to get information about the current URL or set them to navigate to another URL.

+

The "Example" column contains the values of the properties of the following URL:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyDescriptionExample
hashthe part of the URL that follows the # symbol, including the # symbol.
+ You can listen for the hashchange event to get notified of changes to the hash in supporting browsers.
#test
hostthe host name and port number.[www.example.com]:80
hostnamethe host name (without the port number or square brackets).www.example.com
hrefthe entire URL.http://[www.example.com]:80/search?q=devmo#test
pathnamethe path (relative to the host)./search
portthe port number of the URL.80
protocolthe protocol of the URL.http:
searchthe part of the URL that follows the ? symbol, including the ? symbol.?q=devmo
+

If the hash part of the URL contains encoded characters (see Core_JavaScript_1.5_Reference:Global_Functions:encodeURIComponent), hash returns the decoded URL part. This is a bug in Firefox. href, search and pathname return the correct, encoded URL parts. For example:

+ +

results in:

+ +

Methods

+ + + + + + + + + + + + + + + + + + + + + + + +
MethodDescription
assign(url)Load the document at the provided URL.
reload(forceget)Reload the document from the current URL. forceget is a boolean, which, when it is true, causes the page to always be reloaded from the server. If it is false or not specified, the browser may reload the page from its cache.
replace(url)Replace the current document with the one at the provided URL. The difference from the assign() method is that after using replace() the current page will not be saved in session history, meaning the user won't be able to use the Back button to navigate to it.
toString()Returns the string representation of the Location object's URL. See the JavaScript reference for details.
+

Examples

+

Whenever a property of the location object is modified, a document will be loaded using the URL as if window.location.assign() had been called with the modified URL.

+
Replace the current document with the one at the given URL:
+
function goMoz() {
+   window.location = "http://www.mozilla.org";
+}
+
+// in html: <button onclick="goMoz();">Mozilla</button>
+
+
+
+ Note: The example above works in situations where window.location.hash does not need to be retained. However, in Gecko-based browsers, setting window.location.pathname in this manner will erase any information in window.location.hash, whereas in WebKit (and possibly other browsers), setting the pathname will not alter the the hash. If you need to change pathname but keep the hash as is, use the replace() method instead, which should work consistently across browsers.
+


+ Consider the following example, which will reload the page by using the replace() method to insert the value of window.location.pathname into the hash (similar to Twitter's reload of http://twitter.com/username to http://twitter.com/#!/username):

+
function reloadPageWithHash() {
+  var initialPage = window.location.pathname;
+  window.location.replace('http://example.com/#' + initialPage);
+}
+
+
Display the properties of the current URL in an alert dialog:
+
function showLoc() {
+  var oLocation = window.location, aLog = ["Property (Typeof): Value", "window.location (" + (typeof oLocation) + "): " + oLocation ];
+  for (var sProp in oLocation){
+    aLog.push(sProp + " (" + (typeof oLocation[sProp]) + "): " +  (oLocation[sProp] || "n/a"));
+  }
+  alert(aLog.join("\n"));
+}
+
+// in html: <button onclick="showLoc();">Show location properties</button>
+
+
Send a string of data to the server by modifying the search property:
+
function sendData (sData) {
+  window.location.search = sData;
+}
+
+// in html: <button onclick="sendData('Some data');">Send data</button>
+
+
+

The current URL with "?Some%20data" appended is sent to the server (if no action is taken by the server, the current document is reloaded with the modified search string).

+
Get the value of a single window.location.search key:
+
function loadPageVar (sVar) {
+  return unescape(window.location.search.replace(new RegExp("^(?:.*[&\\?]" + escape(sVar).replace(/[\.\+\*]/g, "\\$&") + "(?:\\=([^&]*))?)?.*$", "i"), "$1"));
+}
+
+alert(loadPageVar("name"));
+
+
Nestle the variables obtained through the window.location.search string in an object named oGetVars:
+
var oGetVars = {};
+
+if (window.location.search.length > 1) {
+  for (var aItKey, nKeyId = 0, aCouples = window.location.search.substr(1).split("&"); nKeyId < aCouples.length; nKeyId++) {
+    aItKey = aCouples[nKeyId].split("=");
+    oGetVars[unescape(aItKey[0])] = aItKey.length > 1 ? unescape(aItKey[1]) : "";
+  }
+}
+
+// alert(oGetVars.yourVar);
+
+

…the same thing obtained by an anonymous constructor – useful for a global variable declaration:

+
var oGetVars = new (function (sSearch) {
+  if (sSearch.length > 1) {
+    for (var aItKey, nKeyId = 0, aCouples = sSearch.substr(1).split("&"); nKeyId < aCouples.length; nKeyId++) {
+      aItKey = aCouples[nKeyId].split("=");
+      this[unescape(aItKey[0])] = aItKey.length > 1 ? unescape(aItKey[1]) : "";
+    }
+  }
+})(window.location.search);
+
+// alert(oGetVars.yourVar);
+
+
Nestle the variables obtained through the window.location.search string in an object named oGetVars, also attempting to recognize their typeof:
+
var oGetVars = {};
+
+function buildValue(sValue) {
+  if (/^\s*$/.test(sValue)) { return null; }
+  if (/^(true|false)$/i.test(sValue)) { return sValue.toLowerCase() === "true"; }
+  if (isFinite(sValue)) { return parseFloat(sValue); }
+  if (isFinite(Date.parse(sValue))) { return new Date(sValue); }
+  return sValue;
+}
+
+if (window.location.search.length > 1) {
+  for (var aItKey, nKeyId = 0, aCouples = window.location.search.substr(1).split("&"); nKeyId < aCouples.length; nKeyId++) {
+    aItKey = aCouples[nKeyId].split("=");
+    oGetVars[unescape(aItKey[0])] = aItKey.length > 1 ? buildValue(unescape(aItKey[1])) : null;
+  }
+}
+
+// alert(oGetVars.yourVar);
+
+

…the same thing obtained by an anonymous constructor – useful for a global variable declaration:

+
var oGetVars = new (function (sSearch) {
+  var rNull = /^\s*$/, rBool = /^(true|false)$/i;
+  function buildValue(sValue) {
+    if (rNull.test(sValue)) { return null; }
+    if (rBool.test(sValue)) { return sValue.toLowerCase() === "true"; }
+    if (isFinite(sValue)) { return parseFloat(sValue); }
+    if (isFinite(Date.parse(sValue))) { return new Date(sValue); }
+    return sValue;
+  }
+  if (sSearch.length > 1) {
+    for (var aItKey, nKeyId = 0, aCouples = sSearch.substr(1).split("&"); nKeyId < aCouples.length; nKeyId++) {
+      aItKey = aCouples[nKeyId].split("=");
+      this[unescape(aItKey[0])] = aItKey.length > 1 ? buildValue(unescape(aItKey[1])) : null;
+    }
+  }
+})(window.location.search);
+
+// alert(oGetVars.yourVar);
+
+
Using bookmars without changing the window.location.hash property:
+
<!doctype html>
+<html>
+<head>
+<meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />
+<title>MDN Example</title>
+<script type="text/javascript">
+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) { window.location.hash = sBookmark; return; }
+  var oBookmark = document.querySelector(sBookmark);
+  if (oBookmark) { showNode(oBookmark); }
+}
+</script>
+<style type="text/css">
+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>
+
+
+ Note: The function showNode is also an example of the use of the for cycle without a statement section. In this case a semicolon is always put immediately after the declaration of the cycle.
+

…the same thing but with a dynamic page scroll:

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

See also

+

Manipulating the browser history

+

Browser compatibility

+

{{ CompatibilityTable() }}

+
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+

Specification

+

HTML Specification: window . location

+

{{ languages( { "fr": "fr/DOM/window.location", "ja": "ja/DOM/window.location" } ) }}

diff --git a/files/zh-tw/web/api/window/navigator/index.html b/files/zh-tw/web/api/window/navigator/index.html new file mode 100644 index 0000000000..f729c810a9 --- /dev/null +++ b/files/zh-tw/web/api/window/navigator/index.html @@ -0,0 +1,58 @@ +--- +title: Window.navigator +slug: Web/API/Window/navigator +translation_of: Web/API/Window/navigator +--- +
{{APIRef}}
+ +

The Window.navigator read-only property returns a reference to the {{domxref("Navigator")}} object, which can be queried for information about the application running the script.

+ +

語法

+ +
navigatorObject = window.navigator
+ +

範例

+ +

Example #1: Browser detect and return a 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("You are using: " + sBrowser);
+ +

Example #2: Browser detect and return an index

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

規範

+ + + +

參見

diff --git a/files/zh-tw/web/api/window/opener/index.html b/files/zh-tw/web/api/window/opener/index.html new file mode 100644 index 0000000000..e7ddb3e8c1 --- /dev/null +++ b/files/zh-tw/web/api/window/opener/index.html @@ -0,0 +1,30 @@ +--- +title: Window.opener +slug: Web/API/Window/opener +translation_of: Web/API/Window/opener +--- +
{{APIRef}}
+ +

概要

+ +

回傳一個開啟目前視窗(window)之視窗的參考(reference)。

+ +

語法

+ +
objRef = window.opener;
+
+ +

範例

+ +
if (window.opener != indexWin) {
+  referToTop(window.opener);
+}
+
+ +

備註

+ +

當一個視窗是由另一個視窗所開啟(使用 {{domxref("Window.open")}} 或一個帶有 target 屬性設定的連結),被開啟的這個視窗會於 window.opener 保留開啟它的第一個視窗之參考。假如目前的視窗沒有開啟它的視窗,則會回傳 NULL。

+ +

Windows Phone 瀏覽器不支援 window.opener(測試版本為 Microsoft Edge 25.10586.36.0)。若 window.opener 為不同的安全區域(security zone),則 IE 也不支援此屬性。

+ +

某些瀏覽器中,在發起連結的標籤中加入 rel="noopener" 屬性,可以阻止設定 window.opener 視窗參考。

diff --git a/files/zh-tw/web/api/window/orientationchange_event/index.html b/files/zh-tw/web/api/window/orientationchange_event/index.html new file mode 100644 index 0000000000..fe5264163c --- /dev/null +++ b/files/zh-tw/web/api/window/orientationchange_event/index.html @@ -0,0 +1,69 @@ +--- +title: 'Window: orientationchange event' +slug: Web/API/Window/orientationchange_event +tags: + - Sensors +translation_of: Web/API/Window/orientationchange_event +--- +
{{APIRef}}
+ +

orientationchange 事件在設備方向改變時被觸發。

+ + + + + + + + + + + + + + + + + + + + +
冒泡No
可取消No
介面{{domxref("Event")}}
事件處理器onorientationchange
+ +

範例

+ +

可於 addEventListener 方法中使用 abort 事件:

+ +
window.addEventListener("orientationchange", function() {
+  console.log("the orientation of the device is now " + screen.orientation.angle);
+});
+
+ +

或使用 onorientationchange 事件處理器屬性:

+ +
window.onorientationchange = function() {
+  console.log("the orientation of the device is now " + screen.orientation.angle);
+};
+ +

規範

+ + + + + + + + + + + + +
SpecificationStatus
{{SpecName('Compat', '#event-orientationchange', 'orientationchange')}}{{Spec2('Compat')}}
+ +

瀏覽器相容性

+ + + +

{{Compat("api.Window.orientationchange_event")}}

diff --git a/files/zh-tw/web/api/window/print/index.html b/files/zh-tw/web/api/window/print/index.html new file mode 100644 index 0000000000..4e2a543cf5 --- /dev/null +++ b/files/zh-tw/web/api/window/print/index.html @@ -0,0 +1,46 @@ +--- +title: Window.print() +slug: Web/API/Window/print +translation_of: Web/API/Window/print +--- +

{{ ApiRef() }}

+ +

摘要

+ +

打開列印視窗來列印當前的文件。

+ +

語法

+ +
window.print()
+
+ +

注釋

+ +

Starting with Chrome {{CompatChrome(46.0)}} this method is blocked inside an {{htmlelement("iframe")}} unless its sandbox attribute has the value allow-modals.

+ +

規範

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'timers-and-user-prompts.html#printing', 'print()')}}{{Spec2('HTML WHATWG')}} 
+ +

參見

+ + + +

{{ languages( { "ja": "ja/DOM/window.print", "it": "it/DOM/window.print" , "zh-cn": "zh-cn/DOM/window.print" } ) }}

diff --git a/files/zh-tw/web/api/window/requestidlecallback/index.html b/files/zh-tw/web/api/window/requestidlecallback/index.html new file mode 100644 index 0000000000..743e7b2a39 --- /dev/null +++ b/files/zh-tw/web/api/window/requestidlecallback/index.html @@ -0,0 +1,119 @@ +--- +title: window.requestIdleCallback() +slug: Web/API/Window/requestIdleCallback +translation_of: Web/API/Window/requestIdleCallback +--- +
{{APIRef("HTML DOM")}}{{SeeCompatTable}}
+ +

The window.requestIdleCallback() method queues a function to be called during a browser's idle periods. This enables developers to perform background and low priority work on the main event loop, without impacting latency-critical events such as animation and input response. Functions are generally called in first-in-first-out order; however, callbacks which have a timeout specified may be called out-of-order if necessary in order to run them before the timeout elapses.

+ +
+

You can call requestIdleCallback() within an idle callback function to schedule another callback to take place no sooner than the next pass through the event loop.

+
+ +

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 a {{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 timeout 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

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(47)}}{{CompatGeckoDesktop(53)}} [1]{{CompatNo}}{{CompatOpera(34)}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support{{CompatChrome(47)}}{{CompatChrome(47)}}{{CompatGeckoMobile(53)}} [1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] requestIdleCallback() is implemented in Firefox 53 but is disabled by default; to enable it, set the preference dom.requestIdleCallback.enabled to true. It is enabled by default starting in Firefox 55.

+ +

See also

+ + diff --git a/files/zh-tw/web/api/window/sessionstorage/index.html b/files/zh-tw/web/api/window/sessionstorage/index.html new file mode 100644 index 0000000000..696367e872 --- /dev/null +++ b/files/zh-tw/web/api/window/sessionstorage/index.html @@ -0,0 +1,94 @@ +--- +title: Window.sessionStorage +slug: Web/API/Window/sessionStorage +tags: + - API + - Property + - Storage + - WindowSessionStorage + - localStorage +translation_of: Web/API/Window/sessionStorage +--- +

{{APIRef()}}

+ +

sessionStorage 屬性能讓開發人員訪問當前 origin 的 {{DOMxRef("Storage")}} 物件。sessionStorage 跟 {{DOMxRef("Window.localStorage", "localStorage")}} 很相似:唯一不同的地方是存放在 localStorage 的資料並沒有過期的時效;而存放在 sessionStorage 的資料則會在頁面 session 結束時清空。只要該頁面頁面(頁籤)沒被關閉或者有還原(restore)該頁面,資料就會保存。開啟新頁籤或視窗會產生一個新的sessionStorage,跟Session與Cookies的做法不大一樣。 + +

+ +

另應該注意:不論資料放在 sessionStorage 還是 localStorage,都被限制在該網站的規範內,其他網站無法存取

+ +

語法

+ +
// 將資料存到sessionStorage
+sessionStorage.setItem('key', 'value');
+
+// 從sessionStorage取得之前存的資料
+var data = sessionStorage.getItem('key');
+
+// 從sessionStorage移除之前存的資料
+sessionStorage.removeItem('key');
+
+// 從sessionStorage移除之前存的所有資料
+sessionStorage.clear();
+
+ +

回傳值

+ +

一個 {{DOMxRef("Storage")}} 物件.

+ +

範例

+ +

下面簡短的程式碼,訪問了當前域名下的 session {{DOMxRef("Storage")}} 物件,並使用 {{DOMxRef("Storage.setItem()")}} 添加了資料單元。

+ +
sessionStorage.setItem('myCat', 'Tom');
+ +

以下提供的範例為將文字輸入元件的內容自動保存,如果瀏覽器不小心重新整理,在頁面恢復後,會自動將內容還原,不會造成尚未送出的資料被清空。

+ +
// 取得我們要保留內容的text field元件
+var field = document.getElementById("field");
+
+// 檢查是否有之前的autosave的內容
+// 這段程式碼會在瀏覽器進入該頁面時被執行
+if (sessionStorage.getItem("autosave")) {
+  // 還原先前的內容到指定的text field
+  field.value = sessionStorage.getItem("autosave");
+}
+
+// 註冊事件監聽text field內容的變化
+field.addEventListener("change", function() {
+  // 並儲存變化後的內容至sessionStorage的物件裡
+  sessionStorage.setItem("autosave", field.value);
+});
+ +
+

備註: 完整的範例可參考這篇文章: Using the Web Storage API

+
+ +

規格

+ + + + + + + + + + + + + + +
規格狀態註解
{{SpecName('HTML WHATWG', 'webstorage.html#dom-sessionstorage', 'sessionStorage')}}{{Spec2('HTML WHATWG')}} 
+ +

瀏覽器相容性

+ +

{{Compat("api.Window.sessionStorage")}}

+ + +

相關內容

+ + diff --git a/files/zh-tw/web/api/window/sidebar/adding_search_engines_from_web_pages/index.html b/files/zh-tw/web/api/window/sidebar/adding_search_engines_from_web_pages/index.html new file mode 100644 index 0000000000..020f1be65e --- /dev/null +++ b/files/zh-tw/web/api/window/sidebar/adding_search_engines_from_web_pages/index.html @@ -0,0 +1,35 @@ +--- +title: 自網頁添加搜尋引擎 +slug: Web/API/Window/sidebar/Adding_search_engines_from_Web_pages +tags: + - 搜尋模組 +translation_of: Web/OpenSearch +--- +

Firefox 可以用 JavaScript 安裝搜尋引擎模組,且支援 OpenSearch 及 Sherlock 兩種模組格式。 +

+
註: 自 Firefox 2 起,偏好的模組格式為 OpenSearch。
+

當 JavaScript 程式碼要安裝新的搜尋模組時,Firefox 會詢問使用者是否允許安裝。 +

+

安裝 OpenSearch 模組

+

要安裝 OpenSearch 模組,必須使用 window.external.AddSearchProvider() DOM 方法。此方法的語法為: +

+
window.external.AddSearchProvider(搜尋模組 URL);
+
+

其中 搜尋模組 URL 為搜尋引擎模組之 XML 檔的絕對連結 URL。 +

+
注意: OpenSearch 自 Firefox 2 起的版本才支援。
+

安裝 Sherlock 模組

+

要安裝 Sherlock 模組,必須叫用 window.sidebar.addSearchEngine() 方法,語法為: +

+
window.sidebar.addSearchEngine(搜尋模組 URL, 圖示 URL, 建議名稱, 建議分類);
+
+ +

Sherlock 的相關資訊可參考 http://developer.apple.com/macosx/sherlock/ +

+
+
+{{ languages( { "ca": "ca/Addici\u00f3_de_motors_de_cerca_a_les_p\u00e0gines_web", "en": "en/Adding_search_engines_from_web_pages", "es": "es/A\u00f1adir_motores_de_b\u00fasqueda_desde_p\u00e1ginas_web", "fr": "fr/Ajout_de_moteurs_de_recherche_depuis_des_pages_Web", "it": "it/Installare_plugin_di_ricerca_dalle_pagine_web", "ja": "ja/Adding_search_engines_from_web_pages", "pl": "pl/Dodawanie_wyszukiwarek_z_poziomu_stron_WWW" } ) }} diff --git a/files/zh-tw/web/api/window/sidebar/index.html b/files/zh-tw/web/api/window/sidebar/index.html new file mode 100644 index 0000000000..280b5dcce3 --- /dev/null +++ b/files/zh-tw/web/api/window/sidebar/index.html @@ -0,0 +1,56 @@ +--- +title: Window.sidebar +slug: Web/API/Window/sidebar +tags: + - DOM + - NeedsTranslation + - Non-standard + - Property + - Reference + - TopicStub + - Window +translation_of: Web/API/Window/sidebar +--- +
{{APIRef}} {{Non-standard_header}}
+ +

Returns a sidebar object, which contains several methods for registering add-ons with the browser.

+ +

Notes

+ +

The sidebar object returned has the following methods:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
MethodDescription (SeaMonkey)Description (Firefox)
addPanel(title, contentURL, "")Adds a sidebar panel.Obsolete since Firefox 23 (only present in SeaMonkey).
+ End users can use the "load this bookmark in the sidebar" option instead. Also see Creating a Firefox sidebar.
addPersistentPanel(title, contentURL, "")Adds a sidebar panel, which is able to work in the background.
AddSearchProvider(descriptionURL)Installs a search provider (OpenSearch). Adding OpenSearch search engines contains more details. Added in Firefox 2.
addSearchEngine(engineURL, iconURL, suggestedTitle, suggestedCategory) {{Obsolete_inline(44)}}Installs a search engine (Sherlock). Adding Sherlock search engines contains more details.
IsSearchProviderInstalled(descriptionURL)Indicates if a specific search provider (OpenSearch) is installed.
+ +

Specification

+ +

Mozilla-specific. Not part of any standard.

diff --git a/files/zh-tw/web/api/windowbase64/index.html b/files/zh-tw/web/api/windowbase64/index.html new file mode 100644 index 0000000000..804f10ab1a --- /dev/null +++ b/files/zh-tw/web/api/windowbase64/index.html @@ -0,0 +1,113 @@ +--- +title: WindowBase64 +slug: Web/API/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.

+ +

屬性

+ +

This helper neither defines nor inherits any properties.

+ +

方法

+ +

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

規範

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

瀏覽器相容性

+ +

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

+ +

參見

+ + diff --git a/files/zh-tw/web/api/windoweventhandlers/index.html b/files/zh-tw/web/api/windoweventhandlers/index.html new file mode 100644 index 0000000000..d3d29ddb63 --- /dev/null +++ b/files/zh-tw/web/api/windoweventhandlers/index.html @@ -0,0 +1,182 @@ +--- +title: WindowEventHandlers +slug: Web/API/WindowEventHandlers +translation_of: Web/API/WindowEventHandlers +--- +
{{APIRef("HTML DOM")}}
+ +

WindowEventHandlers mixin describes the event handlers common to several interfaces like {{domxref("Window")}}, or {{domxref("HTMLBodyElement")}} and  {{domxref("HTMLFrameSetElement")}}. Each of these interfaces can implement additional specific event handlers.

+ +

WindowEventHandlers is a not an interface and no object of this type can be created.

+ +

屬性

+ +

The events properties, of the form onXYZ, are defined on the {{domxref("WindowEventHandlers")}}, and implemented by {{domxref("Window")}}, and {{domxref("WorkerGlobalScope")}} for Web Workers.

+ +
+
{{domxref("WindowEventHandlers.onafterprint")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("afterprint")}} event is raised.
+
{{domxref("WindowEventHandlers.onbeforeprint")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("beforeprint")}} event is raised.
+
{{domxref("WindowEventHandlers.onbeforeunload")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("beforeunload")}} event is raised.
+
{{domxref("WindowEventHandlers.onhashchange")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("hashchange")}} event is raised.
+
{{domxref("WindowEventHandlers.onlanguagechange")}} {{experimental_inline}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("languagechange")}} event is raised.
+
{{domxref("WindowEventHandlers.onmessage")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("message")}} event is raised.
+
{{domxref("WindowEventHandlers.onoffline")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("offline")}} event is raised.
+
{{domxref("WindowEventHandlers.ononline")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("online")}} event is raised.
+
{{domxref("WindowEventHandlers.onpagehide")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("pagehide")}} event is raised.
+
{{domxref("WindowEventHandlers.onpageshow")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("pageshow")}} event is raised.
+
{{domxref("WindowEventHandlers.onpopstate")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("popstate")}} event is raised.
+
{{domxref("WindowEventHandlers.onstorage")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("storage")}} event is raised.
+
{{domxref("WindowEventHandlers.onunhandledrejection")}} {{experimental_inline}}
+
An event handler for unhandled {{jsxref("Promise")}} rejection events.
+
{{domxref("WindowEventHandlers.onunload")}}
+
Is an {{domxref("EventHandler")}} representing the code to be called when the {{event("unload")}} event is raised.
+
+ +

方法

+ +

This interface defines no method.

+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
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("HTML5 W3C")}} snapshot.
{{SpecName("HTML5 W3C", "#windoweventhandlers", "GlobalEventHandlers")}}{{Spec2('HTML5 W3C')}}Snapshot of {{SpecName("HTML WHATWG")}}. Creation of WindowEventHandlers (properties where on the target before it).
+ +

瀏覽器相容性

+ +

{{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{{CompatGeckoDesktop(45)}}{{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{{CompatGeckoDesktop(45)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

參見

+ + diff --git a/files/zh-tw/web/api/windoweventhandlers/onbeforeunload/index.html b/files/zh-tw/web/api/windoweventhandlers/onbeforeunload/index.html new file mode 100644 index 0000000000..66ba170df5 --- /dev/null +++ b/files/zh-tw/web/api/windoweventhandlers/onbeforeunload/index.html @@ -0,0 +1,153 @@ +--- +title: WindowEventHandlers.onbeforeunload +slug: Web/API/WindowEventHandlers/onbeforeunload +translation_of: Web/API/WindowEventHandlers/onbeforeunload +--- +
+
{{APIRef("HTML DOM")}}
+
+ +
 
+ +

WindowEventHandlers.onbeforeunload 事件处理函数包含的代码将在 {{event("beforeunload")}} 发出时被执行。当 window 准备释放它的资源时,该事件被触发。此时 document 仍然可见,且事件是仍然可被取消的。

+ +
+

注意: 为了避免不必要的弹出窗口,除非页面已经有过互动,否则可能不会显示beforeunload创建的询问窗口。对于特定的浏览器列表,请参阅浏览器兼容性部分。

+
+ +

语法

+ +
window.onbeforeunload = funcRef
+ + + +

示例

+ +
window.onbeforeunload = function(e) {
+  var dialogText = 'Dialog text here';
+  e.returnValue = dialogText;
+  return dialogText;
+};
+
+ +

注意

+ +

当事件返回了一个非空值时,将需要用户确认是否 unload 页面。在大部分浏览器中,事件的返回值将在对话框中显示。在 Firefox 4 及以后,返回值将不会显示给用户。作为替代,Firefox将会显示"This page is asking you to confirm that you want to leave - data you have entered may not be saved." 请查看{{bug("588292")}}.

+ +

Since 25 May 2011, the HTML5 specification states that calls to {{domxref("window.alert()")}}, {{domxref("window.confirm()")}}, and {{domxref("window.prompt()")}} methods may be ignored during this event. See the HTML5 specification for more details.

+ +

Note also that various mobile browsers ignore the result of the event (that is, they do not ask the user for confirmation). Firefox has a hidden preference in about:config to do the same. In essence this means the user always confirms that the document may be unloaded.

+ +

You can and should handle this event through {{domxref("EventTarget.addEventListener","window.addEventListener()")}} and the {{event("beforeunload")}} event. More documentation is available there.

+ +

Specifications

+ +

The event was originally introduced by Microsoft in Internet Explorer 4 and standardized in the HTML5 specification.

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#windoweventhandlers', 'GlobalEventHandlers')}}{{Spec2('HTML WHATWG')}} 
{{SpecName('HTML5.1', '#windoweventhandlers', 'GlobalEventHandlers')}}{{Spec2('HTML5.1')}} 
{{SpecName("HTML5 W3C", "#windoweventhandlers", "GlobalEventHandlers")}}{{Spec2('HTML5 W3C')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(1.0)}}14123
Custom text support removed{{CompatChrome(51.0)}}{{CompatGeckoMobile("44.0")}} 389.1
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}(no) defect{{CompatVersionUnknown}}
Custom text support removed{{CompatUnknown}}{{CompatChrome(51.0)}}{{CompatGeckoMobile("44.0")}}   {{CompatChrome(51.0)}}
+
+ +

See also

+ + diff --git a/files/zh-tw/web/api/windoworworkerglobalscope/btoa/index.html b/files/zh-tw/web/api/windoworworkerglobalscope/btoa/index.html new file mode 100644 index 0000000000..93d63b6010 --- /dev/null +++ b/files/zh-tw/web/api/windoworworkerglobalscope/btoa/index.html @@ -0,0 +1,136 @@ +--- +title: WindowOrWorkerGlobalScope.btoa() +slug: Web/API/WindowOrWorkerGlobalScope/btoa +translation_of: Web/API/WindowOrWorkerGlobalScope/btoa +--- +

{{APIRef("HTML DOM")}}

+ +

The WindowOrWorkerGlobalScope.btoa() method creates a {{glossary("Base64")}}-encoded ASCII string from a binary string (i.e., a {{jsxref("String")}} object in which each character in the string is treated as a byte of binary data).

+ +

You can use this method to encode data which may otherwise cause communication problems, transmit it, then use the {{domxref("WindowOrWorkerGlobalScope.atob", "atob()")}} method to decode the data again. For example, you can encode control characters such as ASCII values 0 through 31.

+ +

Syntax

+ +
var encodedData = scope.btoa(stringToEncode);
+ +

Parameters

+ +
+
stringToEncode
+
The binary string to encode.
+
+ +

Return value

+ +

An ASCII string containing the Base64 representation of stringToEncode.

+ +

Exceptions

+ +
+
InvalidCharacterError
+
The string contained a character that did not fit in a single byte. See "Unicode strings" below for more detail.
+
+ +

Example

+ +
const encodedData = window.btoa('Hello, world'); // encode a string
+const decodedData = window.atob(encodedData); // decode the string
+
+ +

Unicode strings

+ +

The btoa() function takes a JavaScript string as a parameter. In JavaScript strings are represented using the UTF-16 character encoding: in this encoding, strings are represented as a sequence of 16-bit (2 byte) units. Every ASCII character fits into the first byte of one of these units, but many other characters don't.

+ +

Base64, by design, expects binary data as its input. In terms of JavaScript strings, this means strings in which each character occupies only one byte. So if you pass a string into btoa() containing characters that occupy more than one byte, you will get an error, because this is not considered binary data:

+ +
const ok = "a";
+console.log(ok.codePointAt(0).toString(16)); //   61: occupies < 1 byte
+
+const notOK = "✓"
+console.log(notOK.codePointAt(0).toString(16)); // 2713: occupies > 1 byte
+
+console.log(btoa(ok));    // YQ==
+console.log(btoa(notOK)); // error
+ +

If you need to encode Unicode text as ASCII using btoa(), one option is to convert the string such that each 16-bit unit occupies only one byte. For example:

+ +
// convert a Unicode string to a string in which
+// each 16-bit unit occupies only one byte
+function toBinary(string) {
+  const codeUnits = new Uint16Array(string.length);
+  for (let i = 0; i < codeUnits.length; i++) {
+    codeUnits[i] = string.charCodeAt(i);
+  }
+  return String.fromCharCode(...new Uint8Array(codeUnits.buffer));
+}
+
+// a string that contains characters occupying > 1 byte
+const myString = "☸☹☺☻☼☾☿";
+
+const converted = toBinary(myString);
+const encoded = btoa(converted);
+console.log(encoded);                 // OCY5JjomOyY8Jj4mPyY=
+
+ +

If you do this, of course you'll have to reverse the conversion on the decoded string:

+ +
function fromBinary(binary) {
+  const bytes = new Uint8Array(binary.length);
+  for (let i = 0; i < bytes.length; i++) {
+    bytes[i] = binary.charCodeAt(i);
+  }
+  return String.fromCharCode(...new Uint16Array(bytes.buffer));
+}
+
+const decoded = atob(encoded);
+const original = fromBinary(decoded);
+console.log(original);                // ☸☹☺☻☼☾☿
+
+ +

Polyfill

+ +

You can use a polyfill from https://github.com/MaxArt2501/base64-js/blob/master/base64.js for browsers that don't support it.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#dom-btoa', 'WindowOrWorkerGlobalScope.btoa()')}}{{Spec2('HTML WHATWG')}}Method moved to the WindowOrWorkerGlobalScope mixin in the latest spec.
{{SpecName('HTML5.1', '#dom-windowbase64-btoa', 'WindowBase64.btoa()')}}{{Spec2('HTML5.1')}}Snapshot of {{SpecName("HTML WHATWG")}}. No change.
{{SpecName("HTML5 W3C", "#dom-windowbase64-btoa", "WindowBase64.btoa()")}}{{Spec2('HTML5 W3C')}}Snapshot of {{SpecName("HTML WHATWG")}}. Creation of WindowBase64 (properties where on the target before it).
+ +

Browser compatibility

+ +
+ + +

{{Compat("api.WindowOrWorkerGlobalScope.btoa")}}

+
+ +

See also

+ + diff --git a/files/zh-tw/web/api/windoworworkerglobalscope/index.html b/files/zh-tw/web/api/windoworworkerglobalscope/index.html new file mode 100644 index 0000000000..9fb46d21d5 --- /dev/null +++ b/files/zh-tw/web/api/windoworworkerglobalscope/index.html @@ -0,0 +1,98 @@ +--- +title: WindowOrWorkerGlobalScope +slug: Web/API/WindowOrWorkerGlobalScope +tags: + - API + - HTML DOM + - NeedsTranslation + - Service Worker + - TopicStub + - Window + - WindowOrWorkerGlobalScope + - Worker + - WorkerGlobalScope +translation_of: Web/API/WindowOrWorkerGlobalScope +--- +
{{ApiRef()}}
+ +

The WindowOrWorkerGlobalScope mixin describes several features common to the {{domxref("Window")}} and {{domxref("WorkerGlobalScope")}} interfaces. Each of these interfaces can, of course, add more features in addition to the ones listed below.

+ +
+

Note: WindowOrWorkerGlobalScope is a mixin and not an interface; you can't actually create an object of type 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.crossOriginIsolated")}} {{readOnlyinline}}
+
Returns a boolean value that indicates whether a {{jsxref("SharedArrayBuffer")}} can be sent via a {{domxref("Window.postMessage()")}} call.
+
{{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 methods 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.queueMicrotask()")}}
+
Enqueues a microtask—a short function to be executed after execution of the JavaScript code completes and control isn't being returned to a JavaScript caller, but before handling callbacks and other tasks. This lets your code run without interfering with other, possibly higher priority, code, but before the browser runtime regains control, potentially depending upon the work you need to complete.
+
{{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.
+ +

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/zh-tw/web/api/windoworworkerglobalscope/setinterval/index.html b/files/zh-tw/web/api/windoworworkerglobalscope/setinterval/index.html new file mode 100644 index 0000000000..7685a8f754 --- /dev/null +++ b/files/zh-tw/web/api/windoworworkerglobalscope/setinterval/index.html @@ -0,0 +1,627 @@ +--- +title: WindowOrWorkerGlobalScope.setInterval() +slug: Web/API/WindowOrWorkerGlobalScope/setInterval +translation_of: Web/API/WindowOrWorkerGlobalScope/setInterval +--- +
{{APIRef("HTML DOM")}}
+ +

setInterval() 函式, {{domxref("Window")}} 與 {{domxref("Worker")}} 介面皆提供此一函式, 此函式作用為重複地執行一個函式呼叫或一個程式碼片斷, 每一次執行間隔固定的延遲時間. 此函式呼叫時將傳回一個間隔代碼(Interval ID)用以識別該間隔程序, 因此後續您可以呼叫 {{domxref("WindowOrWorkerGlobalScope.clearInterval", "clearInterval()")}} 函式移除該間隔程序. 此函式為由 {{domxref("WindowOrWorkerGlobalScope")}} 混合定義.

+ +

Syntax

+ +
var intervalID = scope.setInterval(func, [delay, arg1, arg2, ...]);
+var intervalID = scope.setInterval(code, [delay]);
+
+ +

Parameters

+ +
+
func
+
A {{jsxref("function")}} to be executed every delay milliseconds. The function is not passed any arguments, and no return value is expected.
+
code
+
An optional syntax allows you to include a string instead of a function, which is compiled and executed every delay milliseconds. This syntax is not recommended for the same reasons that make using {{jsxref("eval", "eval()")}} a security risk.
+
delay{{optional_inline}}
+
The time, in milliseconds (thousandths of a second), the timer should delay in between executions of the specified function or code. See {{anch("Delay restrictions")}} below for details on the permitted range of delay values.
+
arg1, ..., argN {{optional_inline}}
+
Additional arguments which are passed through to the function specified by func once the timer expires.
+
+ +
+

Note: Passing additional arguments 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

+ +

The returned intervalID is a numeric, non-zero value which identifies the timer created by the call to setInterval(); this value can be passed to {{domxref("WindowOrWorkerGlobalScope.clearInterval()")}} to cancel the timeout.

+ +

It may be helpful to be aware that setInterval() and {{domxref("WindowOrWorkerGlobalScope.setTimeout", "setTimeout()")}} share the same pool of IDs, and that clearInterval() and {{domxref("WindowOrWorkerGlobalScope.clearTimeout", "clearTimeout()")}} can technically be used interchangeably. For clarity, however, you should try to always match them to avoid confusion when maintaining your code.

+ +
Note: The delay argument 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.
+ +

Examples

+ +

Example 1: Basic syntax

+ +

The following example demonstrates setInterval()'s basic syntax.

+ +
var intervalID = window.setInterval(myCallback, 500, 'Parameter 1', 'Parameter 2');
+
+function myCallback(a, b)
+{
+ // Your code here
+ // Parameters are purely optional.
+ console.log(a);
+ console.log(b);
+}
+
+ +

Example 2: Alternating two colors

+ +

The following example calls the flashtext() function once a second until the Stop button is pressed.

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

Example 3: Typewriter simulation

+ +

The following example simulates typewriter by first clearing and then slowly typing content into the NodeList that matches a specified group of selectors.

+ +
<!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().

+ +

Callback arguments

+ +

As previously discussed, Internet Explorer versions 9 and below do not support the passing of arguments to the callback function in either setTimeout() or setInterval(). The following IE-specific code demonstrates a method for overcoming this limitation.  To use, simply add the following code to the top of your 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[, arg1, arg2, ...]);
+|*|  var timeoutID = window.setTimeout(code, delay);
+|*|  var intervalID = window.setInterval(func, delay[, arg1, arg2, ...]);
+|*|  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;
+}
+
+ +

Another possibility is to use an anonymous function to call your callback, although this solution is a bit more expensive. Example:

+ +
var intervalID = setInterval(function() { myFunc('one', 'two', 'three'); }, 1000);
+ +

Another possibility is to use function's bind. Example:

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

+ +

The "this" problem

+ +

When you pass a method to setInterval() or any other function, it is invoked with the wrong this value. This problem is explained in detail in the JavaScript reference.

+ +

Explanation

+ +

Code executed by setInterval() runs in a separate execution context than the function from which it was called. As a consequence, the this keyword for the called function is set to the window (or global) object, it is not the same as the this value for the function that called setTimeout. See the following example (which uses setTimeout() instead of setInterval() – the problem, in fact, is the same for both timers):

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

As you can see there are no ways to pass the this object to the callback function in the legacy JavaScript.

+ +

A possible solution

+ +

A possible way to solve the "this" problem is to replace the two native setTimeout() or setInterval() global functions with two non-native ones that enable their invocation through the Function.prototype.call method. The following example shows a possible replacement:

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

New feature test:

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

Another, more complex, solution for the this problem is 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).

+ +

Arguments

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

+ +

Usage 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()")}}.

+ +

Delay restrictions

+ +

It's possible for intervals to be nested; that is, the callback for setInterval() can in turn call setInterval() to start another interval running, even though the first one is still going. To mitigate the potential impact this can have on performance, once intervals are nested beyond five levels deep, the browser will automatically enforce a 4 ms minimum value for the interval. Attempts to specify a value less than 4 ms in deeply-nested calls to setInterval() will be pinned to 4 ms.

+ +

Browsers may enforce even more stringent minimum values for the interval under some circumstances, although these should not be common. Note also that the actual amount of time that elapses between calls to the callback may be longer than the given delay; see {{SectionOnPage("/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout", "Reasons for delays longer than specified")}} for examples.

+ +

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", "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.

+ +

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/zh-tw/web/api/windowtimers/index.html b/files/zh-tw/web/api/windowtimers/index.html new file mode 100644 index 0000000000..0b26118e10 --- /dev/null +++ b/files/zh-tw/web/api/windowtimers/index.html @@ -0,0 +1,114 @@ +--- +title: WindowTimers +slug: Web/API/WindowTimers +translation_of: Web/API/WindowOrWorkerGlobalScope +--- +
{{APIRef("HTML DOM")}}
+ +

WindowTimers is a mixin used to provide utility methods which set and clear timers. No objects of this type exist; instead, its methods are available on {{domxref("Window")}} for the standard browsing scope, or on {{domxref("WorkerGlobalScope")}} for workers.

+ +

屬性

+ +

WindowTimers 介面沒有繼承也沒有定義任何屬性。

+ +

方法

+ +

除以下自身方法外,WindowTimers 介面提沒有任何繼承方法。

+ +
+
{{domxref("WindowTimers.clearInterval()")}}
+
Cancels the repeated execution set using {{domxref("WindowTimers.setInterval()")}}.
+
{{domxref("WindowTimers.clearTimeout()")}}
+
Cancels the delayed execution set using {{domxref("WindowTimers.setTimeout()")}}.
+
{{domxref("WindowTimers.setInterval()")}}
+
Schedules a function to execute every time a given number of milliseconds elapses.
+
{{domxref("WindowTimers.setTimeout()")}}
+
Schedules a function to execute in a given amount of time.
+
+ +

規範

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

瀏覽器相容性

+ +

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

 

+ +

參見

+ + diff --git a/files/zh-tw/web/api/xmlhttprequest/index.html b/files/zh-tw/web/api/xmlhttprequest/index.html new file mode 100644 index 0000000000..3258579e62 --- /dev/null +++ b/files/zh-tw/web/api/xmlhttprequest/index.html @@ -0,0 +1,177 @@ +--- +title: XMLHttpRequest +slug: Web/API/XMLHttpRequest +tags: + - AJAX + - Fixit + - HTTP + - MakeBrowserAgnostic + - NeedsCleanup + - NeedsMobileBrowserCompatibility + - NeedsTranslation + - TopicStub + - XMLHttpRequest +translation_of: Web/API/XMLHttpRequest +--- +
{{DefaultAPISidebar("XMLHttpRequest")}}
+ +

藉由 XMLHttpRequest(XHR)物件的方式來存取伺服器端的資料,可以讓你直接經由指定的 URL 擷取資料卻不用刷新整個網頁。這樣一來當想要更新網頁中的部分資料時,不再需要藉由刷新整個頁面的方法而中斷使用者的操作。在{{Glossary("AJAX")}}應用中 XMLHttpRequest 被大量的使用。

+ +

{{InheritanceDiagram(650, 150)}}

+ +

雖然 XMLHttpRequest 這個物件的命名包含了 XML 與 HTTP 等字眼,但實際上 XMLHttpRequest 可用來接收任何類型的資料,不限於 XML 類型而已。

+ +

如果在資料交換的時候,需要接收從伺服器端傳來的事件或訊息:可以考慮透過{{domxref("EventSource")}}介面使用server-sent 事件。對於和伺服器全雙工的資訊交換,WebSockets 可能是較佳的選擇。

+ +

建構式

+ +
+
{{domxref("XMLHttpRequest.XMLHttpRequest", "XMLHttpRequest()")}}
+
建構式用來初始化一個 XMLHttpRequest 物件。必須在其他任何所屬方法被呼叫之前被呼叫。
+
+ +

屬性

+ +

此介面也繼承了 {{domxref("XMLHttpRequestEventTarget")}} 及 {{domxref("EventTarget")}} 的屬性。

+ +
+
{{domxref("XMLHttpRequest.onreadystatechange")}}
+
一個 {{domxref("EventHandler")}}(事件處理器)函式,會於 readyState 屬性之狀態改變時被呼叫。
+
{{domxref("XMLHttpRequest.readyState")}} {{readonlyinline}}
+
回傳一個無符號短整數(unsigned short)代表請求之狀態。
+
{{domxref("XMLHttpRequest.response")}} {{readonlyinline}}
+
回傳的內容可能是 {{domxref("ArrayBuffer")}}、{{domxref("Blob")}}、{{domxref("Document")}}、JavaScript 物件或 {{domxref("DOMString")}}。完全根據 {{domxref("XMLHttpRequest.responseType")}} 的值決定回傳的內容為何種型態,資料為回應實體中的內容(response entity body)。
+
{{domxref("XMLHttpRequest.responseText")}} {{readonlyinline}}
+
回傳一個 {{domxref("DOMString")}},其內容為請求之回應的文字內容。如請求失敗或尚未發送,則為 null
+
{{domxref("XMLHttpRequest.responseType")}}
+
為一可列舉(enumerated)值,定義回應內容的資料類型(response type)。
+
{{domxref("XMLHttpRequest.responseURL")}} {{readonlyinline}}
+
回傳一個回應(response)的序列化 URL,如 URL 為 null 則回傳空字串。
+
{{domxref("XMLHttpRequest.responseXML")}} {{readonlyinline}}
+
回傳一個 {{domxref("Document")}},其內容為請求之回應內容所解析成的文件物件。如請求失敗或尚未發送,又或是無法解析成 XML、HTML,則為 null。Not available in workers.
+
{{domxref("XMLHttpRequest.status")}} {{readonlyinline}}
+
回傳一個無符號短整數(unsigned short)表示已發送請求之回應的狀態。
+
{{domxref("XMLHttpRequest.statusText")}} {{readonlyinline}}
+
回傳一個 {{domxref("DOMString")}} 表示 HTTP 伺服器回應之字串。和 {{domxref("XMLHTTPRequest.status")}} 不同的是,XMLHttpRequest.statusText 包含了回應的整個文字訊息(如 "200 OK")。
+
+ +
+

Note: The HTTP/2 specification (8.1.2.4 Response Pseudo-Header Fields), HTTP/2 does not define a way to carry the version or reason phrase that is included in an HTTP/1.1 status line.

+
+ +
+
{{domxref("XMLHttpRequest.timeout")}}
+
為一無符號長整數(unsigned long),代表一個請求在逾時而被自動中止前的可等待時間(毫秒)。
+
{{domxref("XMLHttpRequestEventTarget.ontimeout")}}
+
為一 {{domxref("EventHandler")}} 物件,會於請求逾時時被呼叫。{{gecko_minversion_inline("12.0")}}
+
{{domxref("XMLHttpRequest.upload")}} {{readonlyinline}}
+
為一 {{domxref("XMLHttpRequestUpload")}} 物件,代表上傳的進度。
+
{{domxref("XMLHttpRequest.withCredentials")}}
+
{{domxref("Boolean","布林值")}}。表示是否允許在跨站存取(cross-site Access-Control)之請求當中,發送如 cookies 或 authorization headers 等憑證資訊(credentials)。
+
+ +

非標準屬性

+ +
+
{{domxref("XMLHttpRequest.channel")}}{{ReadOnlyInline}}
+
是一個 {{Interface("nsIChannel")}}。當執行要求時,物件使用的頻道(Channel)。
+
{{domxref("XMLHttpRequest.mozAnon")}}{{ReadOnlyInline}}
+
為一個布林值。如果為真,請求就會以沒有cookie及authentication headers的方式送出。
+
{{domxref("XMLHttpRequest.mozSystem")}}{{ReadOnlyInline}}
+
這是一個布林值。If true, the same origin policy will not be enforced on the request.
+
{{domxref("XMLHttpRequest.mozBackgroundRequest")}}
+
這是一個布林值。指出該物件是否為一個背景型態的服務要求。
+
{{domxref("XMLHttpRequest.mozResponseArrayBuffer")}}{{gecko_minversion_inline("2.0")}} {{obsolete_inline("6")}} {{ReadOnlyInline}}
+
Is an ArrayBuffer. The response to the request, as a JavaScript typed array.
+
{{domxref("XMLHttpRequest.multipart")}}{{obsolete_inline("22")}}
+
This Gecko-only feature, a boolean, was removed in Firefox/Gecko 22. Please use Server-Sent Events, Web Sockets, or responseText from progress events instead.
+
+ +

事件處理器

+ +

所有瀏覽器都支援 XMLHttpRequest 物件實體的 onreadystatechange 屬性。

+ +

之後,各個瀏覽器實作了多種額外的事件處理器(如 onloadonerroronprogress 等)。請參考使用 XMLHttpRequest

+ +

除了以 on* 屬性來設定事件處理函式,更多現代覽瀏器(包括 Firefox)也支援使用標準的 addEventListener() API 註冊監聽 XMLHttpRequest 的事件。

+ +
+
+ +

方法

+ +
+
{{domxref("XMLHttpRequest.abort()")}}
+
中止已發出的請求。
+
{{domxref("XMLHttpRequest.getAllResponseHeaders()")}}
+
回傳所有的回應標頭(response headers),為一以斷行字元(CRLF)分行的字串,如未接收到回應則為 null
+
{{domxref("XMLHttpRequest.getResponseHeader()")}}
+
回傳指定標頭文字之字串,假如回應尚未被接收或是標頭不存在於回應中則為 null
+
{{domxref("XMLHttpRequest.open()")}}
+
初始化一個請求。此方法用於 JavaScript 中;若要在 native code 中初始化請求,請以 openRequest() 作為替代。
+
{{domxref("XMLHttpRequest.overrideMimeType()")}}
+
覆寫伺服器回傳的 MIME type。
+
{{domxref("XMLHttpRequest.send()")}}
+
發送請求。如果為非同步請求(預設值),此方法將在發出請求後便立即回傳(return)。
+
{{domxref("XMLHttpRequest.setRequestHeader()")}}
+
設定 HTTP 請求標頭(request header)值。setRequestHeader() 可被呼叫的時間點必須於 open() 之後、在 send() 之前。
+
+ +

非標準方法

+ +
+
{{domxref("XMLHttpRequest.init()")}}
+
使用 C++ 程式時,用來初始化這個物件。
+
+ +
注意: 請勿在 JavaScript 中呼叫這個方法。
+ +
+
{{domxref("XMLHttpRequest.openRequest()")}}
+
初始化請求。這方法是用於原生程式,若想在 JavaScript 中初始化一個請求,請使用 open() 這個方法來代替。請參照 open() 的相關文件。
+
{{domxref("XMLHttpRequest.sendAsBinary()")}}{{deprecated_inline()}}
+
另一種 send() 方法,用來送出二進位資料。
+
+ +

規範

+ + + + + + + + + + + + + + +
規範狀態註解
{{SpecName('XMLHttpRequest')}}{{Spec2('XMLHttpRequest')}}Live standard, latest version
+ +

瀏覽器相容性

+ + + +
{{Compat("api.XMLHttpRequest")}}
+ +

參見

+ + diff --git a/files/zh-tw/web/api/xmlhttprequest/onreadystatechange/index.html b/files/zh-tw/web/api/xmlhttprequest/onreadystatechange/index.html new file mode 100644 index 0000000000..817daf0efa --- /dev/null +++ b/files/zh-tw/web/api/xmlhttprequest/onreadystatechange/index.html @@ -0,0 +1,113 @@ +--- +title: XMLHttpRequest.onreadystatechange +slug: Web/API/XMLHttpRequest/onreadystatechange +translation_of: Web/API/XMLHttpRequest/onreadystatechange +--- +
{{APIRef}}
+ +

An EventHandler that is called whenever the readyState attribute changes. The callback is called from the user interface thread. The XMLHttpRequest.onreadystatechange property contains the event handler to be called when the {{event("readystatechange")}} event is fired, that is every time the {{domxref("XMLHttpRequest.readyState", "readyState")}} property of the {{domxref("XMLHttpRequest")}} changes.

+ +
+

Warning: This should not be used with synchronous requests and must not be used from native code.

+
+ +

The readystatechange event will not be fired when an XMLHttpRequest request is cancelled with the abort() method.

+ +
+

UPDATE: it's firing in the latest version of browsers (Firefox 51.0.1, Opera 43.0.2442.991, Safari 10.0.3 (12602.4.8), Chrome 54.0.2840.71, Edge, IE11). Example here - just reaload page few times.

+
+ +

語法

+ +
XMLHttpRequest.onreadystatechange = callback;
+ +

+ + + +

範例

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

規範

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('XMLHttpRequest', '#handler-xhr-onreadystatechange')}}{{Spec2('XMLHttpRequest')}}WHATWG living standard
+ +

瀏覽器相容性

+ +

{{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 version 5 and 6 supported ajax calls using ActiveXObject().

diff --git a/files/zh-tw/web/api/xmlhttprequest/readystate/index.html b/files/zh-tw/web/api/xmlhttprequest/readystate/index.html new file mode 100644 index 0000000000..3f7e909fe0 --- /dev/null +++ b/files/zh-tw/web/api/xmlhttprequest/readystate/index.html @@ -0,0 +1,148 @@ +--- +title: XMLHttpRequest.readyState +slug: Web/API/XMLHttpRequest/readyState +translation_of: Web/API/XMLHttpRequest/readyState +--- +

{{APIRef('XMLHttpRequest')}}

+ +

XMLHttpRequest.readyState 屬性會回傳一個 XMLHttpRequest 客戶端物件目前的狀態。一個 XHR 客戶端可以為下列其中一種狀態:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
狀態說明
0UNSENT客戶端已被建立,但 open() 方法尚未被呼叫。
1OPENEDopen() 方法已被呼叫。
2HEADERS_RECEIVEDsend() 方法已被呼叫,而且可取得 header 與狀態。
3LOADING回應資料下載中,此時 responseText 會擁有部分資料。
4DONE完成下載操作。
+ +
+
UNSENT
+
XMLHttpRequest 客戶端物件已被建立,但 open() 方法尚未被呼叫。
+
OPENED
+
open() 方法已被呼叫。於此狀態時,可以使用 setRequestHeader() 方法設定請求標頭(request headers),並可呼叫 send() 方法來發送請求。
+
HEADERS_RECEIVED
+
send() 方法已被呼叫,並且已接收到回應標頭(response header)。
+
LOADING
+
正在接收回應內容(response's body)。如 responseType 屬性為 "text" 或空字串,則 responseText 屬性將會在載入的過程中擁有已載入部分之回應(response)內容中的文字。
+
DONE
+
請求操作已完成。這意味著資料傳輸可能已成功完成或是已失敗。
+
+ +
+

這些狀態名稱在 Internet Explorer 中略有不同。其中 UNSENT, OPENED, HEADERS_RECEIVED, LOADING 和 DONE 變成了 READYSTATE_UNINITIALIZED (0), READYSTATE_LOADING (1), READYSTATE_LOADED (2), READYSTATE_INTERACTIVE (3) 和READYSTATE_COMPLETE (4)。

+
+ +

範例

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

規範

+ + + + + + + + + + + + + + +
規範狀態註解
{{SpecName('XMLHttpRequest', '#states')}}{{Spec2('XMLHttpRequest')}}WHATWG living standard
+ +

瀏覽器相容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
功能ChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
基本支援{{CompatChrome(1)}}{{CompatGeckoDesktop("1.0")}}[1]{{CompatIe(7)}}{{CompatVersionUnknown}}{{CompatSafari("1.2")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
功能AndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
基本支援{{CompatUnknown}}1.0{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
diff --git a/files/zh-tw/web/api/xmlhttprequest/setrequestheader/index.html b/files/zh-tw/web/api/xmlhttprequest/setrequestheader/index.html new file mode 100644 index 0000000000..a8219e7240 --- /dev/null +++ b/files/zh-tw/web/api/xmlhttprequest/setrequestheader/index.html @@ -0,0 +1,66 @@ +--- +title: XMLHttpRequest.setRequestHeader() +slug: Web/API/XMLHttpRequest/setRequestHeader +translation_of: Web/API/XMLHttpRequest/setRequestHeader +--- +
{{APIRef('XMLHttpRequest')}}
+ +

{{domxref("XMLHttpRequest")}} 物件中的 setRequestHeader() 方法用來設定 HTTP 的表頭請求。當使用 setRequestHeader() 的時候,必須在 {{domxref("XMLHttpRequest.open", "open()")}} 之後呼叫,同時也必須在 {{domxref("XMLHttpRequest.send", "send()")}} 之前呼叫。如果這個方法被呼叫了許多次,且設定的表頭是一樣的,那所有設定的值會被合併成一個單一的表頭請求。

+ +

在第一次呼叫 setRequestHeader() 之後的每一次的呼叫,都會把給定的文字附加在已存在的表頭內容之後。

+ +

If no {{HTTPHeader("Accept")}} header has been set using this, an Accept header with the type "*/*" is sent with the request when {{domxref("XMLHttpRequest.send", "send()")}} is called.

+ +

基於安全的理由,有些表頭只有使用者代理器可以使用。這些表頭包含了: {{Glossary("Forbidden_header_name", "forbidden header names", 1)}}  和 {{Glossary("Forbidden_response_header_name", "forbidden response header names", 1)}}.

+ +
+

Note: For your custom fields, you may encounter a "not allowed by Access-Control-Allow-Headers in preflight response" exception when you send requests across domains. In this situation, you need to set up the {{HTTPHeader("Access-Control-Allow-Headers")}} in your response header at server side.

+
+ +

語法

+ +
XMLHttpRequest.setRequestHeader(header, value)
+
+ +

參數

+ +
+
header
+
想要設定所屬值的表頭名稱。
+
value
+
用來設定表頭本身的值。
+
+ +

回傳值

+ +

未定義

+ +

規範

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('XMLHttpRequest', '#the-setrequestheader()-method', 'setRequestHeader()')}}{{Spec2('XMLHttpRequest')}}WHATWG living standard
+ +

瀏覽器相容性

+ + + +

{{Compat("api.XMLHttpRequest.setRequestHeader")}}

+ +

參見

+ + diff --git a/files/zh-tw/web/api/xmlhttprequest/status/index.html b/files/zh-tw/web/api/xmlhttprequest/status/index.html new file mode 100644 index 0000000000..c54ece9939 --- /dev/null +++ b/files/zh-tw/web/api/xmlhttprequest/status/index.html @@ -0,0 +1,115 @@ +--- +title: XMLHttpRequest.status +slug: Web/API/XMLHttpRequest/status +translation_of: Web/API/XMLHttpRequest/status +--- +
{{APIRef('XMLHttpRequest')}}
+ +

XMLHttpRequest.status 屬性根據XMLHttpRequest的回應傳回數值化的狀況編碼。狀況編碼為一正短整數(unsigned short)。Before the request is complete, the value of status will be 0. It is worth noting that browsers report a status of 0 in case of XMLHttpRequest errors too.

+ +

The status codes returned are the standard HTTP status codes. For example, status 200 denotes a successful request. If the server response doesn't explicitly specify a status code, XMLHttpRequest.status will assume the default value of 200.

+ +

Example

+ +
var xhr = new XMLHttpRequest();
+console.log('UNSENT', xhr.status);
+
+xhr.open('GET', '/server', true);
+console.log('OPENED', xhr.status);
+
+xhr.onprogress = function () {
+  console.log('LOADING', xhr.status);
+};
+
+xhr.onload = function () {
+  console.log('DONE', xhr.status);
+};
+
+xhr.send(null);
+
+/**
+ * Outputs the following:
+ *
+ * UNSENT 0
+ * OPENED 0
+ * LOADING 200
+ * DONE 200
+ */
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('XMLHttpRequest', '#the-status-attribute')}}{{Spec2('XMLHttpRequest')}}WHATWG living standard
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(1)}}{{CompatGeckoDesktop("1.0")}}[1]{{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 versions 5 and 6 lacked the XMLHttpRequest object, but provided a way to make AJAX requests using ActiveXObject.

+ +

See also

+ + diff --git a/files/zh-tw/web/api/xmlhttprequest/synchronous_and_asynchronous_requests/index.html b/files/zh-tw/web/api/xmlhttprequest/synchronous_and_asynchronous_requests/index.html new file mode 100644 index 0000000000..e8a148b5a9 --- /dev/null +++ b/files/zh-tw/web/api/xmlhttprequest/synchronous_and_asynchronous_requests/index.html @@ -0,0 +1,260 @@ +--- +title: Synchronous and asynchronous requests +slug: Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests +translation_of: Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests +--- +

XMLHttpRequest 支持同步和非同步請求,一般來說,建議使用非同步請求。

+ +

In short, synchronous requests block the execution of code which creates "freezing" on the screen and an unresponsive user experience. 

+ +

非同步請求

+ +

If you use XMLHttpRequest from an extension, you should use it asynchronously.  In this case, you receive a callback when the data has been received, which lets the browser continue to work as normal while your request is being handled.

+ +

範例: send a file to the console log

+ +

這是使用非同步XMLHttpRequest的基本方式

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

Line 2第3個參數為布林值,true表示非同步請求。

+ +

Line 3 creates an event handler function object and assigns it to the request's onload attribute.  This handler looks at the request's readyState to see if the transaction is complete in line 4, and if it is, and the HTTP status is 200, dumps the received content.  If an error occurred, an error message is displayed.

+ +

Line 15 actually initiates the request.  The callback routine is called whenever the state of the request changes.

+ +

Example: creating a standard function to read external files

+ +

In some cases you must read many external files. This is a standard function which uses the XMLHttpRequest object asynchronously in order to switch the content of the read file to a specified listener.

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

Usage:

+ +
function showMessage (sMsg) {
+  alert(sMsg + this.responseText);
+}
+
+loadFile("message.txt", showMessage, "New message!\n\n");
+
+ +

Line 1 declares a function which will pass all arguments after the third to the callback function when the file has been loaded.

+ +

Line 4 creates an event handler function object and assigns it to the request's onload attribute.  This handler looks at the request's readyState to see if the transaction is complete in line 5, and if it is, and the HTTP status is 200, calls the callback function.  If an error occurred, an error message is displayed.

+ +

Line 13 specifies true for its third parameter to indicate that the request should be handled asynchronously.

+ +

Line 14 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:

+ +
  var args = arguments.slice(2);
+  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.
+ +

In rare cases, the use of a synchronous method is preferable to an asynchronous one.

+ +

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.

+ +

Irreplaceability of the synchronous use

+ +

There are some few cases in which the synchronous usage of XMLHttpRequest is not replaceable. This happens for example during the window.onunload and window.onbeforeunload events (see also below).

+ +

Sending the usual XMLHttpRequest when the page unloaded poses a problem with the asynchronous response from the server: by the time the response comes back, the page has unloaded and the callback function won’t exist anymore. This generates a JavaScript “function is not defined” error.

+ +

+ +

A possible solution is to make sure that any AJAX requests that you make on unload are make synchronously instead of asynchronously. This will ensure that the page doesn’t finish unloading before the server response comes back.

+ +

Example #1: Automatic logout before exit

+ +
window.onbeforeunload = function () {
+  var xhr = new XMLHttpRequest();
+  xhr.open("GET", "logout.php?nick=" + escape(myName), false);  // synchronous request
+  xhr.send(null);
+  if (xhr.responseText.trim() !== "logout done"); {  // "logout done" is the expected response text
+    return "Logout has failed. Do you want to complete it manually?";
+  }
+};
+
+ + + +
<!doctype html>
+<html>
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
+<title>MDN Example</title>
+<script type="text/javascript">
+(function () {
+
+  function dontPanic () {
+    bForsake = false;
+    return true;
+  }
+
+  onload = function () {
+    for (
+      var aLinks = document.links, nLen = aLinks.length, nIdx = 0;
+      nIdx < nLen;
+      aLinks[nIdx++].onclick = dontPanic
+    );
+  };
+
+  onbeforeunload = function () {
+    if (bForsake) {
+      /* silent synchronous request */
+      var oReq = new XMLHttpRequest();
+      oReq.open("GET", "exit.php?leave=" + escape(location.href), false);
+      oReq.send(null);
+    }
+  };
+
+  var bForsake = true;
+
+})();
+</script>
+</head>
+
+<body>
+
+<p><a href="https://developer.mozilla.org/">Example link</a></p>
+
+</body>
+</html>
+ +

See also

+ + + +

{{ languages( {"zh-cn": "zh-cn/DOM/XMLHttpRequest/Synchronous_and_Asynchronous_Requests" } ) }}

diff --git a/files/zh-tw/web/api/xmlhttprequest/using_xmlhttprequest/index.html b/files/zh-tw/web/api/xmlhttprequest/using_xmlhttprequest/index.html new file mode 100644 index 0000000000..97b03c21d1 --- /dev/null +++ b/files/zh-tw/web/api/xmlhttprequest/using_xmlhttprequest/index.html @@ -0,0 +1,766 @@ +--- +title: 使用 XMLHttpRequest +slug: Web/API/XMLHttpRequest/Using_XMLHttpRequest +tags: + - AJAX + - AJAXfile + - Advanced + - DOM + - JXON + - MakeBrowserAgnostic + - NeedsCompatTable + - XML + - XMLHttpRequest +translation_of: Web/API/XMLHttpRequest/Using_XMLHttpRequest +--- +

要送出一個 HTTP 請求,需要建立一個 {{domxref("XMLHttpRequest")}} 物件、開啟一個 URL,並發起一個請求。在交易(transaction)完成後,XMLHttpRequest 物件將會包含如回應內容(response body)及 HTTP 狀態等等請求結果中的有用資訊。本頁概述了一些常見的、甚至略為難理解的 XMLHttpRequest 物件使用案例。

+ +
function reqListener () {
+  console.log(this.responseText);
+}
+
+var oReq = new XMLHttpRequest();
+oReq.addEventListener("load", reqListener);
+oReq.open("GET", "http://www.example.org/example.txt");
+oReq.send();
+ +

請求類型

+ +

透過 XMLHttpRequest 建立的請求,其取得資料的方式可以為非同步(asynchronously)或同步(synchronously)兩種之一。請求的種類是由 {{domxref("XMLHttpRequest.open()")}} 方法的選擇性參數 async(第三個參數)決定。若 async 參數為 true 或是未指定,XMLHttpRequest 會被設定為非同步,相反的若為 false 則會被設定為同步。這兩種請求類型的細節討論與示範可以在同步與非同步請求頁面中找到。一般來說,很少會使用到同步請求。

+ +
備註:自 Gecko 30.0 {{ geckoRelease("30.0") }} 開始,在主執行緒上的同步請求因其差勁的使用者體驗已被棄用。
+ +

處理回應

+ +

XMLHttpRequest 的活動標準規範(living standard specification)定義了數個 XMLHttpRequest 建構出之物件的回應屬性。這些回應屬性告訴客戶端關於 XMLHttpRequest 回應狀態的重要資訊。一些處理非文字類型回應的案例可能會需要一些在下面小節所說明的分析和操作。

+ +

分析及操作 responseXML 屬性

+ +

透過 XMLHttpRequest 取得一個遠端的 XML 文件內容時,responseXML 屬性({{Glossary("property/JavaScript", "property")}})將會是一個由 XML 文件解析而來的 DOM 物件。這可能會造成分析和操作上的一些困難,以下有四種主要的 XML 文件分析方式:

+ +
    +
  1. 利用 XPath 指向需要部份。
  2. +
  3. 手動的解析與序列化 XML 成字串或物件。
  4. +
  5. 利用 {{domxref("XMLSerializer")}} 來序列化 DOM 樹成字串或檔案
  6. +
  7. 如果事先知道 XML 文件內容,可利用 {{jsxref("RegExp")}}。如果換行符號會影響 RegExp 掃描結果,則需要移除換行符號。然而,這項方式應該是「最後不得已的手段(last resort)」,因為一旦 XML 文件內容稍有變動,此方式就可能會失敗。
  8. +
+ +

分析及操作含有 HTML 文件的 responseText 屬性

+ +
備註:W3C 的XMLHttpRequest 規範允許透過 XMLHttpRequest.responseXML 屬性({{Glossary("property/JavaScript", "property")}})來解析 HTML。相關細節請參考 HTML in XMLHttpRequest 一文。
+ +

若透過 XMLHttpRequest 來取得一個遠端的 HTML 網頁內容,則 responseText 屬性({{Glossary("property/JavaScript", "property")}})會是「一串(soup)」包含所有 HTML 標籤的字串。這可能使得在分析和操作上造成困難,以下有三種主要分析此一大串 HTML 字串的方式:

+ +
    +
  1. 利用 XMLHttpRequest.responseXML 屬性。
  2. +
  3. 將內容透過 fragment.body.innerHTML 注入文件片段(document fragment)body 中,並遍歷(traverse)文件片段的 DOM。
  4. +
  5. 如果事先知道 HTML 之 responseText 內容,可利用 {{jsxref("RegExp")}}。如果換行符號會影響 RegExp 掃描結果,則需要移除換行符號。然而,這項方式應該是「最後不得已的手段(last resort)」,因為一旦 HTML 程式碼稍有變動,此方式就可能會失敗。
  6. +
+ +

處理二進位資料

+ +

僅管 XMLHttpRequest 最常被用在傳送及接收文字資料,但它其實也可以傳送及接收二進位內容。有幾種經過良好測試的方法可以用來強制使用 XMLHttpRequest 發送二進位資料。透過使用 XMLHttpRequest 物件的 .overrideMimeType() 方法是一個可行的解決方案。

+ +
var oReq = new XMLHttpRequest();
+oReq.open("GET", url);
+// retrieve data unprocessed as a binary string
+oReq.overrideMimeType("text/plain; charset=x-user-defined");
+/* ... */
+
+ +

XMLHttpRequest Level 2 規範加入了新的 responseType 屬性,讓收發二進位資料變得容易許多。

+ +
var oReq = new XMLHttpRequest();
+
+oReq.onload = function(e) {
+  var arraybuffer = oReq.response; // not responseText
+  /* ... */
+}
+oReq.open("GET", url);
+oReq.responseType = "arraybuffer";
+oReq.send();
+ +

更多的範例可參考傳送及接收二進位資料頁面。

+ +

監視進度

+ +

XMLHttpRequest 提供了監聽請求於處理過程中所發生的各項事件之能力。包括了定期進度通知、錯誤通知等等。

+ +

XMLHttpRequest 支援可監視其傳輸進度的 DOM 進度事件,此事件遵循進度事件規範:這些事件實作了 {{domxref("ProgressEvent")}} 介面。

+ +
var oReq = new XMLHttpRequest();
+
+oReq.addEventListener("progress", updateProgress);
+oReq.addEventListener("load", transferComplete);
+oReq.addEventListener("error", transferFailed);
+oReq.addEventListener("abort", transferCanceled);
+
+oReq.open();
+
+// ...
+
+// progress on transfers from the server to the client (downloads)
+function updateProgress (oEvent) {
+  if (oEvent.lengthComputable) {
+    var percentComplete = oEvent.loaded / oEvent.total;
+    // ...
+  } else {
+    // Unable to compute progress information since the total size is unknown
+  }
+}
+
+function transferComplete(evt) {
+  console.log("The transfer is complete.");
+}
+
+function transferFailed(evt) {
+  console.log("An error occurred while transferring the file.");
+}
+
+function transferCanceled(evt) {
+  console.log("The transfer has been canceled by the user.");
+}
+ +

第 3-6 行加入了事件監聽器來處理使用 XMLHttpRequest 執行資料收發過程中的各類事件。

+ +
備註:必須在呼叫 open() 方法開啟請求連線之前就註冊好事件監聽器,否則 progress 事件將不會被觸發。
+ +

在這個例子中,指定了 updateProgress() 函式作為 progress 事件處理器,progress 事件處理器會於 progress 事件物件的 totalloaded 屬性分別接收到要傳輸的總位元數及已送出的位元數。然而,假如 lengthComputable 屬性值為假,則代表要傳輸的總位元數是未知且 total 屬性值將會為零。

+ +

progress 事件同時存在於上傳及下載傳輸中。下載的相關事件會於 XMLHttpRequest 物件自己身上被觸發,如上面的範例。而上傳相關事件則在 XMLHttpRequest.upload 物件上被觸發,如以下範例:

+ +
var oReq = new XMLHttpRequest();
+
+oReq.upload.addEventListener("progress", updateProgress);
+oReq.upload.addEventListener("load", transferComplete);
+oReq.upload.addEventListener("error", transferFailed);
+oReq.upload.addEventListener("abort", transferCanceled);
+
+oReq.open();
+
+ +
備註:progress 事件無法用於 file: 通訊協定。
+ +
+

備註:自 {{Gecko("9.0")}} 開始,接收到每一個資料的區塊(chunk)時,progress 事件都會被觸發。包括在 progress 事件被觸發前,就已經接收到含有最後一個資料區塊的最後一個封包並且關閉連線的狀況下,在載入此封包時仍會自動觸發 progress 事件。這代表我們可以僅關注 progress 事件即能夠可靠的監視進度。

+
+ +
+

備註:在 {{Gecko("12.0")}} 中,如果 XMLHttpRequestresponseType 屬性為「moz-blob」,那麼 progress 事件觸發時的 XMLHttpRequest.response 值會是一個目前包含了所接收資料的 {{domxref("Blob")}}。

+
+ +

我們也可以透過 loadend 事件來偵測到所有之三種下載結束狀況(abortloaderror):

+ +
req.addEventListener("loadend", loadEnd);
+
+function loadEnd(e) {
+  console.log("The transfer finished (although we don't know if it succeeded or not).");
+}
+
+ +

請注意由 loadend 事件中接收到的資訊並無法確定是由何種結束狀況所觸發。不過還是可以用 loadend 事件來處理所有傳輸結束情況下需要執行的任務。

+ +

提交表單與上傳檔案

+ +

XMLHttpRequest 物件實體有兩種方式來提交表單:

+ + + +

使用 FormData API 是最簡單、快速的方式,但不利於將資料集合進行字串化
+ 只使用 AJAX 的方式較為複雜,但也更加靈活、強大。

+ +

僅使用 XMLHttpRequest

+ +

以不透過 FormData API 提交表單的方式在大多數的情況下都不需要使用其他額外的 API。唯一的例外是要上傳一或多個檔案時,會需要用到 {{domxref("FileReader")}} API。

+ +

提交方法簡介

+ +

一個 HTML {{HTMLElement("form", "表單(form)")}}有以下四種提交方式:

+ + + +

現在,假設要提交一個只包含兩個欄位的表單,欄位名稱為 foobaz。若是使用 POST 方法,伺服器將會收到一個如以下三個例子之一的字串,這取決於所使用的編碼類型(encoding type):

+ + + +

如果是使用 GET 方法,一個如下方的字串會被直接附加入到 URL 上:

+ +
?foo=bar&baz=The%20first%20line.%0AThe%20second%20line.
+ +

小型原生框架

+ +

在我們提交 {{HTMLElement("form")}} 時,瀏覽器自動幫我們做了上面這些工作。假如要使用 JavaScript 達到同樣的效果就必須告訴直譯器(interpreter)要處理的所有事。然而,如何透過純粹的 AJAX 來傳送表單複雜到難以在本頁解釋所有細節。基於這個理由,我們改為在這此提供一組完整(教學用)的框架,可用於上述四種的每一種提交(submit),並包括上傳檔案

+ +
+
<!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() Polyfill ::
+|*|
+|*|  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.
+|*|  https://www.gnu.org/licenses/gpl-3.0-standalone.html
+|*|
+|*|  Syntax:
+|*|
+|*|   AJAXSubmit(HTMLFormElement);
+\*/
+
+var AJAXSubmit = (function () {
+
+  function ajaxSuccess () {
+    /* console.log("AJAXSubmit - Success!"); */
+    console.log(this.responseText);
+    /* you can get the serialized data through the "submittedData" custom property: */
+    /* console.log(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) {
+        /* NOTE: this will submit _all_ submit buttons. Detecting the correct one is non-trivial. */
+        /* 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>
+
+ +

為了進行測試,建立一個名為 register.php 的 PHP 頁面(即為上面範例表單之 action 屬性({{Glossary("attribute")}})所指向的位置),並輸入以下最簡化的內容:

+ +
<?php
+/* register.php */
+
+header("Content-type: text/plain");
+
+/*
+NOTE: You should never use `print_r()` in production scripts, or
+otherwise output client-submitted data without sanitizing it first.
+Failing to sanitize can lead to cross-site scripting vulnerabilities.
+*/
+
+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);
+
+
+ +

使用這個框架的語法簡單如下:

+ +
AJAXSubmit(myForm);
+ +
備註:此框架使用了 {{domxref("FileReader")}} API 來發送檔案上傳。這是個較新的 API,且 IE9 或其先前版本並未實作。因為這個理由,AJAX-only 上傳被認為是一項實驗性技術。若沒有需要上傳二進位檔案,此框架可於大部分瀏覽器中運作良好。
+ +
備註:傳送二進位檔案的最佳方式是藉由 {{jsxref("ArrayBuffer", "ArrayBuffers")}} 或 {{domxref("Blob", "Blobs")}} 結合 {{domxref("XMLHttpRequest.send()", "send()")}} 方法來送出,如果可以也能搭配 FileReader API 的 {{domxref("FileReader.readAsArrayBuffer()", "readAsArrayBuffer()")}} 方法先進行讀取。但因為這段程式指令碼(script)的目的是要處理可字串化的原始資料,所以使用 {{domxref("XMLHttpRequest.sendAsBinary()", "sendAsBinary()")}} 方法結合 FileReader API 的 {{domxref("FileReader.readAsBinaryString()", "readAsBinaryString()")}} 方法。就其本身來看,以上的指令碼只有在處理小型檔案時才有意義。假如不打算上傳二進位內容,請考慮使用 FormData API。
+ +
備註:非標準的 sendAsBinary 方法在 Gecko 31 {{geckoRelease(31)}} 已被認為是棄用的(deprecated),並且即將被移除。而標準的 send(Blob data) 方法可以作為替代。
+ +

使用 FormData 物件

+ +

{{domxref("XMLHttpRequest.FormData", "FormData")}} 建構式可以讓我們收集一連串名/值對資料並透過 XMLHttpRequest 送出。其主要用於傳送表單資料,但也能夠單獨的由表單建立來傳輸使用者輸入的資料。若表單的編碼類型(encoding type)被設定為「multipart/form-data」,則由 FormData 所發送的資料格式和表單用來傳送資料的 submit() 方法相同。FormData 物件可以搭配 XMLHttpRequest 以多種方式使用。相關的範例,以及可以怎麼利用 FormData 配合 XMLHttpRequest 的說明,請參考使用 FormData 物件頁面。為了教學使用,下方為一個利用 FormData API 來改寫先前範例翻譯版本。注意這段精簡後的程式碼:

+ +
+
<!doctype html>
+<html>
+<head>
+<meta http-equiv="Content-Type" charset="UTF-8" />
+<title>Sending forms with FormData &ndash; MDN</title>
+<script>
+"use strict";
+
+function ajaxSuccess () {
+  console.log(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);
+    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>
+
+ +
備註:如同之前所說,{{domxref("FormData")}} 物件是不能被字串化的物件。若想要字串化一個被提交的資料,請使用先前的 AJAX 範例。還要注意的是,雖然在這個例子中有一些 file {{ HTMLElement("input") }} 欄位,當你透過 FormData API 來提交表單便也不需要使用 {{domxref("FileReader")}} API:檔案會自動地載入並上傳。
+ +

取得最後修改日期

+ +
function getHeaderTime () {
+  console.log(this.getResponseHeader("Last-Modified"));  /* A valid GMTString date or null */
+}
+
+var oReq = new XMLHttpRequest();
+oReq.open("HEAD" /* use HEAD if you only need the headers! */, "yourpage.html");
+oReq.onload = getHeaderTime;
+oReq.send();
+ +

當最後修改日期改變時做一些事

+ +

先建立兩個函式:

+ +
function getHeaderTime () {
+  var nLastVisit = parseFloat(window.localStorage.getItem('lm_' + this.filepath));
+  var nLastModif = Date.parse(this.getResponseHeader("Last-Modified"));
+
+  if (isNaN(nLastVisit) || nLastModif > nLastVisit) {
+    window.localStorage.setItem('lm_' + this.filepath, Date.now());
+    isFinite(nLastVisit) && this.callback(nLastModif, nLastVisit);
+  }
+}
+
+function ifHasChanged(sURL, fCallback) {
+  var oReq = new XMLHttpRequest();
+  oReq.open("HEAD" /* use HEAD - we only need the headers! */, sURL);
+  oReq.callback = fCallback;
+  oReq.filepath = sURL;
+  oReq.onload = getHeaderTime;
+  oReq.send();
+}
+ +

並進行測試:

+ +
/* Let's test the file "yourpage.html"... */
+
+ifHasChanged("yourpage.html", function (nModif, nVisit) {
+  console.log("The page '" + this.filepath + "' has been changed on " + (new Date(nModif)).toLocaleString() + "!");
+});
+ +

如果想要知道目前頁面是否已變更,請參考 {{domxref("document.lastModified")}} 一文。

+ +

跨網域 XMLHttpRequest

+ +

現代瀏覽器支援跨網域(cross-site)請求並實作了網路應用程式工作小組(Web Applications (WebApps) Working Group)提出的跨網域請求存取控制標準。只要伺服器被設定為允許來自你的網路應用程式來源(origin)網域之請求,XMLHttpRequest 便能正常運作。否則,將會拋出一個 INVALID_ACCESS_ERR 例外。

+ +

避開快取

+ +

有一個跨瀏覽器相容的避開快取方法,便是將時間戳記(timestamp)附加於 URL 後方,請確保加上了適當的「?」或「&」。例如:

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

由於本地快取的索引是基於 URL,加入時間戳記會導致每一個請求都會是唯一的,藉此避開快取。

+ +

可以使用以下的程式碼來自動的調整 URL:

+ +
var oReq = new XMLHttpRequest();
+
+oReq.open("GET", url + ((/\?/).test(url) ? "&" : "?") + (new Date()).getTime());
+oReq.send(null);
+ +

安全性

+ +

{{fx_minversion_note(3, "Firefox 3 之前的版本允許在偏好設定中設定 capability.policy.<policyname>.XMLHttpRequest.open</policyname>allAccess 來讓指定的網域能夠跨網域存取。現已不再支援。")}}

+ +

{{fx_minversion_note(5, "Firefox 5 之前的版本可以使用 netscape.security.PrivilegeManager.enablePrivilege(\"UniversalBrowserRead\"); 來發送跨網域存取請求。現已不再支援,即使它不會有警告並且依然會顯示允許請求的權限對話框。")}}

+ +

開啟跨網域指令碼(script)的建議方式是於 XMLHttpRequest 的回應中使用 Access-Control-Allow-Origin HTTP 標頭。

+ +

被中止的 XMLHttpRequest

+ +

如果你發現 XMLHttpRequeststatus=0statusText=null,這代表請求並不被允許執行,其狀態為 UNSENT(未送出)。被中止的原因可能是因為 XMLHttpRequest 物件所關聯的 origin(來源網域)值(於 XMLHttpRequest 物件建立時自 window.origin 取得)在呼叫 open() 方法之前就已經被改變。這是可能發生的,例如在 windowonunload 事件觸發時送出 XMLHttpRequest 請求,預期的情況為:XMLHttpRequest 物件剛被建立,而目前的視窗尚未關閉,而最後發送請求(即呼叫了 open() 方法)的時間點是在此視窗失去了焦點並且另外的視窗取得焦點之間。要避開這個問題的最有效方法是在要被終止的(terminated)window 觸發 unload 事件時,於新的 window 的上註冊一個新的 activate 事件監聽器來發送請求。

+ +

使用 JavaScript 模組/XPCOM 元件中的 XMLHttpRequest

+ +

JavaScript 模組 或 XPCOM 元件實體化一個 XMLHttpRequest 物件在做法上會有些許不同;我們無法用 XMLHttpRequest() 建構式,因為此建構式並未在元件中定義,並會導致程式產生錯誤。較佳的方式是使用 XPCOM 元件的建構式。

+ +
const XMLHttpRequest = Components.Constructor("@mozilla.org/xmlextras/xmlhttprequest;1",
+    "nsIXMLHttpRequest");
+
+ +

在 Gecko 16 之前,存在著一個透過這種方式發送的請求會被無條件取消的臭蟲。若程式需要在 Gecko 15 或更早的版本上運作,可以從隱藏的 DOM window 中取得 XMLHttpRequest() 建構式。

+ +
const { XMLHttpRequest } = Components.classes["@mozilla.org/appshell/appShellService;1"]
+                                     .getService(Components.interfaces.nsIAppShellService)
+                                     .hiddenDOMWindow;
+var oReq = new XMLHttpRequest();
+ +

參見

+ +
    +
  1. MDN AJAX 介紹
  2. +
  3. HTTP 存取控制
  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: WHATWG specification
  16. +
diff --git a/files/zh-tw/web/api/xmlhttprequest/withcredentials/index.html b/files/zh-tw/web/api/xmlhttprequest/withcredentials/index.html new file mode 100644 index 0000000000..e70f611ece --- /dev/null +++ b/files/zh-tw/web/api/xmlhttprequest/withcredentials/index.html @@ -0,0 +1,48 @@ +--- +title: XMLHttpRequest.withCredentials +slug: Web/API/XMLHttpRequest/withCredentials +translation_of: Web/API/XMLHttpRequest/withCredentials +--- +
{{APIRef('XMLHttpRequest')}}
+ +

XMLHttpRequest.withCredentials 屬性是一個 {{jsxref("Boolean")}} 型別,它指出無論是否使用 Access-Control 標頭在跨站的要求上,都應該使用像 Cookies、Authorization 標頭或 TLS 用戶端憑證來進行驗證。在相同來源的要求設定 withCredentials 沒有任何效果。

+ +

In addition, this flag is also used to indicate when cookies are to be ignored in the response. The default is false. XMLHttpRequest from a different domain cannot set cookie values for their own domain unless withCredentials is set to true before making the request. The third-party cookies obtained by setting withCredentials to true will still honor same-origin policy and hence can not be accessed by the requesting script through document.cookie or from response headers.

+ +
+

Note: 永遠不會影響到同源請求。

+
+ +
+

Note: XMLHttpRequest responses from a different domain cannot set cookie values for their own domain unless withCredentials is set to true before making the request, regardless of Access-Control- header values. 

+
+ +

範例

+ +
var xhr = new XMLHttpRequest();
+xhr.open('GET', 'http://example.com/', true);
+xhr.withCredentials = true;
+xhr.send(null);
+ +

規格

+ + + + + + + + + + + + + + +
規格狀態備註
{{SpecName('XMLHttpRequest', '#the-withcredentials-attribute')}}{{Spec2('XMLHttpRequest')}}WHATWG living standard
+ +

瀏覽器相容性

+ + + +

{{Compat("api.XMLHttpRequest.withCredentials")}}

diff --git a/files/zh-tw/web/api/xmlhttprequest/xmlhttprequest/index.html b/files/zh-tw/web/api/xmlhttprequest/xmlhttprequest/index.html new file mode 100644 index 0000000000..6459ef0c2a --- /dev/null +++ b/files/zh-tw/web/api/xmlhttprequest/xmlhttprequest/index.html @@ -0,0 +1,50 @@ +--- +title: XMLHttpRequest() +slug: Web/API/XMLHttpRequest/XMLHttpRequest +translation_of: Web/API/XMLHttpRequest/XMLHttpRequest +--- +
{{draft}}{{APIRef('XMLHttpRequest')}}
+ +

XMLHttpRequest() 建構式會建立一個新的 {{domxref("XMLHttpRequest")}} 物件。

+ +

關於如何使用 XMLHttpRequest 物件的細節,請參照: Using XMLHttpRequest.

+ +

語法

+ +
const request = new XMLHttpRequest();
+
+ +

參數

+ +

無。

+ +

回傳值 

+ +

將回傳一個新的 {{domxref("XMLHttpRequest")}} 物件。{{domxref("XMLHttpRequest")}} 物件在呼叫{{domxref("XMLHttpRequest.send", "send()")}} 送出要求到伺服器之前,至少要藉著呼叫 {{domxref("XMLHttpRequest.open", "open()")}} 來準備好必需的設定。

+ +

非標準的 Firefox 語法

+ +

Firefox 16 added a non-standard parameter to the constructor that can enable anonymous mode (see {{Bug("692677")}}). Setting the mozAnon flag to true effectively resembles the AnonXMLHttpRequest() constructor described in older versions of the XMLHttpRequest specification.

+ +
const request = new XMLHttpRequest(paramsDictionary);
+ +

Parameters (non-standard)

+ +
+
objParameters {{gecko_minversion_inline("16.0")}}
+
There are two flags you can set: +
+
mozAnon
+
Boolean: Setting this flag to true will cause the browser not to expose the {{Glossary("origin")}} and user credentials when fetching resources. Most important, this means that {{Glossary("Cookie", "cookies")}} will not be sent unless explicitly added using setRequestHeader.
+
mozSystem
+
Boolean: Setting this flag to true allows making cross-site connections without requiring the server to opt-in using {{Glossary("CORS")}}. Requires setting mozAnon: true, i.e. this can't be combined with sending cookies or other user credentials. This only works in privileged (reviewed) apps ({{Bug("692677")}}); it does not work on arbitrary webpages loaded in Firefox
+
+
+
+ +

參見

+ + diff --git a/files/zh-tw/web/api/xmlhttprequesteventtarget/index.html b/files/zh-tw/web/api/xmlhttprequesteventtarget/index.html new file mode 100644 index 0000000000..41045ab17f --- /dev/null +++ b/files/zh-tw/web/api/xmlhttprequesteventtarget/index.html @@ -0,0 +1,111 @@ +--- +title: XMLHttpRequestEventTarget +slug: Web/API/XMLHttpRequestEventTarget +translation_of: Web/API/XMLHttpRequestEventTarget +--- +

{{APIRef("XMLHttpRequest")}}

+ +

XMLHttpRequestEventTarget 介面描述了一個 {{ domxref("XMLHttpRequest") }} 物件實體當中,所有可註冊事件處理器的屬性。

+ +

{{InheritanceDiagram}}

+ +

屬性

+ +
+
{{ domxref("XMLHttpRequestEventTarget.onabort") }}
+
Contains the function to call when a request is aborted and the {{event('abort')}} event is received by this object.
+
{{ domxref("XMLHttpRequestEventTarget.onerror") }}
+
Contains the function to call when a request encounters an error and the {{event('error')}} event is received by this object.
+
{{ domxref("XMLHttpRequestEventTarget.onload") }}
+
Contains the function to call when an HTTP request returns after successfully fetching content and the {{event('load')}} event is received by this object.
+
{{ domxref("XMLHttpRequestEventTarget.onloadstart") }}
+
Contains the function that gets called when the HTTP request first begins loading data and the {{event('loadstart')}} event is received by this object.
+
{{ domxref("XMLHttpRequestEventTarget.onprogress") }}
+
Contains the function that is called periodically with information about the progress of the request and the {{event('progress')}} event is received by this object.
+
{{ domxref("XMLHttpRequestEventTarget.ontimeout") }}
+
Contains the function that is called if the event times out and the {{event("timeout")}} event is received by this object; this only happens if a timeout has been previously established by setting the value of the XMLHttpRequest object's timeout attribute.
+
{{ domxref("XMLHttpRequestEventTarget.onloadend") }}
+
Contains the function that is called when the load is completed, even if the request failed, and the {{event('loadend')}} event is received by this object.
+
+ +

規範

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('XMLHttpRequest')}}{{Spec2('XMLHttpRequest')}}WHATWG living standard
+ +

瀏覽器相容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support1{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.0")}}7{{CompatVersionUnknown}}1.2
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatUnknown}}1.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

 

+ +

參見

+ + diff --git a/files/zh-tw/web/css/@font-face/index.html b/files/zh-tw/web/css/@font-face/index.html new file mode 100644 index 0000000000..ca045e5dab --- /dev/null +++ b/files/zh-tw/web/css/@font-face/index.html @@ -0,0 +1,247 @@ +--- +title: '@font-face' +slug: Web/CSS/@font-face +tags: + - CSS + - CSS Reference + - CSS 參考 + - Fonts + - WOFF + - 字型 +translation_of: Web/CSS/@font-face +--- +
{{CSSRef}}
+ +

摘要

+ +

The @font-face CSS at-rule allows authors to specify online fonts to display text on their web pages. By allowing authors to provide their own fonts, @font-face eliminates the need to depend on the limited number of fonts users have installed on their computers. The @font-face at-rule may be used not only at the top level of a CSS, but also inside any CSS conditional-group at-rule.

+ +

{{seeCompatTable}}

+ +

語法

+ +
@font-face {
+  [font-family: <family-name>;]?
+  [src: [ <uri> [format(<string>#)]? | <font-face-name> ]#;]?
+  [unicode-range: <urange>#;]?
+  [font-variant: <font-variant>;]?
+  [font-feature-settings: normal|<feature-tag-value>#;]?
+  [font-stretch: <font-stretch>;]?
+  [font-weight: <weight>];
+  [font-style: <style>];
+}
+
+ +

參數值

+ +
+
<family-name>
+
Specifies a font name that will be used as font face value for font properties.
+
<uri>
+
URL for the remote font file location, or the name of a font on the user's computer in the form local("Font Name").
+
<font-variant>
+
A {{cssxref("font-variant")}} value.
+
<font-stretch>
+
A {{cssxref("font-stretch")}} value.
+
<weight>
+
A font weight value.
+
<style>
+
A font style value.
+
+ +

You can specify a font on the user's local computer by name using the local() syntax. If that font isn't found, other sources will be tried until one is found.

+ +

範例

+ +

這個範例指定一個可供下載的字型,並套用至 document 的整個 body。

+ +

檢視線上範例

+ +
<html>
+<head>
+  <title>Web Font Sample</title>
+  <style type="text/css" media="screen, print">
+    @font-face {
+      font-family: "Bitstream Vera Serif Bold";
+      src: url("http://developer.mozilla.org/@api/deki/files/2934/=VeraSeBd.ttf");
+    }
+
+    body { font-family: "Bitstream Vera Serif Bold", serif }
+  </style>
+</head>
+<body>
+  This is Bitstream Vera Serif Bold.
+</body>
+</html>
+
+ +

這個範例會套用使用者本地的 "Helvetica Neue Bold" 字型,只有當使用者未安裝該字型(兩種名稱都試過了),才會下載 "MgOpenModernaBold.ttf" 字型:

+ +
@font-face {
+  font-family: MyHelvetica;
+  src: local("Helvetica Neue Bold"),
+  local("HelveticaNeue-Bold"),
+  url(MgOpenModernaBold.ttf);
+  font-weight: bold;
+}
+
+ +

注意事項

+ + + +

規格文件

+ + + + + + + + + + + + + + + + + + + + + +
規格文件狀態註解
{{SpecName('WOFF1.0', '', 'WOFF font format')}}{{Spec2('WOFF1.0')}}字型格式規格文件
{{SpecName('CSS3 Fonts', '#font-face-rule', '@font-face')}}{{Spec2('CSS3 Fonts')}} 
+ +

瀏覽器相容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
功能特色Firefox (Gecko)ChromeInternet ExplorerOperaSafari
基本支援{{CompatGeckoDesktop("1.9.1")}}4.04.010.03.1
WOFF{{CompatGeckoDesktop("1.9.1")}}6.09.011.105.1
SVG 字型{{CompatNo}}
+ {{unimplemented_inline(119490)}}
{{CompatNo}}
unicode-range +

yes ({{bug(443976)}})

+
9.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
功能特色AndroidFirefox 行動版 (Gecko)IE 行動版Opera MiniOpera 行動版Safari 行動版
基本支援{{CompatVersionUnknown}}{{CompatGeckoMobile("1.9.1")}}{{CompatUnknown}}{{CompatNo}}10.0{{CompatVersionUnknown}}
WOFF{{CompatNo}}{{CompatGeckoMobile("5.0")}}{{CompatUnknown}}{{CompatNo}}11.0{{CompatNo}}
SVG 字型{{CompatNo}}{{CompatNo}}
+ {{unimplemented_inline(119490)}}
{{CompatUnknown}}{{CompatNo}}10.0{{CompatVersionUnknown}}
unicode-range     {{CompatVersionUnknown}}
+
+ +

注意事項

+ + + +

詳見

+ + diff --git a/files/zh-tw/web/css/@media/height/index.html b/files/zh-tw/web/css/@media/height/index.html new file mode 100644 index 0000000000..cb15e99e80 --- /dev/null +++ b/files/zh-tw/web/css/@media/height/index.html @@ -0,0 +1,77 @@ +--- +title: height +slug: Web/CSS/@media/height +translation_of: Web/CSS/@media/height +--- +

height 屬於 CSS 的媒體功能之一,其值為可視區域 (viewport) 的高度,像是 CSS 的 <length>

+ +

規格

+ + + + + + + + + + + + + + + + +
規格狀態註釋
{{SpecName('CSS3 Media Queries', '#height', 'height')}}{{Spec2('CSS3 Media Queries')}}初始定義。
+ +

瀏覽器相容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

 

diff --git a/files/zh-tw/web/css/@media/index.html b/files/zh-tw/web/css/@media/index.html new file mode 100644 index 0000000000..11f39d07b6 --- /dev/null +++ b/files/zh-tw/web/css/@media/index.html @@ -0,0 +1,377 @@ +--- +title: '@media' +slug: Web/CSS/@media +tags: + - At-rule + - CSS + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/CSS/@media +--- +

{{CSSRef}}

+ +

概要

+ +

@media CSS at-rule 與一組被大括弧隔開、並由 media query 條件定義的 CSS 巢狀區塊有關。@media at-rule 不只能用在最頂層的 CSS 區塊,也能在任何 CSS conditional-group at-rule 使用。

+ +

@media at-rule 能透過 CSS object model 介面 {{domxref("CSSMediaRule")}} 通行。

+ +

語法

+ +
{{csssyntax}}
+ +

A <media-query> is composed of a optional media type and/or a number of media features.

+ +

Media types

+ +
+
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. Note: CSS2 had a similar media type called 'aural' for this purpose. See the appendix on aural style sheets for details.
+
+ +
Note: CSS2.1 and Media Queries 3 defined several additional media types (tty, tv, projection, handheld, braille, embossed, aural), but they were deprecated in Media Queries 4 and shouldn't be used.
+ +

Media Features

+ +

Each media feature tests for one specific feature of the browser or device.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameSummaryNotes
widthViewport width
heightViewport height
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
gridIs the device a grid or bitmap?
update-frequencyHow quickly (if at all) can the output device modify the appearance of the 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-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 member.Defined in the Web App Manifest spec.
monochromeBits per pixel in the output device's monochrome frame buffer, or 0 if the device is not monochrome.
inverted-colorsIs the user agent or underlying OS inverting colors?Added in Media Queries Level 4
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-levelCurrent ambient light levelAdded in Media Queries Level 4
scriptingIs scripting (e.g. JavaScript) available?Added in Media Queries Level 4
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
-webkit-transform-2d {{non-standard_inline}}Are CSS 2D {{cssxref("transform")}}s supported?Nonstandard; WebKit-specific
-webkit-transition {{non-standard_inline}}Are CSS {{cssxref("transition")}}s supported?Nonstandard; WebKit-specific
-webkit-animation {{non-standard_inline}}Are CSS {{cssxref("animation")}}s supported?Nonstandard; WebKit-specific
+ +

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

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

Added scripting, pointer, hover, light-level, update-frequency, overflow-block, and overflow-inline media features.
+ Deprecated all media types except for screen, print, speech, and all.
+ Made 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) }}{{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}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

See also

+ + diff --git a/files/zh-tw/web/css/@viewport/height/index.html b/files/zh-tw/web/css/@viewport/height/index.html new file mode 100644 index 0000000000..e883d44041 --- /dev/null +++ b/files/zh-tw/web/css/@viewport/height/index.html @@ -0,0 +1,120 @@ +--- +title: height +slug: Web/CSS/@viewport/height +translation_of: Web/CSS/@viewport +--- +
{{CSSRef}}
+ +

概要

+ +

高度 的 CSS 描述符是用於設定兩者的簡易描述符 {{cssxref("@viewport/min-height", "min-height")}} 與 {{cssxref("@viewport/max-height", "max-height")}} 的可視區域(viewport)。提供一個可視區域的長度值,將設定兩者的最小高度與最大高度的值。

+ +

如果提供了兩個可視區域(viewport),第一個值將設定為最小高度,而第二個值將設定為最大高度。

+ +

語法

+ +
/* One value */
+height: auto;
+height: 320px;
+height: 15em;
+
+/* Two values */
+height: 320px 200px;
+
+ +

+ +
+
auto
+
使用 CSS 描述符來進行值的計算。
+
<length>
+
非負絕對值或相對長度。
+
<percentage>
+
初始可視區域的相對寬度或相對高度百分比的縮放係數為 1.0,且必須是非負數。
+
+ +

正式語法

+ +
{{csssyntax}}
+
+ +

舉例

+ +
@viewport {
+  height: 500px;
+}
+ +

格式

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Device', '#descdef-viewport-height', '"height" descriptor')}}{{Spec2('CSS3 Device')}}Initial definition
+ +

瀏覽器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support29 (behind a flag){{CompatNo}}10 {{property_prefix("-ms")}}11.10
+ Removed in 15
+ Reintroduced behind a flag in 16
{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support4.429{{CompatNo}}10{{property_prefix("-ms")}}11.10
+ Removed in 15
+ Reintroduced behind a flag in 16
{{CompatNo}}
+
diff --git a/files/zh-tw/web/css/@viewport/index.html b/files/zh-tw/web/css/@viewport/index.html new file mode 100644 index 0000000000..f03aaee77b --- /dev/null +++ b/files/zh-tw/web/css/@viewport/index.html @@ -0,0 +1,159 @@ +--- +title: '@viewport' +slug: Web/CSS/@viewport +tags: + - Adaptation + - At-rule + - CSS + - Device + - NeedsContent + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/CSS/@viewport +--- +

{{CSSRef}}

+ +

Summary

+ +

The @viewport CSS at-rule contains a set of nested descriptors in a CSS block that is delimited by curly braces. These descriptors control viewport settings, primarily on mobile devices.

+ +

Syntax

+ +

A zoom factor of 1.0 or 100% corresponds to no zooming. Larger values zoom in. Smaller values zoom out.

+ +

Descriptors

+ +

Browsers are supposed to ignore unrecognized descriptors.

+ +
+
min-width
+
Used in the determination of the width of the viewport when the document is first displayed.
+
max-width
+
Used in the determination of the width of the viewport when the document is first displayed.
+
width
+
A shorthand descriptor for setting both min-width and max-width
+
min-height
+
Used in the determination of the height of the viewport when the document is first displayed.
+
max-height
+
Used in the determination of the height of the viewport when the document is first displayed.
+
height
+
A shorthand descriptor for setting both min-height and max-height
+
zoom
+
Sets the initial zoom factor.
+
min-zoom
+
Sets the minimum zoom factor.
+
max-zoom
+
Sets the maximum zoom factor.
+
user-zoom
+
Controls whether or not the user should be able to change the zoom factor.
+
orientation
+
Controls the document's orientation.
+
+ +

Formal syntax

+ +
{{csssyntax}}
+ +

Examples

+ +
@viewport {
+  min-width: 640px;
+  max-width: 800px;
+}
+@viewport {
+  zoom: 0.75;
+  min-zoom: 0.5;
+  max-zoom: 0.9;
+}
+@viewport {
+  orientation: landscape;
+}
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Device', '#the-atviewport-rule', '@viewport')}}{{Spec2('CSS3 Device')}}Initial definition
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support29 (behind a flag) [4]{{CompatNo()}} [2]10 {{property_prefix("-ms")}}11.10
+ Removed in 15
+ Reintroduced behind a flag in 16
{{CompatNo}} [3]
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support4.429{{CompatNo}} [2]10{{property_prefix("-ms")}}[1]11.10
+ Removed in 15
+ Reintroduced behind a flag in 16
{{CompatNo}} [3]
+
+ +

[1] There is a bug in IE Mobile 10 on older versions of Windows Phone 8, where device-width, when used within @-ms-viewport, evaluates to the screen width in physical pixels rather than normalized CSS pixels, which is wrong according to the specification. However, when used within a viewport {{HTMLElement("meta")}} tag, device-width evaluates correctly. According to Microsoft, this bug was fixed in Windows Phone 8 Update 3 (a.k.a. GDR3), although there are some reports that the Lumia Black GDR3 update did not fix the bug (at least on the Lumia 920). For more details and a workaround, see Tim Kadlec's blog post "Windows Phone 8 and Device-Width".

+ +

[2]: See {{bug(747754, 'summary')}}

+ +

[3]: See {{webkitbug(95959)}}

+

[4]: See Chromium issue #235457: Enable @viewport on all platforms

+

See also

+ + diff --git a/files/zh-tw/web/css/_colon_first-child/index.html b/files/zh-tw/web/css/_colon_first-child/index.html new file mode 100644 index 0000000000..195449ca3d --- /dev/null +++ b/files/zh-tw/web/css/_colon_first-child/index.html @@ -0,0 +1,154 @@ +--- +title: ':first-child' +slug: 'Web/CSS/:first-child' +tags: + - CSS + - CSS Pseudo-class + - Layout + - Reference + - Web +translation_of: 'Web/CSS/:first-child' +--- +
{{CSSRef}}
+ +

:first-childCSS當中的一種偽類別(pseudo-class),代表任何身為長子的元素(親元素的第一個子元素)。

+ +

語法

+ +
{{csssyntax}}
+
+ +

範例

+ +

範例 1

+ +

HTML 內文

+ +
<div>
+  <span>This span is limed!</span>
+  <span>This span is not. :(</span>
+</div>
+
+ +

CSS 內文

+ +
span:first-child {
+    background-color: lime;
+}
+
+ +

呈現效果如下:

+ +

{{EmbedLiveSample('範例_1',300,50)}}

+ +

範例 2 - 使用 UL

+ +

HTML 內文

+ +
<ul>
+  <li>List 1</li>
+  <li>List 2</li>
+  <li>List 3</li>
+</ul>
+ +

CSS 內文

+ +
li{
+  color:red;
+}
+li:first-child{
+  color:green;
+}
+ +

呈現效果如下:

+ +

{{EmbedLiveSample('範例_2_-_使用_UL',300,100)}}

+ +

規格

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
規格狀態註解
{{SpecName('CSS4 Selectors', '#first-child-pseudo', ':first-child')}}{{Spec2('CSS4 Selectors')}}無變更
{{SpecName('CSS3 Selectors', '#first-child-pseudo', ':first-child')}}{{Spec2('CSS3 Selectors')}}無變更
{{SpecName('CSS2.1', 'selector.html#first-child', ':first-child')}}{{Spec2('CSS2.1')}}初始定義
+ +

瀏覽器相容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
功能ChromeFirefox (Gecko)Internet ExplorerOperaSafari
基礎支援4.0{{CompatGeckoDesktop("1.9")}}7[1]9.54
+
+ +
+ + + + + + + + + + + + + + + + + + + +
功能AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
基礎支援1.0{{CompatGeckoMobile("1.9.1")}}7[1]10.03.1
+
+ +

[1] 在不重新載入網頁的情況下,Internet Explorer 7 的樣式表並不會套用在動態新增的元素上。在 Internet Explorer 8,若元素是以點擊連結而形成的,則 first-child 在該連結不被選取後才有作用。

+ +

參見

+ + diff --git a/files/zh-tw/web/css/_colon_first-of-type/index.html b/files/zh-tw/web/css/_colon_first-of-type/index.html new file mode 100644 index 0000000000..93a524c4b7 --- /dev/null +++ b/files/zh-tw/web/css/_colon_first-of-type/index.html @@ -0,0 +1,162 @@ +--- +title: ':first-of-type' +slug: 'Web/CSS/:first-of-type' +tags: + - CSS + - CSS 虛擬類別 + - 參考 + - 外觀 + - 網頁 +translation_of: 'Web/CSS/:first-of-type' +--- +
{{CSSRef}}
+ +

在 CSS 虛擬類別(pseudo-class)中,:first-of-type 代表本節點為兄弟節點中第一個此類型節點。

+ +
/* 選取第一個出現在父節點下的<p>,不考慮其在所有子節點中的位置。 */
+p:first-of-type {
+  color: red;
+}
+ +
+

附註: 在初始定義中,被選取的節點必須擁有父節點。從選取器層級4(Selectors Level 4)開始已經不再有這個限制了。

+
+ +

語法

+ +
{{csssyntax}}
+
+ +

範例

+ +

例一:選取第一段文章

+ +

來考慮以下 HTML:

+ +
<h2>Heading</h2>
+
+<p>Paragraph</p>
+
+<p>Paragraph</p>
+ +

及 CSS:

+ +
p:first-of-type {
+  color: red;
+}
+ +

會有這樣的效果 - 只有第一段文章變為紅色,因為它是 body 中第一個文章節點:

+ +

{{EmbedLiveSample('Example_1_Simple_first_paragraph')}}

+ +

例二:預定通用選擇器(Assumed universal selector)

+ +

這個範例展示了當沒有指定一般選擇器(simple selector)時,通用選擇器是如何被預判。

+ +

首先來看 HTML:

+ +
<div>
+  <span>This `span` is first!</span>
+  <span>But this `span` isn't.</span>
+  <span>This <em>nested `em` is</em>!</span>
+  <span>And so is this <span>nested `span`</span>!</span>
+  <b>This `b` qualifies!</b>
+  <span>This final `span` does not.</span>
+</div>
+
+ +

接著是 CSS:

+ +
div :first-of-type {
+  background-color: lime;
+}
+ +

會有這樣的效果:

+ +

{{EmbedLiveSample('Example_2_Assumed_universal_selector','100%', '120')}}

+ +

特定規格

+ + + + + + + + + + + + + + + + + + + + + +
規格狀態附註
{{SpecName('CSS4 Selectors', '#first-of-type-pseudo', ':first-of-type')}}{{Spec2('CSS4 Selectors')}}配對節點不需要具有父節點。
{{SpecName('CSS3 Selectors', '#first-of-type-pseudo', ':first-of-type')}}{{Spec2('CSS3 Selectors')}}初始定義。
+ +

瀏覽器相容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1.0{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.1")}}9.09.53.2
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support2.1{{CompatVersionUnknown}}{{CompatGeckoMobile("1.9.1")}}9.010.03.2
+
+ +

參見

+ + diff --git a/files/zh-tw/web/css/_colon_lang/index.html b/files/zh-tw/web/css/_colon_lang/index.html new file mode 100644 index 0000000000..f79d142f09 --- /dev/null +++ b/files/zh-tw/web/css/_colon_lang/index.html @@ -0,0 +1,98 @@ +--- +title: ':lang()' +slug: 'Web/CSS/:lang' +translation_of: 'Web/CSS/:lang' +--- +
{{CSSRef}}
+ +

:lang() 是一種 CSS 偽類 ( pseudo-class )。它會根據括號中指定的語系,來選擇使用的元素。

+ +
/* 選取任何語言屬性為英文 (en) 的 <p> */
+p:lang(en) {
+  quotes: '\201C' '\201D' '\2018' '\2019';
+}
+ +
+

注意: 在 HTML 中,語言是通過 {{htmlattrxref("lang")}} 屬性和 {{HTMLElement("meta")}} 元素的組合來決定的, 也可能是通過協議的信息來確定 (例如 HTTP 表頭). 對於其他文檔類型,也可能存在其他用於確定語言的方法。

+
+ +

語法 Syntax

+ +

語法格式 Formal syntax

+ +
{{csssyntax}}
+ +

參數 Parameter

+ +
+
<language-code>
+
{{cssxref("<string>")}} 代表你要指定的語言。可接受的值為 HTML 規範中指定的值。
+
+ +

範例 Example

+ +

在此例中,:lang() 偽類 會依據 “引用元素 quote” ({{htmlElement("q")}}) 的父層來選擇 子組合子 ( child combinators )。 請注意,此處演示的方法並不是唯一的,並且最好的方式,是依據文檔類型來確定。還要注意的是, {{glossary("Unicode")}} 的值,有明確指定到那些你要使用的字符。

+ +

HTML

+ +
<div lang="en"><q>This English quote has a <q>nested</q> quote inside.</q></div>
+<div lang="fr"><q>This French quote has a <q>nested</q> quote inside.</q></div>
+<div lang="de"><q>This German quote has a <q>nested</q> quote inside.</q></div>
+
+ +

CSS

+ +
:lang(en) > q { quotes: '\201C' '\201D' '\2018' '\2019'; }
+:lang(fr) > q { quotes: '« ' ' »'; }
+:lang(de) > q { quotes: '»' '«' '\2039' '\203A'; }
+
+ +

結果 Result

+ +

{{EmbedLiveSample('Example', 350)}}

+ +

技術規格 Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
規格 Specification狀態 Status註 Comment
{{SpecName('CSS4 Selectors', '#lang-pseudo', ':lang()')}}{{Spec2('CSS4 Selectors')}}Adds wildcard language matching and comma-separated list of languages.
+ 添加萬用字符語言匹配,且逗號分隔語言列表。
{{SpecName('CSS3 Selectors', '#lang-pseudo', ':lang()')}}{{Spec2('CSS3 Selectors')}}沒有重大變化。
{{SpecName('CSS2.1', 'selector.html#lang', ':lang()')}}{{Spec2('CSS2.1')}}初步定義。
+ +

瀏覽器兼容性 Browser compatibility

+ +
+ + +

{{Compat("css.selectors.lang")}}

+
+ +

其他參考 See also

+ + diff --git a/files/zh-tw/web/css/_colon_target/index.html b/files/zh-tw/web/css/_colon_target/index.html new file mode 100644 index 0000000000..74d1767fb9 --- /dev/null +++ b/files/zh-tw/web/css/_colon_target/index.html @@ -0,0 +1,275 @@ +--- +title: ':target' +slug: 'Web/CSS/:target' +translation_of: 'Web/CSS/:target' +--- +
{{CSSRef}}
+ +

The :target pseudo-class represents the unique element, if any, with an id matching the fragment identifier of the URI of the document..

+ +

URIs with fragment identifiers link to a certain element within the document, known as the target element. For instance, here is a URI pointing to an anchor named section2:
+ http://example.com/folder/document.html#section2
+ The anchor can be any element with an id attribute, e.g. <h1 id="section2"> in our example. The target element h1 can be represented by the :target pseudo-class.

+ +
Note: The id attribute was new in HTML 4 (December 1997).  In old-style HTML <a> is a target element.  The :target pseudo-class applies to those targets as well.
+ +

範例

+ +
:target { outline: solid red }  /* draw a red, solid line around the target element */
+
+ +
/* example code for userContent.css or any web pages;
+   a red/yellow arrow indicates the target element */
+
+:target {
+ -webkit-box-shadow: 0.2em 0.2em 0.3em #888;
+    -moz-box-shadow: 0.2em 0.2em 0.3em #888;
+         box-shadow: 0.2em 0.2em 0.3em #888;
+}
+
+:target:before {
+  font:           70% Arial,"Nimbus Sans L",sans-serif !important;
+  content:        "\25ba";  /* ► */
+  color:          red;
+  background:     gold;
+  border:         solid thin;
+  padding-left:   1px;
+  display:        inline-block;
+  margin-right:   0.13em;
+  vertical-align: 20%;
+}
+
+ +

Working with display: none elements…

+ +

The :target pseudo-class also works fine with undisplayed elements:

+ +
<!DOCTYPE html>
+<html>
+<head>
+<meta charset="UTF-8">
+<title>:target pseudoclass example</title>
+<style>
+#newcomment {
+  display: none;
+}
+
+#newcomment:target {
+  display: block;
+}
+</style>
+
+</head>
+<body>
+ <p><a href="#newcomment">Add a comment</a></p>
+ <div id="newcomment">
+  <form>
+  <p>Write your comment:<br />
+  <textarea></textarea></p>
+  </form>
+ </div>
+</body>
+</html>
+
+ +

Creating a pure CSS "lightbox"

+ +

The :target pseudo-class is useful to switch on/off some invisible elements. In this way you can create a pure-CSS lightbox (live demo).

+ +
+
<!DOCTYPE html>
+<html>
+<head>
+<meta charset="UTF-8" />
+<title>MDN Example &ndash; CSS Lightbox</title>
+<style type="text/css">
+div.lightbox {
+  display: none;
+  position: fixed;
+  left: 0;
+  top: 0;
+  width: 100%;
+  height: 100%;
+}
+
+div.lightbox:target {
+  display: table;
+}
+
+div.lightbox figure {
+  display: table-cell;
+  margin: 0;
+  padding: 0;
+  width: 100%;
+  height: 100%;
+  vertical-align: middle;
+}
+
+div.lightbox figure figcaption {
+  display: block;
+  margin: auto;
+  padding: 8px;
+  background-color: #ddbbff;
+  height: 250px;
+  position: relative;
+  overflow: auto;
+  border: 1px #000000 solid;
+  border-radius: 10px;
+  text-align: justify;
+  font-size: 14px;
+}
+
+div.lightbox figure .closemsg {
+  display: block;
+  margin: auto;
+  height: 0;
+  overflow: visible;
+  text-align: right;
+  z-index: 2;
+  cursor: default;
+}
+
+div.lightbox figure .closemsg, div.lightbox figure figcaption {
+  width: 300px;
+}
+
+.closemsg::after {
+  content: "\00D7";
+  display: inline-block;
+  position: relative;
+  right: -20px;
+  top: -10px;
+  z-index: 3;
+  color: #ffffff;
+  border: 1px #ffffff solid;
+  border-radius: 10px;
+  width: 20px;
+  height: 20px;
+  line-height: 18px;
+  text-align: center;
+  margin: 0;
+  background-color: #000000;
+  font-weight: bold;
+  cursor: pointer;
+}
+
+.closemsg::before {
+  content: "";
+  display: block;
+  position: fixed;
+  left: 0;
+  top: 0;
+  width: 100%;
+  height: 100%;
+  background-color: #000000;
+  opacity: 0.85;
+}
+</style>
+</head>
+
+<body>
+
+<h1>Pure CSS Lightbox</h1>
+
+<p>Some sample text&hellip;</p>
+
+<p>[ <a href="#example1">Open example #1</a> | <a href="#example2">Open example #2</a> ]</p>
+
+<p>Another sample text&hellip;</p>
+
+<div class="lightbox" id="example1">
+  <figure>
+    <a href="#" class="closemsg"></a>
+    <figcaption>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec felis enim, placerat id eleifend eu, semper vel sem. Sed interdum commodo enim venenatis pulvinar. Proin mattis lorem vitae diam scelerisque hendrerit. Fusce cursus imperdiet mauris, vitae hendrerit velit dignissim a. Suspendisse potenti. Aenean feugiat facilisis diam, in posuere sapien mattis vel. Proin molestie rutrum diam, pharetra feugiat ligula sollicitudin sed. Etiam cursus diam quis tellus aliquam gravida. Aliquam erat volutpat.<br />
+    Etiam varius adipiscing mi eget imperdiet. Nulla quis vestibulum leo. Integer molestie massa ut massa commodo in blandit purus aliquam. Mauris sit amet posuere massa. Ut a eleifend augue. Proin sodales mauris nec tellus pharetra dictum.</figcaption>
+  </figure>
+</div>
+
+<div class="lightbox" id="example2">
+  <figure>
+    <a href="#" class="closemsg"></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. Etiam ullamcorper augue quis orci posuere et tincidunt augue semper. Maecenas varius augue eu orci auctor bibendum tristique ligula egestas. Morbi pharetra tortor iaculis erat porta id aliquam leo cursus. Ut nec elit vel mauris dapibus lacinia eget sed odio.</figcaption>
+  </figure>
+</div>
+
+</body>
+</html>
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("CSS4 Selectors", "#the-target-pseudo", ":target")}}{{Spec2("CSS4 Selectors")}}No changes
{{SpecName("CSS3 Selectors", "#target-pseudo", ":target")}}{{Spec2("CSS3 Selectors")}}Initial definition
+ +

瀏覽器兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1.0{{CompatGeckoDesktop("1.3")}}99.51.3
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support2.1{{CompatGeckoMobile("1.3")}}9.09.52.0
+
+ +

參見

+ + diff --git a/files/zh-tw/web/css/_doublecolon_first-letter/index.html b/files/zh-tw/web/css/_doublecolon_first-letter/index.html new file mode 100644 index 0000000000..b9d4c7a6f9 --- /dev/null +++ b/files/zh-tw/web/css/_doublecolon_first-letter/index.html @@ -0,0 +1,206 @@ +--- +title: '::first-letter (:first-letter)' +slug: 'Web/CSS/::first-letter' +translation_of: 'Web/CSS/::first-letter' +--- +

{{ CSSRef() }}

+ +

概要

+ +

::first-letter CSS 虛擬元素選取了一個區塊第一行的第一個字母,如果那一行前面沒有其他內容(例如圖片或是行內表格)。

+ +

The first letter of an element is not necessarily trivial to identify:

+ + + +

A first line has meaning only in a block-container box, therefore the ::first-letter pseudo-element has an effect only on elements with a {{ cssxref("display") }} value of block, inline-block, table-cell, list-item or table-caption. In all other cases, ::first-letter has no effect.

+ +

Only a small subset of all CSS properties can be used inside a declaration block of a CSS ruleset containing a selector using the ::first-letter pseudo-element:

+ + + +

As this list will be extended in the future, it is recommended that you not use any other properties inside the declaration block, in order to keep the CSS future-proof.

+ +
+

In CSS 2, pseudo-elements were prefixed with a single colon character. As pseudo-classes were also following the same convention, they were indistinguishable. To solve this, CSS 2.1 changed the convention for pseudo-elements. Now a pseudo-element is prefixed with two colon characters, and a pseudo-class is still prefixed with a single colon.

+ +

As several browsers already implemented the CSS 2 version in a release version, all browsers supporting the two-colon syntax also support the old one-colon syntax.

+ +

If legacy browsers must be supported, :first-letter is the only viable choice; if not, ::first-letter is preferred.

+
+ +

Example

+ +

Make the first letter of every paragraph red and big.

+ +

HTML Content

+ +
<p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt
+  ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo
+  dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est. Lorem ipsum dolor
+  sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy amet.</p>
+<p>Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat.</p>
+<p>Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut
+  aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit
+  esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et
+  iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait
+  nulla facilisi.</p>
+<p>-The beginning of a special punctuation mark.</p>
+<p>_The beginning of a special punctuation mark.</p>
+<p>"The beginning of a special punctuation mark.</p>
+<p>'The beginning of a special punctuation mark.</p>
+<p>*The beginning of a special punctuation mark.</p>
+<p>#The beginning of a special punctuation mark.</p>
+<p>「特殊的汉字标点符号开头。</p>
+<p>《特殊的汉字标点符号开头。</p>
+<p>“特殊的汉字标点符号开头。</p>
+ +

CSS Content

+ +
p::first-letter { /* Use :first-letter if support for IE 8 or earlier is needed */
+  color: red;
+  font-size: 130%;
+}
+ +

Output

+ +

{{ EmbedLiveSample('Example', 679, 390) }}

+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
規範狀態註解
{{ SpecName('CSS4 Pseudo-Elements', '#first-letter-pseudo', '::first-letter')}}{{ Spec2('CSS4 Pseudo-Elements')}}Generalized allowed properties to typesetting, text decoration and inline layout properties, {{ cssxref("opacity") }} and {{ cssxref("box-shadow") }}.
{{ SpecName('CSS3 Text Decoration', '#text-shadow', 'text-shadow with ::first-letter')}}{{ Spec2('CSS3 Text Decoration')}}Allowed the usage of {{cssxref("text-shadow")}} with ::first-letter.
{{ SpecName('CSS3 Selectors', '#first-letter', '::first-letter') }}{{ Spec2('CSS3 Selectors') }}Defined edge-case behavior like in list items, or with language specific behavior (like the Dutch digraph IJ). The two-colon syntax for pseudo-elements has been introduced.
{{ SpecName('CSS2.1', 'selector.html#first-letter', '::first-letter') }}{{ Spec2('CSS2.1') }}No significant change, though CSS Level 2 still used the one-colon syntax.
{{ SpecName('CSS1', '#the-first-letter-pseudo-element', '::first-letter') }}{{ Spec2('CSS1') }}The initial definition used the one-colon syntax.
+ +

瀏覽器相容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support1.0{{ CompatGeckoDesktop("1") }}9.07.01.0 (85)
Old one-colon syntax (:first-letter)1.0{{ CompatGeckoDesktop("1") }}5.53.51.0 (85)
Support for the Dutch digraph IJ{{ CompatNo() }}{{ CompatNo() }} {{ bug("92176") }} {{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}{{ CompatGeckoMobile("1") }}{{ CompatNo() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
Old one-colon syntax (:first-letter){{ CompatUnknown() }}{{ CompatGeckoMobile("1") }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
Support for the Dutch digraph IJ{{ CompatUnknown() }}{{ CompatNo() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

參見

+ + diff --git a/files/zh-tw/web/css/animation-fill-mode/index.html b/files/zh-tw/web/css/animation-fill-mode/index.html new file mode 100644 index 0000000000..9ac0552304 --- /dev/null +++ b/files/zh-tw/web/css/animation-fill-mode/index.html @@ -0,0 +1,158 @@ +--- +title: animation-fill-mode +slug: Web/CSS/animation-fill-mode +translation_of: Web/CSS/animation-fill-mode +--- +
 
+ +

animation-fill-mode  CSS 属性指定CSS动画应该如何在其执行前后的样式展示情况。

+ +
/* 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;
+
+ +

使用提示 animation 来一次设置所有动画属性通常很方便。

+ +

语法

+ +

属性值

+ +
+
none
+
不执行动画时,动画不会应用任何样式。该元素会使用其keyframes关键动画帧规则来显示动画。这是默认值。
+
forwards
+
动画执行后停留到最后一个关键帧动画的计算值,简单来说执行结束动画会停留到结束时候的状态,不会是动画执行之前的效果。比如一个元素从左往右运动,添加当前属性值 forwards 元素会停留到动画执行结束后的右边而不是最初的左边。可以看以下图
+
+
当然最后动画停留显示的关键帧会取决于 "animation-direction" 和 "animation-iteration-count"这两个属性 运行方向和运行次数: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
animation-directionanimation-iteration-countlast keyframe encountered
normal偶数或奇数值100% 或 to
reverse偶数或奇数值0%from
alternate偶数值0%from
alternate奇数值100%to
alternate-reverse偶数值100%to
alternate-reverse奇数值0%from
+
+
backwards
+
与上面 forwards 值效果相反,动画执行后停留到第一个关键帧动画,准确说是没有执行动画之前的初始状态
+
【(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 "animation-delay" period.)原文大概意思是会停留第一个关键帧,并会保留 "animation-delay" 延迟属性的所设定周期。】
+
会在延迟之后才开始执行关键帧动画,而不是一开始使用第一帧进行停留,具体可以结合both的例子进行尝试。
+
+
第一个相关关键帧会取决于 "animation-direction" 方向属性: + + + + + + + + + + + + + + + + + +
animation-directionfirst relevant keyframe
normal 或 alternate0%from
reversealternate-reverse100%to
+
+
+ +
+
both
+
动画将遵循开始和结束后的帧动画进行停留,也就是说会从第一帧开始停留显示,动画执行之后会停留到动画结束时的状态。
+
+
与上面两个值的差别是,如果元素使用 forwardsbackwards 两个值会在没有添加动画之前的展示状态进行停留,执行动画的时候才会开始执行关键帧,有这么一些细小的差别。
+
+ +
+

PS: 当您在一个animation-*属性上指定多个逗号分隔的值时,它们将被分配给 "animationname" 属性中指定的动画,这取决于有多少动画。有关更多信息,请参见设置多个动画属性值

+
+ +

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

 

+ +

查看 CSS animations 更多有關的例子

+ +

相關鏈接

+ + diff --git a/files/zh-tw/web/css/attr()/index.html b/files/zh-tw/web/css/attr()/index.html new file mode 100644 index 0000000000..7cce14ec01 --- /dev/null +++ b/files/zh-tw/web/css/attr()/index.html @@ -0,0 +1,200 @@ +--- +title: attr +slug: Web/CSS/attr() +translation_of: Web/CSS/attr() +--- +
{{CSSRef}}
+ +

概要

+ +

attr() CSS 函數使用於樣式取得被選取之元素中特定屬性的值。它也可以用在擬元素選取項(Pseudo-element),在此情形下,其屬性值來自於擬元素選取項相依的原始元素。

+ +

attr() 函數可以被用在任何 CSS 屬性,但除了 content 以外的屬性皆屬於實驗階段。

+ +

語法

+ +
/* Simple usage */
+attr(data-count);
+attr(title);
+
+/* With type */
+attr(src url);
+attr(data-count number);
+attr(data-width px);
+
+/* With fallback */
+attr(data-count number, 0);
+attr(src url, '');
+attr(data-width px, inherit);
+attr(data-something, 'default');
+
+ +

+ +
+
attribute-name
+
在 CSS 中參考之 HTML 元素的屬性名稱。
+
<type-or-unit> {{experimental_inline}}
+
Is a keyword representing either the type of the attribute's value, or its unit, as in HTML some attributes have implicit units. If the use of <type-or-unit> as a value for the given attribute is invalid, the attr() expression will be invalid too. If omitted, it defaults to string. The list of valid values are: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
KeywordAssociated typeCommentDefault value
string{{cssxref("<string>")}}The attribute value is treated as a CSS {{cssxref("<string>")}}.  It is NOT reparsed, and in particular the characters are used as-is instead of CSS escapes being turned into different characters.An empty string
color {{experimental_inline}}{{cssxref("<color>")}}The attribute value is parsed as a hash (3- or 6-value hash) or a keyword. It must be a valid CSS {{cssxref("<string>")}} value.
+ Leading and trailing spaces are stripped.
currentColor
url {{experimental_inline}}{{cssxref("<uri>")}}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>.
+
+ +

形式語法

+ +
{{csssyntax}}
+ +

範例

+ +
p::before {
+  content: attr(data-foo) " ";
+}
+
+ +
<p data-foo="hello">world</p>
+
+ +

結果

+ +

{{EmbedLiveSample("Examples", '100%', '80')}}

+ +

規範

+ + + + + + + + + + + + + + + + + + + + + +
規範狀態註解
{{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>")}}.
+ +

瀏覽器相容性

+ +

{{Compat("css.types.attr")}}

diff --git a/files/zh-tw/web/css/background-attachment/index.html b/files/zh-tw/web/css/background-attachment/index.html new file mode 100644 index 0000000000..138623a543 --- /dev/null +++ b/files/zh-tw/web/css/background-attachment/index.html @@ -0,0 +1,151 @@ +--- +title: background-attachment +slug: Web/CSS/background-attachment +tags: + - CSS + - CSS Background + - CSS Property + - Reference +translation_of: Web/CSS/background-attachment +--- +
{{CSSRef}}
+ +

background-attachment 這個 CSS 屬性能夠設定,背景圖片的位置是否要固定在 {{glossary("viewport")}}(視圖)上,還是背景圖片會隨著它的 containing block(外層容器)一起滾動。

+ +
{{EmbedInteractiveExample("pages/css/background-attachment.html")}}
+ + + +

語法

+ +
/* Keyword values */
+background-attachment: scroll;
+background-attachment: fixed;
+background-attachment: local;
+
+/* Global values */
+background-attachment: inherit;
+background-attachment: initial;
+background-attachment: unset;
+
+ +

background-attachment 屬性的值,可以是下方清單中的其中之一。

+ +

Values

+ +
+
fixed
+
讓背景相對於 viewport(視圖)的移動是固定的。即便元素中的內容是可滾動的,背景也不會在滾動元素內容時跟著移動。(這個屬性與 {{cssxref("background-clip", "background-clip: text", "#text")}} 不相容。)
+
local
+
讓背景相對於元素的內容是固定的,且背景在滾動元素的內容時會跟著移動。另外,背景的繪製與定位區域是相對於元素的可滾動區域,而不是包裹著它們的邊框。
+
scroll
+
讓背景相對於元素本身是固定的,使背景在滾動元素的內容時不會跟著移動。(It is effectively attached to the element's border.)
+
+ +

Formal syntax

+ +
{{csssyntax}}
+
+ +

例子

+ +

Simple example

+ +

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

CSS

+ +
p {
+  background-image: url("https://mdn.mozillademos.org/files/12057/starsolid.gif");
+  background-attachment: fixed;
+}
+
+ +

Result

+ +

{{EmbedLiveSample("Simple_example")}}

+ +

Multiple background images

+ +

這個屬性支援多個背景圖片。你可以對每個背景設定不同的 <attachment>。每個背景圖片會依序對應在 <attachment> 設定的類型。

+ +

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

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

Result

+ +

{{EmbedLiveSample("Multiple_background_images")}}

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{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')}}No significant change.
{{SpecName('CSS1', '#background-attachment', 'background-attachment')}}{{Spec2('CSS1')}}No significant change.
+ +

{{cssinfo}}

+ +

Browser compatibility

+ + + +

{{Compat("css.properties.background-attachment")}}

+ +

See also

+ + diff --git a/files/zh-tw/web/css/background-color/index.html b/files/zh-tw/web/css/background-color/index.html new file mode 100644 index 0000000000..3c5cea28b3 --- /dev/null +++ b/files/zh-tw/web/css/background-color/index.html @@ -0,0 +1,115 @@ +--- +title: background-color +slug: Web/CSS/background-color +translation_of: Web/CSS/background-color +--- +
{{CSSRef}}
+ +

background-color CSS property 是用來設定HTML元素的背景顏色,值可以是顏色亦可以是特定關鍵字-- transparent.

+ +

語法

+ +
background-color: red;
+background-color: rgb(255, 255, 128);
+background-color: hsla(50, 33%, 25%, 0.75);
+background-color: currentColor;
+background-color: transparent;
+background-color: #bbff00;
+
+background-color: inherit;
+
+ +

參數

+ +
+
<color>
+
一個 CSS {{cssxref("<color>")}} 用來表示一致的背景顏色。即便設定了一個或多個 {{cssxref("background-image")}} ,背景渲染上依舊會渲染這顏色,若是圖片並非不透明圖,在透明區域就能看見。在 CSS 中, transparent 是一種顏色
+
+ +

正式語法

+ +
{{csssyntax}}
+ +

範例

+ +

HTML

+ +
<div class="exampleone">
+ Lorem ipsum dolor sit amet, consectetuer
+</div>
+
+<div class="exampletwo">
+  Lorem ipsum dolor sit amet, consectetuer
+</div>
+
+<div class="examplethree">
+  Lorem ipsum dolor sit amet, consectetuer
+</div>
+ +

CSS

+ +
.exampleone {
+  background-color: teal;
+  color: white;
+}
+
+.exampletwo {
+  background-color: rgb(153,102,153);
+  color: rgb(255,255,204);
+}
+
+.examplethree {
+  background-color: #777799;
+  color: #FFFFFF;
+}
+
+ +

Result

+ +

{{EmbedLiveSample("範例","200","150")}}

+ +

規格定義

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Backgrounds', '#background-color', 'background-color')}}{{Spec2('CSS3 Backgrounds')}}技術上來說,移除了 transparent 關鍵字,但實際上並未發生任何改變,因為它被列入至正式的 {{cssxref("<color>")}}
{{SpecName('CSS2.1', 'colors.html#propdef-background-color', 'background-color')}}{{Spec2('CSS2.1')}}無變動
{{SpecName('CSS1', '#background-color', 'background-color')}}{{Spec2('CSS1')}}原始定義。
+ +

{{cssinfo}}

+ +

Browser compatibility

+ + + + + +

{{Compat("css.properties.background-color")}}

+

延伸閱讀

+ + diff --git a/files/zh-tw/web/css/border-image/border-image/index.html b/files/zh-tw/web/css/border-image/border-image/index.html new file mode 100644 index 0000000000..210a2663eb --- /dev/null +++ b/files/zh-tw/web/css/border-image/border-image/index.html @@ -0,0 +1,111 @@ +--- +title: border-image +slug: Web/CSS/border-image/border-image +tags: + - CSS +--- +

摘要

+ +

CSS 屬性 border-image 可以讓你在元素的邊框上擺上圖片。這讓呈現看似很複雜的一個網頁的小單元簡單很多,它可以省最多九個元素。

+ +
緊告:官方的 CSS3 規範描述的 border-image 屬性在這個功能被凍結並出現在 Gecko 1.9.1 的釋出版之後改變很多。因此,這項功能的語法跟呈現方法很可能在未來 Gecko 的釋出版改變。特別是選擇性的 border-width 參數,它覆蓋既有 border-width 取值的這項特性已經從規範移除了,因此勢必也會在未來的 Gecko 被拿掉。
+ +

瀏覽器會顯示 border-image 指定的圖片而不是 {{ cssxref("border-style") }} 給的邊框樣式,但是若它的取值是 none 或是因某些理由無法顯示該圖片,瀏覽器就會顯示邊框樣式。border-image 會畫一個額外的背景圖片在原來 {{ cssxref("background-image") }} 指 定的背景圖片之上。

+ + + +

語法

+ +
none |
+  [ <圖片> [ <數字> | <百分比> ]{1,4} [/ <邊框寬度>{1,4}]? ] && [ stretch | repeat | round ]{0,2} 
+ +

取值

+ +
+
none
+
不顯示圖片,使用邊框樣式。
+
<圖片> (必填)
+
圖片值是一個 {{cssxref("<uri>")}},例: url(http://example.org/image.png)
+
<數> | <百分比> (必填)
+
一個、兩個、三個、四個分別代表從頂邊、右邊、底邊、左邊從圖片外圍到切圖線的距離,將圖片切為九塊:四個角、四個邊跟一個中間部份。
+
+ 一個值的話,該值用於圖片的全部四個邊。
+ 兩個值得話,值用於:一、頂邊與底邊 二、右邊與左邊。
+ 三個值的話,值用於:一、頂邊 二、右邊與左邊 三、底邊。
+ 四個值的情況,四個值分邊用在圖片的頂邊、右邊、底邊、左邊。
+
+ 在 Gecko 1.9.1 (Firefox 3.5) 圖片的中間那個部份會被當做元素的背景。這在未來的版本可能會改變。
+
+ 百分比 由圖片的長度/寬度計算。
+ 但表圖片的像素(若為點陣圖)或向量座標(若為 SVG)。
+
<邊框寬度> (選擇性)
+
如果斜線 / 出現在屬性值的話,一個、兩個、三個或是四個在它之後的取值會被當成是 {{ cssxref("border-width") }} 的取值使用。取值的順序如同 {{ cssxref("border-width") }} 。
+
stretch | round | repeat (選擇性)
+
一個或兩個關鍵字,指定邊上的圖片跟中間部份要如何縮放及鋪擺。
+ stretch (預設值)縮放該圖片,使其與配置大小相等。
+ round 鋪擺該圖片,但也縮放它使得被配置範圍鋪滿整數張該圖片。
+ repeat   直接鋪擺該圖片。
+ 第一個關鍵字的對象是頂邊,中間跟底邊的圖片,而第二個關鍵字的對象是左邊跟右邊的邊框。如果第二個不存在,則沿用第一個關鍵字的設定。如果兩者皆不存在,預設值為 stretch
+
+ +

範例

+ +

[這裡還需要一些活範例]

+ +
#header  { -moz-border-image: url(border.png) 27 27 27 27 round round; }
+
+.button  { -moz-border-image: url(button.png) 0 5 0 5; }
+
+.example { -moz-border-image: url(example.jpg) 3 4 6 8 / 10px 12px 14px 22px; }
+
+ +
/* 鮮見例,在 Firefox 3.5 下看起來像是完全伸展的 background-image */
+
+ div     { -moz-border-image: url(bgimage.png) 0; }
+
+ +

瀏覽器兼容性

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
瀏覽器最小版本支援
Internet Explorer------
Firefox (Gecko)3.5 (1.9.1)-moz-border-image
Opera10.5border-image
Safari (WebKit)3.0 (522)-webkit-border-image
+ +

規範

+ + + +

{{ languages( { "en": "en/CSS/-moz-border-image"} ) }}

diff --git a/files/zh-tw/web/css/border-image/index.html b/files/zh-tw/web/css/border-image/index.html new file mode 100644 index 0000000000..bd553c7d6e --- /dev/null +++ b/files/zh-tw/web/css/border-image/index.html @@ -0,0 +1,9 @@ +--- +title: border-image +slug: Web/CSS/border-image +--- +

 

+ +

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

+ +

 

diff --git a/files/zh-tw/web/css/border/index.html b/files/zh-tw/web/css/border/index.html new file mode 100644 index 0000000000..b7a8d098e3 --- /dev/null +++ b/files/zh-tw/web/css/border/index.html @@ -0,0 +1,134 @@ +--- +title: border +slug: Web/CSS/border +tags: + - CSS + - CSS Borders + - CSS Property + - Layout + - Reference +translation_of: Web/CSS/border +--- +
{{CSSRef("CSS Borders")}}
+ +

border shorthand CSS 屬性可用來設定元素的邊框。它可以設定以下的值 {{Cssxref("border-width")}}、{{Cssxref("border-style")}} 以及 {{Cssxref("border-color")}}。

+ +
{{EmbedInteractiveExample("pages/css/border.html")}}
+ + + +

As with all shorthand properties, any omitted sub-values will be set to their initial value. Importantly, border cannot be used to specify a custom value for {{cssxref("border-image")}}, but instead sets it to its initial value, i.e., none.

+ +

The border shorthand is especially useful when you want all four borders to be the same. To make them different from each other, however, you can use the longhand {{Cssxref("border-width")}}, {{Cssxref("border-style")}}, and {{Cssxref("border-color")}} properties, which accept different values for each side. Alternatively, you can target one border at a time with the physical (e.g., {{Cssxref("border-top")}} ) and logical (e.g., {{Cssxref("border-block-start")}}) border properties.

+ +

Borders vs. outlines

+ +

Borders and outlines are very similar. However, outlines differ from borders in the following ways:

+ + + +

Syntax

+ +
/* style */
+border: solid;
+
+/* width | style */
+border: 2px dotted;
+
+/* style | color */
+border: outset #f33;
+
+/* width | style | color */
+border: medium dashed green;
+
+/* Global values */
+border: inherit;
+border: initial;
+border: unset;
+
+ +

The border property may be specified using one, two, or three of the values listed below. The order of the values does not matter.

+ +
+

Note: The border will be invisible if its style is not defined. This is because the style defaults to none.

+
+ +

Values

+ +
+
<line-width>
+
Sets the thickness of the border. Defaults to medium if absent. See {{Cssxref("border-width")}}.
+
<line-style>
+
Sets the style of the border. Defaults to none if absent. See {{Cssxref("border-style")}}.
+
{{cssxref("<color>")}}
+
Sets the color of the border. Defaults to currentcolor if absent. See {{Cssxref("border-color")}}.
+
+ +

Formal syntax

+ +
{{csssyntax}}
+ +

Example

+ +

HTML

+ +
<div>I have a border, an outline, AND a box shadow! Amazing, isn't it?</div>
+
+ +

CSS

+ +
div {
+  border: 0.5rem outset pink;
+  outline: 0.5rem solid khaki;
+  box-shadow: 0 0 0 2rem skyblue;
+  border-radius: 12px;
+  font: bold 1rem sans-serif;
+  margin: 2rem;
+  padding: 1rem;
+  outline-offset: 0.5rem;
+}
+ +

Result

+ +

{{EmbedLiveSample('Example')}}

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Backgrounds', '#the-border-shorthands', 'border')}}{{Spec2('CSS3 Backgrounds')}}Removes specific support for transparent, as it is now a valid {{cssxref("<color>")}}; this has no practical impact.
+ Though it cannot be set to a custom value using the shorthand, border now resets {{cssxref("border-image")}} to its initial value (none).
{{SpecName('CSS2.1', 'box.html#border-shorthand-properties', 'border')}}{{Spec2('CSS2.1')}}Accepts the inherit keyword. Also accepts transparent as a valid color.
{{SpecName('CSS1', '#border', 'border')}}{{Spec2('CSS1')}}Initial definition.
+ +

{{cssinfo}}

+ +

Browser compatibility

+ + + +

{{Compat("css.properties.border")}}

diff --git a/files/zh-tw/web/css/box-shadow/index.html b/files/zh-tw/web/css/box-shadow/index.html new file mode 100644 index 0000000000..4d23dc2d13 --- /dev/null +++ b/files/zh-tw/web/css/box-shadow/index.html @@ -0,0 +1,228 @@ +--- +title: box-shadow +slug: Web/CSS/box-shadow +tags: + - CSS + - CSS Backgrounds and Borders + - CSS Property + - CSS Styles + - HTML Colors + - Reference + - Shadows + - Styles + - Styling HTML + - box-shadow +translation_of: Web/CSS/box-shadow +--- +

{{CSSRef}}

+ +

box-shadow 屬性為一個逗號分隔的列表描述一個或多個的陰影效果. 這使的你能夠從幾乎任何元素的框架放入陰影. 如果一個標記了 {{cssxref("border-radius")}} 的元素也標記了 box shadow, 這將使得他們有相同的圓邊. 多重 box shadows 的 z-index 排序跟多重 text shadows 一樣(第一個備標記的陰影在最上面).

+ +

{{cssinfo}}

+ +

Box-shadow 產生器

+ +

Interactive tool 可以產生 box-shadow.

+ +

表達式

+ +
/* 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;
+
+ +

參數

+ +
+

+ inset
+ 如果未指定(默認),則假定陰影為陰影(就好像該框被提升到內容之上)。 inset關鍵字的存在將陰影更改為幀內的陰影(就好像內容在框內被壓下)。在邊框內部(甚至是透明的)繪製插入陰影,在背景上方,但在內容下方。
+
+ <offset-x> <offset-y>
+ 這兩個 {{cssxref("<length>")}} 值用於設置陰影偏移量。 <offset-x>指定水平距離。負值將陰影置於元素的左側。 <offset-y>指定垂直距離。負值將陰影置於元素上方。有關可能的單位,請參見 {{cssxref("<length>")}}。 如果兩個值均為0,則陰影位於元素後面(如果設置了<blur-radius>和/或<spread-radius>,則可能會生成模糊效果)。
+
+ <blur-radius>
+ 這是第三個 {{cssxref("<length>")}} 值。此值越大,模糊越大,陰影變得越來越大。不允許使用負值。如果未指定,則為0(陰影邊緣清晰)。
+
+ <spread-radius>
+ 這是第四個 {{cssxref("<length>")}} 值。正值將導致陰影擴大並變大,負值將導致陰影縮小。如果未指定,則為0(陰影將與元素的大小相同)。
+
+ <color>
+ 有關可能的關鍵字和符號,請參閱 {{cssxref("<color>")}} 值。 如果未指定,則使用的顏色取決於瀏覽器 - 它通常是 {{cssxref("color")}} 屬性的值,但請注意,Safari在此情況下當前繪製透明陰影。
+
+ +

語法

+ +
{{csssyntax}}
+ +

範例

+ + + +
box-shadow: rgba(0, 0, 0, 0.35) 0px 5px 15px;
+
+ +
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;
+ +

規範

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Backgrounds', '#box-shadow', 'box-shadow')}}{{Spec2('CSS3 Backgrounds')}}Initial definition
+ +

瀏覽相容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support10.0[1]
+ 1.0{{property_prefix("-webkit")}}
{{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")}}
{{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")}}
{{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")}}
{{CompatGeckoDesktop("2.0")}}
+ {{CompatGeckoDesktop("1.9.1")}}{{property_prefix("-moz")}}
9.010.55.1
+ 5.0 {{property_prefix("-webkit")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureSafari MobileOpera MiniOpera MobileAndroid
Basic support +

5.0[1]
+ {{CompatVersionUnknown }}{{ property_prefix("-webkit")}}

+
{{CompatUnknown}}{{CompatVersionUnknown }}[1]{{CompatVersionUnknown }}{{property_prefix("-webkit")}}[1]
Multiple shadows5.0
+ {{CompatVersionUnknown }}{{ property_prefix("-webkit")}}
{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
inset keyword5.0
+ {{CompatVersionUnknown }}{{ property_prefix("-webkit")}}
{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
Spread radius5.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.

diff --git a/files/zh-tw/web/css/box-sizing/index.html b/files/zh-tw/web/css/box-sizing/index.html new file mode 100644 index 0000000000..058f179918 --- /dev/null +++ b/files/zh-tw/web/css/box-sizing/index.html @@ -0,0 +1,94 @@ +--- +title: box-sizing +slug: Web/CSS/box-sizing +tags: + - CSS + - CSS Box Model + - CSS Property + - Experimental + - Reference + - border-box + - box model + - content-box +translation_of: Web/CSS/box-sizing +--- +
{{CSSRef}}{{SeeCompatTable}}
+ +

概要

+ +

The box-sizing property is used to alter the default CSS box model used to calculate width and height of the elements. It is possible to use this property to emulate the behavior of browsers that do not correctly support the CSS box model specification.

+ +

box-sizing  屬性 用於更改預設 CSS 盒子模型 中所計算的寬度和高度。可以使用此屬性來模擬不正確支持CSS盒子模型規範的瀏覽器的行為。

+ +

{{cssinfo}}

+ +

句法

+ +
/* Keyword values */
+box-sizing: content-box;
+box-sizing: border-box;
+
+/* Global values */
+box-sizing: inherit;
+box-sizing: initial;
+box-sizing: unset;
+
+ +

+ +
+
content-box
+
這是根據 CSS 標準的起始值和預設值。 {{Cssxref("width")}}  與  {{Cssxref("height")}} 只包括內容本身的寬和高, 不包括邊框(border)、內邊距(padding)、外邊距(margin)。注意:內邊距、邊框和外邊距都在這個盒子的外部。例如,如果 .box {width: 350px}; 而且 {border: 10px solid black;} ,那麼在瀏覽器中的渲染該容器的實際寬度將是370px,;
+
+ 簡單來說,尺寸計算公式:width = 內容的寬度,height = 內容的高度。寬度和高度都不包含內容的邊框(border)和內邊距(padding)。
+
border-box
+
 {{Cssxref("width")}} 和 {{Cssxref("height")}} 屬性包括內容(content),內邊距(padding)和邊框(border),但不包括外邊距(margin)。這是當文檔處於 Quirks 模式時 Internet Explorer 所使用的盒模型。注意,內邊距和邊框都將在盒子內 ,例如,.box {width: 350px; border: 10px solid black;} ,渲染出的容器寬度會固定在 350px,而內容(content)的寬度就會變成 330px, 因為邊框(border)佔了20px。內容框不能為負,並且進位到 0,使得不可能使用 border-box 使元素消失。
+
+ 這裡的維度計算為:
+
width = border + padding + 內容的  width
+
height = border + padding + 內容的 height
+
padding-box {{non-standard_inline}} {{deprecated_inline}}
+
The {{Cssxref("width")}} and {{Cssxref("height")}} properties include the content, the padding but neither the border, nor the margin. Only Firefox implemented this value, and it was removed in Firefox 50.
+
+ +

Formal syntax

+ +
{{csssyntax}}
+ +

Examples

+ +
/* support Firefox, Chrome, Safari, Opera, IE8+ and old Android */
+
+.example {
+  -moz-box-sizing: border-box;
+  box-sizing: border-box;
+}
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Basic UI', '#box-sizing', 'box-sizing')}}{{Spec2('CSS3 Basic UI')}}Initial definition
+ +

Browser compatibility

+ +

{{Compat("css.properties.box-sizing")}}

+ +

See also

+ + diff --git a/files/zh-tw/web/css/clip/index.html b/files/zh-tw/web/css/clip/index.html new file mode 100644 index 0000000000..900be65c41 --- /dev/null +++ b/files/zh-tw/web/css/clip/index.html @@ -0,0 +1,174 @@ +--- +title: clip +slug: Web/CSS/clip +translation_of: Web/CSS/clip +--- +
{{CSSRef}}{{deprecated_header}}
+ +

總結

+ +

這個 clip CSS 屬性用來定義元素的哪一個部分是可見的. clip 屬性只能被賦予在絕對位置的元素(element)上, 像是帶有這些的CSS屬性的元素 {{cssxref("position","position:absolute")}} or {{cssxref("position","position:fixed")}}.

+ +
+

警告: 這個屬性被遺棄了. 請改用 {{cssxref("clip-path")}} .

+
+ +

{{cssinfo}}

+ +

Syntax

+ +
/* Keyword value */
+clip: auto;
+
+/* <shape> values */
+clip: rect(1px 10em 3rem 2ch);
+clip: rect(1px, 10em, 3rem, 2ch);
+
+/* Global values */
+clip: inherit;
+clip: initial;
+clip: unset;
+
+ +

Values

+ +
+
<shape>
+
A rectangular {{cssxref("<shape>")}} of the form rect(<top>, <right>, <bottom>, <left>) or of the form rect(<top> <right> <bottom> <left>) (which is a more backwards compatible syntax) <top> and <bottom> specify offsets from the inside top border edge of the box, and <right>, and <left> specify offsets from the inside left border edge of the box — that is, the extent of the padding box.
+
<top>, <right>, <bottom>, and <left> may either have a {{cssxref("<length>")}} value or auto. If any side's value is auto, the element is clipped to that side's inside border edge.
+
auto
+
The element does not clip (default value). Note that this is distinct from rect(auto, auto, auto, auto), which does clip to the inside border edges of the element.
+
+ +

Formal syntax

+ +
{{csssyntax}}
+
+ +

Examples

+ +
.dotted-border {
+   border: dotted;
+   position: relative;
+   width: 536px;
+   height: 350px;
+}
+
+#top-left, #middle, #bottom-right {
+   position: absolute;
+   top: 0px;
+}
+
+#top-left {
+   left: 360px;
+   clip: rect(0px, 175px, 113px, 0px);
+}
+
+
+#middle {
+   left: 280px;
+   clip: rect(119px, 255px, 229px, 80px);
+   /* standard syntax, unsupported by Internet Explorer 4-7 */
+}
+
+#bottom-right {
+   left: 200px;
+   clip: rect(235px 335px 345px 160px);
+   /* non-standard syntax, but supported by all major browsers*/
+}
+ +
<p class="dotted-border">
+   <img src="https://developer.mozilla.org/@api/deki/files/3613/=hut.jpg" title="Original Graphic" />
+   <img id="top-left" src="https://developer.mozilla.org/@api/deki/files/3613/=hut.jpg" title="Graphic clipped to upper left">
+   <img id="middle" src="https://developer.mozilla.org/@api/deki/files/3613/=hut.jpg" title="Graphic clipped towards middle">
+   <img id="bottom-right" src="https://developer.mozilla.org/@api/deki/files/3613/=hut.jpg" title="Graphic clipped to bottom right">
+</p>
+ +

{{EmbedLiveSample('Examples', '689px', '410px')}}

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS Masks', '#clip-property', 'clip')}}{{Spec2('CSS Masks')}}Deprecates clip property, suggests {{cssxref("clip-path")}} as replacement.
{{SpecName('CSS3 Transitions', '#animatable-css', 'clip')}}{{Spec2('CSS3 Transitions')}}Defines clip as animatable.
{{SpecName('CSS2.1', 'visufx.html#clipping', 'clip')}}{{Spec2('CSS2.1')}}Initial definition
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support1.01.0 (1.0)4.0[1]7.01.0 (85)[1]
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Internet Explorer up to version 7.0 and Safari up to at least 5.1.7 incorrectly interpret clip: auto as clip: rect(auto, auto, auto, auto).

+ +

See also

+ + diff --git a/files/zh-tw/web/css/common_css_questions/index.html b/files/zh-tw/web/css/common_css_questions/index.html new file mode 100644 index 0000000000..b824c671c4 --- /dev/null +++ b/files/zh-tw/web/css/common_css_questions/index.html @@ -0,0 +1,165 @@ +--- +title: CSS 一般問題 +slug: Web/CSS/Common_CSS_Questions +tags: + - CSS + - 待審閱技術 + - 待審閱文字 + - 所有類別 +translation_of: Learn/CSS/Howto/CSS_FAQ +--- +

+

+

我的 CSS 合乎規格,但繪出的版面有誤

+

如果想讓大部分的瀏覽器都能正確繪製標準 HTML/CSS 頁面,便須於 HTML 檔案中放上完整的正確 DOCTYPE。 +

新近瀏覽器都有兩種佈局模式: +

+ +

以 Gecko 為核心的瀏覽器都有第三種近乎標準模式,其中只有一些些不合規範的地方。 +

如果你宣告的 DTD 不合標準或過期了,那麼瀏覽器就會進入 Quirks 模式。 +

以下是常用的 DTD 列表,可以讓瀏覽器進入標準或近乎標準模式。 +

+
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"
+"http://www.w3.org/TR/html4/loose.dtd">
+
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
+"http://www.w3.org/TR/html4/strict.dtd">
+
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
+"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
+"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
+
+

idclass 之間的差別

+

HTML 元素都可有 idclass 屬性。id 屬性是讓你為元素命名的,整個頁面中的元素名稱也不應有重複;class 屬性則可將元素歸為某特定類別,通常也會有很多元素屬於同一種類別 (意即 class 屬性值相同。) CSS 可以讓你以 idclass 來決定某元素的樣式。 +

如果你想指定某特定單一元素的樣式,則應使用 id。 +

+
+

若有很多個元素皆有相同樣式,則可使用 class。 +

這方面的資訊亦可參考 CSS 選取符。 +

+
+

恢復某特性的預設值

+

CSS2 並不提供任何指定某特性預設值的方法,所以要恢復某特性預設值的唯一方法就是重新指定此值。此外你自己得知道預設值是什麼,因為 CSS 也沒有所謂 default 的關鍵字。 +

所以,以選取符撰寫樣式時須特別注意 (例如以標籤名稱 p 作為選取符),或許可以用更明確的選取符 (例如 ID 或 class)。以標籤名稱作選取符茲事體大,一旦使用便將影響整個網頁,而且沒有自動恢復預設值的方法。 +

此外,由於 CSS 具串聯特性,指定選取符時通常越明確越好,以免把不相干的元素都牽扯進來。 +

+

相依樣式

+

CSS 並不支援「以另一個樣式規則為基準」的樣式設定法。 (參考 Eric Meyer 所寫、關於 CSS 工作小組的說明。) 不過,你可以為某單一元素套上多重樣式,製作出類似效果。 +

+

套用多重類別

+

你可以在 HTML 元素的 class 屬性裡以空白字元分隔填上多個樣式類別名稱,便能同時套用多重類別。 +

+
<style type="text/css">
+.firstclass { background: black; color: white; }
+.secondclass { font-weight: bold; }
+</style>
+
+<div class="firstclass secondclass">
+... content ...
+... content ...
+... content ...
+</div>
+
+

若是這些規則中設定了同一種特性值,則會依序以明確性(specificity)、定義位置先後決定顯示方式,與class 屬性中的次序無關。 +

+

無用樣式

+

即使樣式規則已經正確設定完畢,還是可能為瀏覽器所忽略,此時通常是經過語法及優先權法則判斷後的正常現象。 +

以下是導致樣式被略過的常見情形: +

+ +

你可以使用 DOM 觀察器CSS Style Rules 來檢查上述問題。 +

HTML 元素層次問題 +

此時 CSS 樣式套用與否與元素的層次大有相關,請留意:套用到子元素的樣式必定會蓋過母元素的樣式,跟明確性或 CSS 規則的優先權無關。 +

+
#section { font-weight: bold; }
+.redtext { font-weight: normal; color: red; }
+
+<div id="section">
+   粗體、
+   <span class="redtext">正常紅字、</span>
+   又見粗體
+</div>
+
+

如果你的 HTML 層級錯綜複雜,發生規則意外被忽略的情形時,請檢查元素層級問題。可能有某個子元素套上了不該用的樣式。 +

樣式規則重新定義 +

在 CSS 樣式表中,先後次序非常重要。如果你定義了某規則後又重新定義一次,則晚定義的才算數。 +

+
#section { font-weight: bold; }
+.redtext { color: red; }
+/* 其他規則 */
+/* 其他規則 */
+/* 其他規則 */
+.redtext { color: green; }
+
+<div id="section">
+粗體、
+<span class="redtext">正常紅字?</span>
+又見粗體
+</div>
+
+

為避免此類錯誤發生,每個特定選取符請僅定義一次樣式,集中特性一次定義也便於管理些。 +


+特性的簡寫法 +

使用簡寫法來定義樣式簡明扼要,是個不錯的方法。你也可以用簡寫法設定某組特性中的部分特性值,但須留意其他沒寫到的部分會自動採用預設值。這表示之前的規則中為某單一特性定義的值可能失效。 +

+
#section { font-size: 12px; font-family: Verdana; font-weight: bold; }
+.redtext { font: 14px Arial; color: red; }
+
+<div id="section">
+   採用 Verdana 粗體的 12px 字樣;
+   <span class="redtext">採用 Arial 正常字體的 14px 紅字;</span>
+   還是採用 Verdana 粗體的 12px 字樣。
+</div>
+
+

前一個例子中,套用到不同元素範圍的同族特性是問題所在,但就算特性都寫在同一條規則裡也可能出問題,因為順序真的很重要。 +

+
#section {
+   font-weight: bold;
+   font: 12px Verdana;  /* 有了這行,font-weight 又回到預設的 normal 了 */
+}
+
+


+使用 * 選取符 +

* 選取符表示任何元素皆符合,但使用上應多加小心。 +

+
body * { font-weight: normal; }
+#section { font: 12px Verdana; }
+.boldtext { font-weight: bold; }
+.redtext { color: red; }
+
+<div id="section">
+   正常、
+   <span class="boldtext">
+      <span class="redtext">正常紅字、</span>
+   </span>
+   又見正常。
+</div>
+
+

在此例中,選取符為 body * 的規則會套用到所有 body 內的元素,也包括 redtext,所以原先套用到 boldtextfont-weight: bold; 就被覆蓋為 font-weight: normal; 了。 +


+CSS 明確性 +

如果某元素會套用好幾條規則,則相衝突的特性就要靠規則的明確性來分高下。行內樣式(放在 HTML 各標籤的 style 屬性中)優先權最高,其次是以 id 做選取符的規則,再其次是以 class 套用的類別,最後則是單純以元素名稱當選取符的規則。 +

+
div { color: black; }
+#orange { color: orange; }
+.green { color: green; }
+
+<div id="orange" class="green" style="color: red;">是紅的!</div>
+
+

如果樣式規則的選取符分成好幾段,計算方式就更為複雜一些。需要瞭解完整資訊者,請參考 CSS 2.1 規格書的 6.4.3 一節。 +

+

-moz-* 特性是什麼玩意?

+

請見 Mozilla 擴充的 CSS。由於這些擴充規格不是 W3C 標準的一部分,因此並不建議使用。 +

+
+
+{{ languages( { "en": "en/Common_CSS_Questions", "pl": "pl/Cz\u0119ste_pytania_o_CSS" } ) }} diff --git a/files/zh-tw/web/css/css_animations/index.html b/files/zh-tw/web/css/css_animations/index.html new file mode 100644 index 0000000000..7c953b2359 --- /dev/null +++ b/files/zh-tw/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

+ +
+ +
+ +

CSS At-rules

+ +
+ +
+ +

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

+ + + +

 

diff --git a/files/zh-tw/web/css/css_animations/using_css_animations/index.html b/files/zh-tw/web/css/css_animations/using_css_animations/index.html new file mode 100644 index 0000000000..82acb8ac6e --- /dev/null +++ b/files/zh-tw/web/css/css_animations/using_css_animations/index.html @@ -0,0 +1,334 @@ +--- +title: CSS 動畫 +slug: Web/CSS/CSS_Animations/Using_CSS_animations +tags: + - Advanced + - CSS animation + - CSS 動畫 + - Example + - Experimental + - Guide +translation_of: Web/CSS/CSS_Animations/Using_CSS_animations +--- +

{{SeeCompatTable}}{{CSSRef}}

+ +
+

 CSS animations 使 CSS style configuration 的轉變變得可行。在這種動畫的運作上,你只需要定義兩個部份:1. 動畫的最初及結尾 2. 動畫轉變的方式。

+ +

  相較於傳統 script-driven 的動畫技術,CSS animations 有三種好處:

+ +
    +
  1. 對於不複雜的動畫來說,CSS animation 是好選擇。你甚至不必懂得  JavaScript。
  2. +
  3. 在資源消耗上,CSS animation 有優勢,即使在系統負載超過 50% 仍可有效運作。在 JavaScript 上要達到一樣的目的有賴於你寫出品質非常好的  code。事實上,CSS animation 在運作上可以適時的減少 frame 量或以其它技術減少資源消耗。
  4. +
  5. CSS animation 讓瀏覽器來負責動畫的產生過程,如此可以擁有較好的優化。
  6. +
+ +

CSS animation 設定

+ +

  你可以使用 {{ cssxref("animation") }} property 或其 sub-properties 來創建 CSS 動畫的細節(諸如轉化時間等)。但這並不能決定動畫的外觀,外觀的部份我們將在下面的 {{ anch("使用關鍵影格定義動畫流程") }} 介紹。

+ +

  這裡是 {{ cssxref("animation") }} property 的 sub-properties:

+ +
+
{{ cssxref("animation-delay") }}
+
定義元素讀取完畢到動畫開始的間隔時間。
+
{{ cssxref("animation-direction") }}
+
定義是否動畫播放完畢後將會反向播放。
+
{{ cssxref("animation-duration") }}
+
定義動畫完成一次週期的時間。
+
{{ cssxref("animation-iteration-count") }}
+
定義動畫重複的次數。你可以用 infinite 來讓動畫永遠重複播放。
+
{{ cssxref("animation-name") }}
+
定義關鍵影格 {{ cssxref("@keyframes") }} 的名字。
+
{{ cssxref("animation-play-state") }}
+
控制動畫的播放狀態。有 pause 和 running 兩種值,後者為預設值。
+
{{ cssxref("animation-timing-function") }}
+
定義動畫轉變時時間的加速曲線 (例如 linear)。
+
{{ cssxref("animation-fill-mode") }}
+
定義元素在動畫播放外(動畫開始前及結束後)的狀態。
+
+ +

使用關鍵影格定義動畫流程

+ +

  在你設定了動畫的時間資訊之後,你必須要設定動畫漸變的過程。這可以藉由建造兩個或更多的關鍵影格來達到目的 (使用 {{ cssxref("@keyframes") }} )。關鍵影格描述了該元素在漸變過程中的外觀。

+ +

  因為動畫漸變時間已經在 CSS style 中被定義(見上節),所以關鍵影格使用 {{ cssxref("percentage") }} 來指出他們會在整個漸變流程中的哪個時間點出現。 0% 代表他是整個動畫的起點,而 100% 指出他是整個動畫的結束點。這兩個特殊時間點一定要被定義,如此一來瀏覽器材知道該如何產生你的動畫。也因為他們是如此重要,所以這兩個時間點有特殊的別名: from 和 to。

+ +

  當然你也可以在動畫轉變過程中增加更多的關鍵影格。

+ +

範例

+ +
注意: 為了簡潔起見,以下的範例中我們只列出前綴為 -moz- 的部份。當你查看 Live Sample 的原始碼時,可以看到前綴為 -webkit- 的部份。
+ +

使文字滑過畫面

+ +

  這是一個簡單的範例,他展示了 {{ HTMLElement("p") }} element 從畫面右方滑向左方。

+ +
<style type="text/css">
+  p {
+    -moz-animation-duration: 3s;
+    -moz-animation-name: slidein;
+  }
+
+  @-moz-keyframes slidein {
+    from {
+      margin-left: 100%;
+      width: 300%
+    }
+
+    to {
+      margin-left: 0%;
+      width: 100%;
+    }
+  }
+</style>
+
+ +

  這裡用 {{ cssxref("animation-duration") }} property 定義 {{ HTMLElement("p") }} element 的變動自開始到結束共花 3 秒。而關鍵影格的名稱由 {{ cssxref("@keyframes") }} 指定 - 叫做 slidein。

+ +

  傳統的 {{ HTMLElement("p") }} element 尚有其他性質可供設定,但假設這些性質並不支援 CSS animation,則我們不能期待他們會被瀏覽器顯示。

+ +

  這裡的關鍵影格我們定義了兩個 (以 {{ cssxref("@keyframes") }} 定義),開始 (0%)和結束 (100%)。開始的影格在 from 中,而結束在 to 中。由程式中我們可以看到,整個動畫由最一開始處於最右方且 width 為 300% 轉變為處於最左方且 width 為 100%。如此一來你就可以看到 {{ HTMLElement("p") }} element 由右而左的滑過畫面。

+ +

  結束影格描述 width 為 100% 可以確保 {{ HTMLElement("p") }} element 在可視範圍內。

+ +
<p>The Caterpillar and Alice looked at each other for some time in silence:
+at last the Caterpillar took the hookah out of its mouth, and addressed
+her in a languid, sleepy voice.</p>
+
+ +

{{EmbedLiveSample("使文字滑過畫面","100%","250")}}

+ +

在開頭和結束間加入關鍵影格

+ +

  現在我們試著多加入新的關鍵影格。在這個範例中,我們希望做到在文字在移動時字體先變大而後恢復正常。程式碼如下:

+ +
75% {
+  font-size: 300%;
+  margin-left: 25%;
+  width: 150%;
+}
+
+ + + + + +

  這段程式碼告訴瀏覽器在開始後過了 75% 的時間後字體增大到三倍,且位置在離左側 25 % 處,此時總寬度為 150%。

+ +

{{EmbedLiveSample("在開頭和結束間加入關鍵影格","100%","250")}}

+ +

重複播放

+ +

  為了達到重複播放的目的,我們使用 {{ cssxref("animation-iteration-count") }} property。讓我們把它設定成 infinite :

+ +
p {
+  -moz-animation-duration: 3s;
+  -moz-animation-name: slidein;
+  -moz-animation-iteration-count: infinite;
+} 
+ + + + + +

{{EmbedLiveSample("重複播放","100%","250")}}

+ +

播放完畢後反向播放

+ +

  由上個例子我們知道該如何永久性播放動畫。但這個顯示結果有些突兀,是以我們試著讓他播放完畢後倒帶執行。這需要用到 {{ cssxref("animation-direction") }},賦予 alternate 的值:

+ +
p {
+  -moz-animation-duration: 3s;
+  -moz-animation-name: slidein;
+  -moz-animation-iteration-count: infinite;
+  -moz-animation-direction: alternate;
+} 
+ + + + + +

{{EmbedLiveSample("播放完畢後反向播放","100%","250")}}

+ +

使用動畫的事件

+ +

  你可以藉由 animation event 來對 CSS animation 做更進階的控制,這需要用到 {{ domxref("event/AnimationEvent", "AnimationEvent") }} 物件。他可以用來偵測動畫所處的時間點等資訊。每個 event 包含發生的時間以及觸發 event 的動畫名字。

+ +

  我們將修改剛剛的範例來展示 animation event 的能力。

+ +
.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%;
+ }
+}
+ +

設定 animation event listeners

+ +

  我們使用 JavaScript 來監控所有可能的 animation events。下面的 setup() 函式設定我們的 event listeners,並且在文件第一次被載入時執行他:

+ +
function setup() {
+  var e = document.getElementById("watchme");
+  e.addEventListener("animationstart", listener, false);
+  e.addEventListener("animationend", listener, false);
+  e.addEventListener("animationiteration", listener, false);
+
+  var e = document.getElementById("watchme");
+  e.className = "slidein";
+}
+
+ +

  這是非常簡單的程式,你可以從其它相關文件中取得 {{ domxref("element.addEventListener()") }} 的更多細節。setup() 函式所做的最後一件事是設定這個 element 的 class name 為 slidein,此時,我們啟動了這個動畫。

+ +

  這麼做的原因是 animationstart event 會在被動畫執行時立刻被觸發,所以我們只好在最後才設定 class name。

+ +

接收 events

+ +

  這些 events 會被發送到 listener() 函式,如下所示:

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

  這段程式檢查藉由檢查 {{ domxref("event.type") }} 得知現在收到了哪種 animation event,並且以一個 {{ HTMLElement("ul") }} (unordered list) 形式的記錄下他。

+ +

  程式執行結果看起來會是這樣子的:

+ + + +

  注意這裡的時間是一個範例,你自己執行可能會取得不一樣的結果(但應該會近似)。此外,在動畫的最後,event 會是 animationend 而非  animationiteration 。

+ +

完整的 HTML 程式碼

+ +

  這裡是完整的 HTML 程式碼:

+ +
<body onload="setup()">
+  <h1 id="watchme">Watch me move</h1>
+  <p>This example shows how to use CSS animations to make <code>h1</code> elements
+  move across the page.</p>
+  <p>In addition, we output some text each time an animation event fires, so you can see them in action.</p>
+  <ul id="output">
+  </ul>
+</body> 
+ +

{{EmbedLiveSample('使用動畫的事件', '600', '300')}}

+ +

更多資訊

+ + +
+ +

 

diff --git a/files/zh-tw/web/css/css_background_and_borders/index.html b/files/zh-tw/web/css/css_background_and_borders/index.html new file mode 100644 index 0000000000..dcfeef033a --- /dev/null +++ b/files/zh-tw/web/css/css_background_and_borders/index.html @@ -0,0 +1,152 @@ +--- +title: CSS Background and Borders +slug: Web/CSS/CSS_Background_and_Borders +tags: + - CSS + - CSS Background and Borders + - CSS Reference + - Overview +translation_of: Web/CSS/CSS_Backgrounds_and_Borders +--- +

{{CSSRef}}

+ +

CSS Background and Borders is a module of CSS that defines how background and borders of elements are described. Borders can be lines or images, boxes can have one or multiple backgrounds, have rounded corners, and shadows.

+ +

Reference

+ +

CSS Properties

+ +
+ +
+ +

Guides

+ +
+
Using CSS multiple backgrounds
+
Explains how to set backgrounds on elements and how they will interact with it.
+
Scaling background images
+
Describes how to change the appearance of the background images, by stretching them or repeating them, to cover the whole background of the element, or not.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSS3 Backgrounds') }}{{ Spec2('CSS3 Backgrounds') }} 
{{SpecName('CSS2.1', 'box.html')}}{{Spec2('CSS2.1')}} 
{{SpecName('CSS1', '#border')}}{{Spec2('CSS1')}} 
+ +

Browser compatibility

+ +

{{CompatibilityTable()}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1.0{{CompatGeckoDesktop("1.0")}}4.03.51.0 (85)
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown()}}{{CompatGeckoMobile("1.9.2")}}{{CompatVersionUnknown()}}{{CompatVersionUnknown()}}1.0
+
diff --git a/files/zh-tw/web/css/css_background_and_borders/using_css_multiple_backgrounds/index.html b/files/zh-tw/web/css/css_background_and_borders/using_css_multiple_backgrounds/index.html new file mode 100644 index 0000000000..244234b839 --- /dev/null +++ b/files/zh-tw/web/css/css_background_and_borders/using_css_multiple_backgrounds/index.html @@ -0,0 +1,84 @@ +--- +title: 使用 CSS 多重背景 +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}}

+ +

藉由 CSS3 我們可以對元素使用 多重背景。每個設定的背景被一個個分層,第一個背景在最上面,最後一個背景是在最下面一層。 記得只有最後一個背景可以設定 background color。

+ +

簡易的表達方式:

+ +
.myclass {
+  background:
+      background 1, //第一層
+      background 2,
+      ...,
+      background N;  //最後一層
+}
+
+ +

可以使用縮寫的方式 {{ cssxref("background") }} 和個別標記的方式設定多重背景,但是部分屬性無法設置多重背景,例如 {{ cssxref("background-color") }}。下面是能設置為多重背景的背景屬性: 

+ + + +

範例

+ +

下面的範例中,重疊三個背景:Firefox logo、線性漸層、一張泡泡的圖片

+ +
.multi_bg_example {
+  background-image   : url(https://mdn.mozillademos.org/files/11305/firefox.png),
+                       url(https://mdn.mozillademos.org/files/11307/bubbles.png),
+                       linear-gradient(to right, rgba(30, 75, 115, 1),  rgba(255, 255, 255, 0));
+
+  background-repeat  : no-repeat,
+                       no-repeat,
+                       no-repeat;
+
+  background-position: bottom right,
+                       left,
+                       right;
+}
+
+ + + +

結果

+ +

{{EmbedLiveSample('範例','100%','400')}}

+ +

如你所見,Firefox logo(列表第一個選項)在最上面,接著是漸層。每個隨後的子屬性({{ cssxref("background-repeat") }} 和 {{ cssxref("background-position") }})應用相對的背景上。所以第一個 {{ cssxref("background-repeat") }} 的值應用在第一個(最前面)背景。

+ +

參見

+ + diff --git a/files/zh-tw/web/css/css_box_model/index.html b/files/zh-tw/web/css/css_box_model/index.html new file mode 100644 index 0000000000..cb4dd91343 --- /dev/null +++ b/files/zh-tw/web/css/css_box_model/index.html @@ -0,0 +1,167 @@ +--- +title: CSS Box Model +slug: Web/CSS/CSS_Box_Model +tags: + - CSS + - CSS Box Model + - CSS Reference + - NeedsTranslation + - Overview + - TopicStub +translation_of: Web/CSS/CSS_Box_Model +--- +
{{CSSRef}}
+ +

CSS Box Model is a CSS module that defines the rectangular boxes, including their padding and margin, that are generated for elements and laid out according to the visual formatting model.

+ +

Reference

+ +

Properties

+ +

Properties controlling the flow of content in a box

+ +
+ +
+ +

Properties controlling the size of a box

+ +
+ +
+ +

Properties controlling the margins of a box

+ +
+ +
+ +

Properties controlling the paddings of a box

+ +
+ +
+ +

Other properties

+ +
+ +
+ +

Guides and tools

+ +
+
Introduction to the CSS box model
+
Explains one of the fundamental concept of CSS, the box model: describes the meaning of the margin, padding, as well as the different areas of a box.
+
Mastering margin collapsing
+
In several cases, two adjacent margins are collapsed into one. This article describes when this is happening and how to control it.
+
Box-shadow generator
+
An interactive tool that allows to visually create shadows and to generate the needed syntax for the {{cssxref("box-shadow")}} property.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("CSS3 Box")}}{{Spec2("CSS3 Box")}} 
{{SpecName("CSS2.1", "box.html")}}{{Spec2("CSS2.1")}} 
{{SpecName("CSS1")}}{{Spec2("CSS1")}}Initial definition
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support1.0{{CompatGeckoDesktop("1")}}3.03.51.0 (85)
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support1.0{{CompatGeckoMobile("1")}}6.06.01.0
+
diff --git a/files/zh-tw/web/css/css_box_model/mastering_margin_collapsing/index.html b/files/zh-tw/web/css/css_box_model/mastering_margin_collapsing/index.html new file mode 100644 index 0000000000..be8ea00259 --- /dev/null +++ b/files/zh-tw/web/css/css_box_model/mastering_margin_collapsing/index.html @@ -0,0 +1,107 @@ +--- +title: 理解邊界重疊的原因 +slug: Web/CSS/CSS_Box_Model/Mastering_margin_collapsing +translation_of: Web/CSS/CSS_Box_Model/Mastering_margin_collapsing +--- +
{{CSSRef}}
+ +
當一個 Block 的 下邊界範圍 ( margin-bottom ) 和一個 Block 的 上邊界範圍 ( margin-top ) 都有設定時只會留下最大那個,這種情況我們稱為邊界重疊 ( margin collapsing )。請留意設定了 float 或絕對定位的元件並不會產生邊界重疊。
+ + + +

有三個標準情況會形成邊界重疊:

+ +
+
同一層的相鄰
+
兩個相鄰的元素邊界就會發生重疊,除非後者有加上clear-fix。例如: +
<style>
+  p:nth-child(1){
+    margin-bottom: 13px;
+  }
+  p:nth-child(2){
+    margin-top: 87px;
+  }
+</style>
+
+ <p>下邊界範圍會...</p>
+ <p>...跟這個元素的上邊界範圍重疊。</p>
+
+
+
如果邊界會合併的的話,理所當然會認為上例中的上下兩個元素會合成一個 100px 的邊界範圍。
+ 但其實會發生重疊,而且只會留下最大的邊界範圍,以此例子來說,邊界範圍就是 87px。
+
+
父元素與第一個/最後一個子元素
+
如果第一個子元素跟父元素的上邊界範圍 ( margin-top ) 貼在一起,也會發生邊界重疊的情況。除非父元素有設定邊框 ( border ) 、 內距 ( padding )、內容設定為 inline 或是有加上 clear-fix,這些都會隔開子元素和父元素的屬性。
+ 最後一個子元素也是,但是與父元素的下邊界範圍 ( margin-bottom ) 更容易被隔開,因為父元素可以設定這些屬性。例如:
+
+
<style type="text/css">
+    section    {
+        margin-top: 13px;
+        margin-bottom: 87px;
+    }
+
+    header {
+        margin-top: 87px;
+    }
+
+    footer {
+        margin-bottom: 13px;
+    }
+</style>
+
+<section>
+    <header>上邊界重疊是 87</header>
+    <footer>下邊界重疊還是 87 不能再高了</footer>
+</section>
+
+
空的元素
+
當同一個元素上邊界範圍可以直接貼到下邊界範圍時,也會發生邊界重疊。這種情況會發生在一個元素完全沒有設定邊框 ( border ) 、 內距 ( padding )、高度 ( height )​ 、最小高度 ( min-height ) 、最大高度 ( max-height )​ 、內容設定為 inline 或是加上 clear-fix 的時候。例如:
+
+
<style>
+  p {
+    margin: 0px;
+  }
+  div {
+    margin-top: 13px;
+    margin-bottom: 87px;
+  }
+</style>
+
+<p>下邊界範圍是 87</p>
+<div></div>
+<p>...上邊界範圍也是 87。</p>
+
+
+
+ +

上面這些情況是會同時發生的,那時邊界重疊的原因又更複雜了。

+ +

比較特別的是,當計算的時候某些邊界範圍是負數,邊界重疊的結果會取最大值和最小值相加。舉例來說如果 -13px、8px 和 100px 疊在一起,邊界範圍的計算方法會是 100px - 13px 也就是 87px。

+ +

以上這些內容都是發生在 Block-Level 的元素,設定 floating 和 absolutely positioned 的元素完全不用擔心邊界重疊的計算。

+ +

標準文件

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("CSS2.1", "box.html#collapsing-margins", "margin collapsing")}}{{Spec2("CSS2.1")}}Initial definition
+ +

參考

+ + diff --git a/files/zh-tw/web/css/css_colors/color_picker_tool/index.html b/files/zh-tw/web/css/css_colors/color_picker_tool/index.html new file mode 100644 index 0000000000..367e58ce23 --- /dev/null +++ b/files/zh-tw/web/css/css_colors/color_picker_tool/index.html @@ -0,0 +1,3221 @@ +--- +title: 色彩選擇工具 +slug: Web/CSS/CSS_Colors/Color_picker_tool +tags: + - CSS + - Tools +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}}

+ +

這是個可以讓人新增、調整和測試網頁顏色的工具。藉由這個工具讓人可以輕鬆將顏色轉換成各種 CSS 支援的格式,包含:HEXA、RGB(Red/Green/Blue)和 HSL (Hue/Staturation/Lightness)。在 RGB(rgba)和 HSL(hsla)格式也支援控制阿爾法通道(alpha channel)

+ +

隨著調整每個顏色都會顯示成三種 CSS 的標準格式;此外,基於目前選擇的顏色,一個調色板 HSL 和 HSV、還有 alpha, 被創建。滴管風格的色彩選擇器對話框可以在 HSL 或 HSV 格式中切換。

+ +

{{ EmbedLiveSample('ColorPicker_Tool', '100%', '900') }}

+ +

 

diff --git a/files/zh-tw/web/css/css_colors/index.html b/files/zh-tw/web/css/css_colors/index.html new file mode 100644 index 0000000000..607d1790af --- /dev/null +++ b/files/zh-tw/web/css/css_colors/index.html @@ -0,0 +1,119 @@ +--- +title: CSS Colors +slug: Web/CSS/CSS_Colors +tags: + - CSS + - CSS Colors + - NeedsTranslation + - Overview + - Reference + - TopicStub +translation_of: Web/CSS/CSS_Color +--- +

{{CSSRef}}

+ +

CSS Colors is a module of CSS that deals with colors, color types and transparency.

+ +

Reference

+ +

Properties

+ +
+ +
+ +

CSS Data Types

+ +

{{cssxref("<color>")}}

+ +

Guides

+ +

None.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Colors')}}{{Spec2('CSS3 Colors')}} 
{{SpecName('CSS2.1', 'colors.html')}}{{Spec2('CSS2.1')}} 
{{SpecName('CSS1')}}{{Spec2('CSS1')}} 
+ +

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

See also

+ + diff --git a/files/zh-tw/web/css/css_flexible_box_layout/index.html b/files/zh-tw/web/css/css_flexible_box_layout/index.html new file mode 100644 index 0000000000..f26fcfb2e8 --- /dev/null +++ b/files/zh-tw/web/css/css_flexible_box_layout/index.html @@ -0,0 +1,118 @@ +--- +title: CSS 彈性盒子排版 +slug: Web/CSS/CSS_Flexible_Box_Layout +tags: + - CSS + - CSS Flexible Boxes + - CSS Reference + - NeedsTranslation + - Overview + - TopicStub +translation_of: Web/CSS/CSS_Flexible_Box_Layout +--- +
{{CSSRef}}
+ +

CSS 彈性盒子排版(CSS Flexible Box Layout)是 CSS 的模組。它為了最佳化 CSS 盒子模型的使用者介面設計而來、並把項目都配置在一個維度之內。在彈性盒子排版中,彈性容器的子項目們可以伸展到任何方向、並讓他們的尺寸更加「彈性」、或者持續增大,以填補未使用的空間,抑或縮小,以避免父元素溢出。子項目橫向或縱向對齊都很容易操作。

+ +

基本範例

+ +

下例的容器已經設為 display: flex、意味著三個子元素變成了彈性項目(flex item)。justify-content 值也設成了 space-between 以便將項目均勻地分佈在主軸上。每個物品之間放置相等數量的空間,左右項目與彈性容器(flex container)的邊緣齊平。你可能也發現到各項目在切軸(cross axis)上伸展。那是因為 align-items 的值是 stretch。項目伸展為彈性容器的高度、令它們看起来都如同最高的項目一般高。

+ +

{{EmbedGHLiveSample("css-examples/flexbox/basics/simple-example.html", '100%', 500)}}

+ +

參考

+ +

CSS 屬性

+ +
+ +
+ +

對齊屬性

+ +

The properties align-content, align-self, align-items and justify-content initially appeared in the Flexbox specification, but are now defined in Box Alignment and the Flexbox spec refers to the Box Alignment Specification for up to date definitions. Additional alignment properties are also defined in Box Alignment.

+ +
+ +
+ +

短詞

+ +
+ +
+ +

教學

+ +
+
彈性盒子的基本概念
+
彈性盒子的概述
+
彈性盒子與其他排版的關係
+
彈性盒子如何與其他排版和 CSS 規範相關連
+
在彈性容器內對齊
+
彈性盒子的 Box Alignment 屬性如何做動。
+
給彈性項目排序
+
解釋改變彈性項目順序和方向的不同方法,並講到潛在的問題。
+
控制彈性項目與主軸的比例
+
將解釋 flex-grow、flex-shrink、flex-basis 屬性。
+
掌握彈性項目 wrapping
+
如何使用多行建立彈性容器,並控制這些行中項目的顯示。
+
彈性盒子的典型用例
+
彈性盒子常見的設計範式。
+
彈性盒子的向下相容
+
彈性盒子的瀏覽器相容性、互操作性問題、支持舊版瀏覽器和規範的版本
+
+ +

規範

+ + + + + + + + + + + + + + + + +
規範狀態註解
{{ SpecName('CSS3 Flexbox') }}{{ Spec2('CSS3 Flexbox') }}初期定義。
+ +

參見

+ +
+
Flexbugs
+
a community-curated list of flexbox browser bugs and workarounds
+
Cross-browser Flexbox mixins
+
This article provides a set of mixins for those who want to create cross-browser flexbox experiences that even work in older browser that don't support the modern flexbox syntax
+
diff --git a/files/zh-tw/web/css/css_flexible_box_layout/using_css_flexible_boxes/index.html b/files/zh-tw/web/css/css_flexible_box_layout/using_css_flexible_boxes/index.html new file mode 100644 index 0000000000..19ca6226ec --- /dev/null +++ b/files/zh-tw/web/css/css_flexible_box_layout/using_css_flexible_boxes/index.html @@ -0,0 +1,382 @@ +--- +title: CSS彈性盒子用法 +slug: Web/CSS/CSS_Flexible_Box_Layout/Using_CSS_flexible_boxes +tags: + - '#RWD' + - CSS + - Web + - 例子 + - 先进的 + - 入门 + - 灵活 + - 盒 +translation_of: Web/CSS/CSS_Flexible_Box_Layout/Basic_Concepts_of_Flexbox +--- +
{{CSSRef}}
+ +

CSS3 彈性盒子,又稱flexbox,是為了適應不同螢幕尺寸和顯示設備而生的佈局模式針對許多應用而言,不用 floats 的彈性盒子模型會比塊狀模型(block model)易用,彈性容器的邊緣也不會與內容的邊緣重疊。

+ +

多數設計師會發現 flexbox 用起來比 box 簡單得多。像是不多注意 div 的話,它就會經常違反設計師意願地,跑到頁頂去──令 footer 附著在頁底,也因此變得很棘手。flexbox 的寬高能改變以適應顯示空間,將較低的元件固定住。Flexbox 邏輯也能讓你確實令 div 壓在頁面的右方或底部。Flexbox 元素的顯示順序,與原始碼的顯示順序相互獨立。

+ +

一些時髦的佈局,也能因而透過更簡潔的程式碼完成。這種有意的獨立性只影響視覺渲染,基於 HTML 原始碼的語意順序及瀏覽不會受到影響。

+ +
注:儘管 CSS 彈性盒子佈局規範還處於最終徵求意見稿(Last Call Working Draft)階段(參見最新編輯草案)、也不是所有瀏覽器都實做彈性盒子的所有功能。但這麼說好了,現在主流的瀏覽器,都對 flexbox 有著良好的支持。請參見相容性表格的具體屬性,以獲取最新的相容狀態。
+ +

彈性盒子的概念

+ +

Flex 排版的大致定義,是能更改該項目的長與(或)高,以便貼合任何顯示設備的空間。Flex container 能針對該元件擴張以便填補可用的空間、或收縮以便阻止空間溢出。

+ +

塊狀佈局(Block layout)以垂直方向為準、行內佈局(Inline layout)以水平方向為準、而彈性佈局(Flexbox layout)則同時允許這兩種。塊狀佈局雖適於頁面顯示,但在程式元件(application component)需要在用戶代理(user agent)變更、手機從垂直方向翻轉到水平方向……等變更定位、大小、拉伸、收縮的情形下,這種佈局就很難用了。彈性盒子佈局長於小規模佈局、而剛剛流行的格線佈局(Grid layout)則長於大規模佈局。二者皆為 CSS 工作小組為在不同用戶代理、書寫模式、和其他要求下的 Web 應用程式,提供良好互通性的一部分。

+ +

彈性盒子的字彙

+ +

在彈性盒子的世界,我們不會稱水平(inline)或垂直(block),而是主軸(main axis)與切軸(cross axis)。如果 flex-directioncolumn,主軸就會充當垂直、而切軸則充當水平。請參考下面的圖,它展示了一個 flex-directionrow 的彈性容器,意味著該彈性項目會基於主軸,作水平排列。

+ +

flex_terms.png

+ +
+
彈性容器(Flex container)
+
包住彈性項目(Flex item)的父元素。在 {{Cssxref("display")}} 屬性用上 flexinline-flex 值的,就是彈性容器。
+
彈性項目(Flex item)
+
+

所有彈性容器的子元素都會變成彈性項目。直接包含在彈性容器的文字,會被包裝成匿名的 Flex 項目。

+
+
軸(Axes)
+
+

所有彈性盒子布局都有兩個軸。主軸(main axis)是跟隨著彈性項目順序的軸、而切軸(cross axis)是垂直於主軸的軸。

+ +
    +
  • flex-direction 屬性啟用主軸。
  • +
  • justify-content 屬性定義目前彈性項目的主軸如何擺放。
  • +
  • align-items 屬性定義目前彈性項目的切軸如何擺放。
  • +
  • align-self 屬性定義目前單一彈性項目如何對齊。這個設定會覆蓋 align-items 的預設值。
  • +
+
+
方向(Directions)
+
+

彈性容器的 main start/main endcross start/cross end sides 描述了彈性項目流的起點與終點。它們跟隨著由 writing-mode 所建立的向量中,彈性容器的主軸與切軸排列(左至右或右至左……等等)。

+ +
    +
  • order assigns elements to ordinal groups and determines which elements appear first.
  • +
  • flex-flow 屬性是 flex-directionflex-wrap 屬性的簡寫,描述了彈性項目的整體布局。
  • +
+
+
Lines
+
+

Flex items can be laid out on either a single line or on several lines according to the flex-wrap property, which controls the direction of the cross axis and the direction in which new lines are stacked.

+
+
Dimensions
+
+

The flex items' agnostic equivalents of height and width are main size and cross size, which respectively follow the main axis and cross axis of the flex container.

+ + +
+
+ +

設計一個彈性盒子

+ +

要設計基於這種風格的 CSS 元素,請把 display 屬性設為:

+ +
display: flex;
+ +

或:

+ +
display: inline-flex;
+ +

這樣一來,元素就會變成彈性容器,而它的子元素們就會變成彈性項目。flex 值會讓彈性容器變成塊級元素(block-level element)、inline-flex 則會讓彈性容器成為單一的行內元素(atomic inline-level element)。

+ +
注意:如果需要支援較舊的瀏覽器,請把廠商前輟標記(vendor prefix tag)寫在 display 屬性(property),而不是屬性值(attribute)。例如:display: -webkit-flex
+ +

彈性項目需要留心……

+ +

Text that is directly contained inside a flex container is automatically wrapped in an anonymous flex item. However, an anonymous flex item that contains only white space is not rendered, as if it were designated display: none.

+ +

Absolutely positioned children of a flex container are positioned so that their static position is determined in reference to the main start content-box corner of their flex container.

+ +

The margins of adjacent flex items do not collapse. Using auto margins absorbs extra space in the vertical or horizontal direction and can be used for alignment or to separate adjacent flex items. See Aligning with 'auto' margins in the W3C CSS Flexible Box Layout Module specification for more details.

+ +

Flexbox's alignment properties do "true" centering, unlike other centering methods in CSS. This means that the flex items will stay centered, even if they overflow the flex container. This can sometimes be problematic, however, if they overflow past the top edge of the page, or the left edge (in LTR languages like English; the problem occurs on the right edge in RTL languages like Arabic), as you can't scroll to that area, even if there is content there! In a future release, the alignment properties will be extended to have a "safe" option as well. For now, if this is a concern, you can instead use margins to achieve centering, as they'll respond in a "safe" way and stop centering if they overflow. Instead of using the align- properties, just put auto margins on the flex items you wish to center. Instead of the justify- properties, put auto margins on the outside edges of the first and last flex items in the flex container. The auto margins will "flex" and assume the leftover space, centering the flex items when there is leftover space, and switching to normal alignment when not. However, if you're trying to replace justify-content with margin-based centering in a multi-line flexbox, you're probably out of luck, as you need to put the margins on the first and last flex item on each line. Unless you can predict ahead of time which items will end up on which line, you can't reliably use margin-based centering in the main axis to replace the justify-content property.

+ +

Recall that while the display order of the elements is independent of their order in the source code, this independence affects only the visual rendering, leaving speech order and navigation based on the source order. Even the {{cssxref("order")}} property does not affect speech or navigation sequence. Thus developers must take care to order elements properly in the source so as not to damage the document's accessibility.

+ +

彈性盒子的屬性

+ +

不對彈性盒子生效的屬性

+ +

由於彈性盒子使用不同的排版演算法,所以有些屬性不太適合用在彈性容器內:

+ + + +

示例

+ +

基本彈性排版示例

+ +

這個基本彈性將展示如何把「彈性化」引至某個元素、並在彈性狀態下相鄰該元素的表現。

+ +
​<!DOCTYPE html>
+<html lang="en">
+  <head>
+    <meta charset="utf-8">
+    <style>
+    .flex {
+        /* basic styling */
+        width: 350px;
+        height: 200px;
+        border: 1px solid #555;
+        font: 14px Arial;
+
+        /* flexbox setup */
+        display: flex;
+        flex-direction: row;
+    }
+
+    .flex > div {
+        flex: 1 1 auto;
+        width: 30px; /* To make the transition work nicely. (Transitions to/from
+                        "width:auto" are buggy in Gecko and Webkit, at least.
+                        See http://bugzil.la/731886 for more info.) */
+        transition: width 0.7s ease-out;
+    }
+
+    /* colors */
+    .flex > div:nth-child(1){ background: #009246; }
+    .flex > div:nth-child(2){ background: #F1F2F1; }
+    .flex > div:nth-child(3){ background: #CE2B37; }
+
+    .flex > div:hover {
+        width: 200px;
+    }
+
+    </style>
+  </head>
+  <body>
+    <p>Flexbox nuovo</p>
+    <div class="flex">
+      <div>uno</div>
+      <div>due</div>
+      <div>tre</div>
+    </div>
+  </body>
+</html>
+ +

聖杯排版示例

+ +

本示例將示範彈性盒子在不同的解析度之下,如何提供動態變更的能力。下圖將說明轉換。

+ +

HolyGrailLayout.png

+ +

這裡展示了貼合了瀏覽器視窗的排版,必須為智慧型手機視窗最佳化的情況。不僅尺寸要縮減,呈現順序也要改變。彈性盒子把這件事變得相當簡單。

+ +
​<!DOCTYPE html>
+<html lang="en">
+  <head>
+    <style>
+    body {
+        font: 24px Helvetica;
+        background: #999999;
+    }
+
+    #main {
+        min-height: 800px;
+        margin: 0;
+        padding: 0;
+        display: flex;
+        flex-flow: row;
+    }
+
+    #main > article {
+        margin: 4px;
+        padding: 5px;
+        border: 1px solid #cccc33;
+        border-radius: 7pt;
+        background: #dddd88;
+        flex: 3 1 60%;
+        order: 2;
+    }
+
+    #main > nav {
+        margin: 4px;
+        padding: 5px;
+        border: 1px solid #8888bb;
+        border-radius: 7pt;
+        background: #ccccff;
+        flex: 1 6 20%;
+        order: 1;
+    }
+
+    #main > aside {
+        margin: 4px;
+        padding: 5px;
+        border: 1px solid #8888bb;
+        border-radius: 7pt;
+        background: #ccccff;
+        flex: 1 6 20%;
+        order: 3;
+    }
+
+    header, footer {
+        display: block;
+        margin: 4px;
+        padding: 5px;
+        min-height: 100px;
+        border: 1px solid #eebb55;
+        border-radius: 7pt;
+        background: #ffeebb;
+    }
+
+    /* Too narrow to support three columns */
+    @media all and (max-width: 640px) {
+        #main, #page {
+            flex-direction: column;
+        }
+
+        #main > article, #main > nav, #main > aside {
+        /* Return them to document order */
+            order: 0;
+        }
+
+        #main > nav, #main > aside, header, footer {
+            min-height: 50px;
+            max-height: 50px;
+        }
+    }
+    </style>
+  </head>
+  <body>
+    <header>header</header>
+    <div id='main'>
+      <article>article</article>
+      <nav>nav</nav>
+      <aside>aside</aside>
+    </div>
+    <footer>footer</footer>
+  </body>
+</html>
+ +

遊樂場

+ +

以下提供一些與彈性盒子相關的網站讓你親手操作:

+ + + +

要注意的事情

+ +

有時候配置 Flex item 的演算法會有點難以理解。因此,在設計 Flexible box 時有一些指引,能讓你避免負面意義上的驚嘆。

+ +

Flexible box 通常會盡量貼合 writing mode 的配置,這意味著 main startmain end 會基於 startend 的位置來配置。

+ +

cross startcross end 依賴 startbefore 的定義的位置,其依賴 direction 的值

+ +

Page breaks are possible in flexible boxes layout as long as break- property allows it. CSS3 break-after, break-before, and break-inside as well as CSS 2.1 page-break-before, page-break-after, and page-break-inside properties are accepted on a flex container, flex items, and inside flex items.

+ +

瀏覽器相容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Basic support (single-line flexbox){{CompatGeckoDesktop("18.0")}}[6]{{property_prefix("-moz")}}[2]
+ {{CompatGeckoDesktop("22.0")}}
21.0{{property_prefix("-webkit")}}
+ 29.0
11[3]12.10{{property_prefix("-webkit")}}[5]6.1{{property_prefix("-webkit")}}[1]
Multi-line flexbox{{CompatGeckoDesktop("28.0")}}21.0{{property_prefix("-webkit")}}
+ 29.0
11[3]12.10[5]
+ 15 {{property_prefix("-webkit")}}
6.1{{property_prefix("-webkit")}}[1]
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureFirefox Mobile (Gecko)Firefox OSAndroidIE PhoneOpera MobileSafari Mobile
Basic support (single-line flexbox){{CompatGeckoMobile("18.0")}}{{property_prefix("-moz")}}[2]
+ {{CompatGeckoMobile("22.0")}}
+

1.0{{property_prefix("-moz")}}[2]
+ 1.1

+
2.1{{property_prefix("-webkit")}}[4]
+ 4.4
1112.10[5]
+ 15{{property_prefix("-webkit")}}
7{{property_prefix("-webkit")}}[1]
Multi-line flexbox{{CompatGeckoMobile("28.0")}}1.32.1{{property_prefix("-webkit")}}[4]
+ 4.4
1112.10[5]
+ 15{{property_prefix("-webkit")}}
7{{property_prefix("-webkit")}}[1]
+
+ +

[1] Safari up to version 6.0 (iOS.1) supported an old incompatible draft version of the specification. Safari 6.1 (and Safari on iOS 7) has been updated to support the final version.

+ +

[2] Up to Firefox 22, to activate flexbox support, the user has to change the about:config preference layout.css.flexbox.enabled to true. From Firefox 22 to Firefox 27, the preference is true by default, but the preference has been removed in Firefox 28.

+ +

[3] Internet Explorer 10 supports an old incompatible draft version of the specification; Internet Explorer 11 has been updated to support the final version.

+ +

[4] Android browser up to 4.3 supported an old incompatible draft version of the specification. Android 4.4 has been updated to support the final version.

+ +

[5] While in the initial implementation in Opera 12.10 flexbox was not prefixed, it got prefixed in versions 15 to 16 of Opera and 15 to 19 of Opera Mobile with {{property_prefix("-webkit")}}. The prefix was removed again in Opera 17 and Opera Mobile 24.

+ +

[6] Up to Firefox 29, specifying visibility: collapse on a flex item causes it to be treated as if it were display: none instead of the intended behavior, treating it as if it were visibility: hidden. The suggested workaround is to use visibility:hidden for flex items that should behave as if they were designated visibility:collapse. For more information, see {{bug(783470)}}.

+ +

參見

+ + diff --git a/files/zh-tw/web/css/css_grid_layout/basic_concepts_of_grid_layout/index.html b/files/zh-tw/web/css/css_grid_layout/basic_concepts_of_grid_layout/index.html new file mode 100644 index 0000000000..2c6c9685cc --- /dev/null +++ b/files/zh-tw/web/css/css_grid_layout/basic_concepts_of_grid_layout/index.html @@ -0,0 +1,715 @@ +--- +title: 格線佈局的基本概念 +slug: Web/CSS/CSS_Grid_Layout/Basic_Concepts_of_Grid_Layout +translation_of: Web/CSS/CSS_Grid_Layout/Basic_Concepts_of_Grid_Layout +--- +

CSS 格線佈局介紹了二維的 CSS 格線系統。格線可以用來佈置頁面的主要區域、或小型用戶介面。本文介紹 CSS 格線 Level 1 規範的其中一部份。這份概觀顯示的某些功能,將在教學的其他部份詳細解釋。

+ +

什麽是格線?

+ +

格線是一組水平線和垂直線的交叉集合(intersecting set):一個定義為行(row),另一個定義為列(column)。你可以讓各元素依照行列的規則放到各格線上。CSS 格線佈局具有以下特點:

+ +

固定和靈活的軌道尺寸

+ +

你可以給各格線指定一個固定的軌道大小,例如像素(pixel)。這樣就能把格線設為指定的像素,以貼近你期望的排版。也可以創建一個使用百分比、或是新的 fr 單位之格線。fr 單位就是為了格線布局而生。

+ +

單元佈置

+ +

你可以在格線使用行號、名字、目標區域,讓各單元放到精確的位置。格線也有控制非明式(explicit)單元的布局演算法。

+ +

Creation of additional tracks to hold content

+ +

你可以按照需求,定義明式格線、也可以處理沒有指定的格線、還可以增加額外的行(row)與列(column)。如果需要「盡可能地放進容器容得了的列」之類的也辦得到。

+ +

控制對齊

+ +

格線也包含了依序對齊的功能,以便控制各格線內的各單元、還有整個格線要如何對齊。

+ +

Control of overlapping content

+ +

數個單位也能被放進 grid cell、或是區域的一部分相互重疊。我們可以透過 {{cssxref("z-index")}} 控制該分層。

+ +

格線是個強大的規範、它在與諸如彈性盒子之類的 CSS 結合時,也有助於用 CSS 建立前所尚未有的排版。一切都建立要從建立格線容器(grid container)開始。

+ +

格線容器

+ +

我們會宣告 display: griddisplay: inline-grid 來給一個元素建立格線容器(grid container)。宣告以後,該元素的所有直接子元素會變成格線單位(grid item)

+ +

本例中,我有個稱作 wrapper class 的 div,裡面有五個元素。

+ +
<div class="wrapper">
+   <div>One</div>
+   <div>Two</div>
+   <div>Three</div>
+   <div>Four</div>
+   <div>Five</div>
+</div>
+
+ +

接著我讓 .wrapper 變成格線容器(grid container)。

+ +
.wrapper {
+  display: grid;
+}
+
+ + + +

{{ EmbedLiveSample('The_Grid_container', '200', '330') }}

+ +

在它下面的直接子元素,現在都是格線單元了。從網路瀏覽器來看,各單元變成格線的前後,似乎沒什麼不同,因為目前格線只有建立一個格線列,來放所有的格線單元。這時候,你會發現格線檢測器相當好用。如果在 Firefox 檢查這個示例的格線,你會發現在 grid 值旁邊,有一個小圖標。點選這個小圖標,瀏覽器視窗的元素,就會被一個圖層覆蓋。

+ +

Using the Grid Highlighter in DevTools to view a grid

+ +

在理解並與 CSS 格線共事時,這個工具能幫你視覺化理解,格線到底怎麼做動的。

+ +

如果要開始把做得更像格線,我們還需要多寫個 column track。

+ +

格線軌道(Grid Track)

+ +

我們在格線裡透過 {{cssxref("grid-template-columns")}} 與 {{cssxref("grid-template-rows")}} 屬性定義了行與列。它們也定義了格線軌道。格線軌道是在格線的兩個欄位之間的空隙。下圖就會看到軌道的高亮:就在格線裡面的第一行。

+ +

+ +

I can add to our earlier example by adding the grid-template-columns property, then defining the size of the column tracks.

+ +

I have now created a grid with three 200-pixel-wide column tracks. The child items will be laid out on this grid one in each grid cell.

+ +
+
<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', '200') }}

+
+ +

fr 單位

+ +

格線軌道可以使用任何單位定義,不過格線引入了額外的單位,以助於建立有彈性的格線軌道。新的單位 fr 代表格線容器內,可用空間的分塊(fraction)。接下來的格線定義,會建立三個同等、且能依照可用空間縮放的長度軌道。

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

+
+ +

接著下例將創建有一個 2fr 的軌道,接著還有兩個 1fr 的軌道。可用空間會因此被分為四塊:其中兩塊給第一個軌道、剩下兩塊給兩個軌道各一個。

+ +
.wrapper {
+  display: grid;
+  grid-template-columns: 2fr 1fr 1fr;
+}
+
+ +

最後,我們會把分塊與絕對大小做結合。第一個軌道有 500 像素,這個固定的寬度,會因此從可用空間先割一塊出去。接下來的空間會被劃分為三塊,並按比例指派給剩下的彈性軌道。

+ +
.wrapper {
+  display: grid;
+  grid-template-columns: 500px 1fr 2fr;
+}
+
+ +

Track listings with repeat() notation

+ +

含有許多軌道的格線能用 repeat() 標記,以使軌道透過迴圈表列數次。以下面為例:

+ +
.wrapper {
+  display: grid;
+  grid-template-columns: 1fr 1fr 1fr;
+}
+
+ +

這可以寫成:

+ +
.wrapper {
+  display: grid;
+  grid-template-columns: repeat(3, 1fr);
+}
+
+ +

重複標記是軌道表列一部分。下例中,我們建立了有 20 像素的軌道,接著重複 1fr 軌道六次,最後以 20 像素的軌道做結。

+ +
.wrapper {
+  display: grid;
+  grid-template-columns: 20px repeat(6, 1fr) 20px;
+}
+
+ +

重複標記使用軌道表列,因此可以用它來建立重複的模式。下個例子的格線,會包含十個軌道:也就是 1fr 後面有 2fr 的軌道,並重複五次。

+ +
.wrapper {
+  display: grid;
+  grid-template-columns: repeat(5, 1fr 2fr);
+}
+
+ +

明式與暗式格線

+ +

在建立上例格線的時候,我們用 {{cssxref("grid-template-columns")}} 屬性指定了列軌道,但格線自己也建立了一行。相較於使用 {{cssxref("grid-template-columns")}} 或 {{cssxref("grid-template-rows")}} 屬性的明式格線(explicit grid),這幾行就屬於暗式格線(implicit grid)。

+ +

你也能在暗式格線內透過 {{cssxref("grid-auto-rows")}} 與 {{cssxref("grid-auto-columns")}} 屬性,給軌道定義一套大小。

+ +

下例將使用 grid-auto-rows 以確保由暗式格線建立的軌道,高度都會是 200 像素。

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

+ +

軌道縮放與 minmax()

+ +

在設定顯式格線或希望自動給軌道一個最小尺寸,但也要確保它們擴展以適應任何添加的內容——像是希望某行不能小於 100 像素以避免跑版,但如果內容高度超過 300 像素,該行就要拉到那麼高。

+ +

針對這個情境,格線提供了 {{cssxref("minmax", "minmax()")}} 函式。本例中,我針對 {{cssxref("grid-auto-rows")}} 指定了 minmax() 的數值。它會指定高度最小要 100 像素,最大則是 autoauto 意味著大小會檢查內容大小,並適配這一行 cell 內最高項目的高度。

+ +
.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') }}

+ +

Grid Lines

+ +

It should be noted that when we define a grid we define the grid tracks, not the lines. Grid then gives us numbered lines to use when positioning items. In our three column, two row grid we have four column lines.

+ +

Diagram showing numbered grid lines.

+ +

Lines are numbered according to the writing mode of the document. In a left-to-right language, line 1 is on the left-hand side of the grid. In a right-to-left language, it is on the right-hand side of the grid. Lines can also be named, and we will look at how to do this in a later guide in this series.

+ +

Positioning items against lines

+ +

We will be exploring line based placement in full detail in a later article, the following example demonstrates doing this in a simple way. When placing an item we target the line – rather than the track.

+ +

In the following example I am placing the first two items on our three column track grid, using the {{cssxref("grid-column-start")}}, {{cssxref("grid-column-end")}}, {{cssxref("grid-row-start")}} and {{cssxref("grid-row-end")}} properties. Working from left to right, the first item is placed against column line 1, and spans to column line 4, which in our case is the far right line on the grid. It begins at row line 1 and ends at row line 3, therefore spanning two row tracks.

+ +

The second item starts on grid column line 1, and spans one track. This is the default so I do not need to specify the end line. It also spans two row tracks from row line 3 to row line 5. The other items will place themselves into empty spaces on the 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') }}

+ +

Don't forget that you can use the Grid Inspector in Firefox Developer Tools to see how the items are positioned against the lines of the grid.

+ +

Grid Cells

+ +

A grid cell is the smallest unit on a grid, conceptually it is like a table cell. As we saw in our earlier examples, once a grid is defined on a parent the child items will lay themselves out once in each cell of the defined grid. In the below image I have highlighted the first cell of the grid.

+ +

The first cell of the grid highlighted

+ +

Grid areas

+ +

Items can span one or more cells both by row or by column, and this creates a grid area. Grid areas have to be rectangular – it isn’t possible to create an L-shaped area for example. The highlighted grid area spans two row and two column tracks.

+ +

A grid area

+ +

Gutters

+ +

Gutters or alleys between grid cells can be created using the {{cssxref("grid-column-gap")}} and {{cssxref("grid-row-gap")}} properties, or the shorthand {{cssxref("grid-gap")}}. In the below example I am creating a 10-pixel gap between columns and a 1em gap between rows.

+ +
.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') }}

+ +

Any space used by gaps will be accounted for before space is assigned to flexible length fr tracks, and gaps act for sizing purposes like a regular grid track, however you cannot place anything into a gap. In terms of line-based positioning, the gap acts like a fat line.

+ +

Nesting grids

+ +

A grid item can become a grid container. In the following example I have the three-column grid created earlier, with our two positioned items. In this case the first item has some sub-items. As these items are not direct children of the grid they do not participate in grid layout and so display in normal document flow.

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

+ +

If I set box1 to display: grid I can give it a track definition and it too will become a grid, the items then lay out on this new 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') }}

+ +

In this case the nested grid has no relationship to the parent. As you can see in the example it has not inherited the {{cssxref("grid-gap")}} of the parent and the lines in the nested grid do not align to the lines in the parent grid.

+ +

Subgrid

+ +

In the level 1 grid specification there is a feature called subgrid which would let us create nested grids that use the track definition of the parent grid.

+ +
+

Subgrids are not yet implemented in any browsers, and the specification is subject to change.

+
+ +

In the current specification, we would edit the above nested grid example to use display: subgrid rather than display: grid, then remove the track definition. The nested grid will use the parent grid tracks to lay out items.

+ +

It should be noted that the nested grid is in both dimensions—rows and columns. There is no concept of the implicit grid working with subgrids. This means you need to ensure that the parent grid has enough row and column tracks for all the subitems.

+ +
.box1 {
+   grid-column-start: 1;
+   grid-column-end: 4;
+   grid-row-start: 1;
+   grid-row-end: 3;
+   display: subgrid;
+}
+
+ +

Layering items with z-index

+ +

Grid items can occupy the same cell. If we return to our example with items positioned by line number, we can change this to make two items overlap.

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

+ +

The item box2 is now overlapping box1, it displays on top as it comes later in the source order.

+ +

Controlling the order

+ +

We can control the order in which items stack up by using the z-index property - just as with positioned items. If we give box2 a lower z-index than box1 it will display below box1 in the stack.

+ +
.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') }}

+ +

下一步

+ +

In this article we have had a very quick look through the Grid Layout Specification. Have a play with the code examples, and then move onto the next part of this guide where we will really start to dig into the detail of CSS Grid Layout.

+ + diff --git a/files/zh-tw/web/css/css_grid_layout/index.html b/files/zh-tw/web/css/css_grid_layout/index.html new file mode 100644 index 0000000000..0fd5616848 --- /dev/null +++ b/files/zh-tw/web/css/css_grid_layout/index.html @@ -0,0 +1,252 @@ +--- +title: CSS格線布局 +slug: Web/CSS/CSS_Grid_Layout +tags: + - CSS + - 參考 + - 布局 + - 柵格 + - 示列 + - 網格布局 +translation_of: Web/CSS/CSS_Grid_Layout +--- +

CSS 格線佈局長於把頁面的主要區域分離、或是在 HTML 原生語法構建的區域間,定義大小、位置、層次等方面的關聯。

+ +

格線佈局使作者能夠對齊元素為行和列,就像表格一樣,。然而,格線佈局可以更輕易的達成比一般表格更多元化的排版。例如,一個網格容器的子元素可以定位自己和層重疊,類似於CSS定位元素。

+ +

基本示例

+ +

以下示例展示了一個三列軌道格線,其中創建的行數最小為 100 像素,最大為 auto。Items 已經使用基於線放置在網格的位置上。

+ +
+ + +

HTML

+ +
<div class="wrapper">
+  <div class="one">One</div>
+  <div class="two">Two</div>
+  <div class="three">Three</div>
+  <div class="four">Four</div>
+  <div class="five">Five</div>
+  <div class="six">Six</div>
+</div>
+ +

CSS

+ +
.wrapper {
+  display: grid;
+  grid-template-columns: repeat(3, 1fr);
+  grid-gap: 10px;
+  grid-auto-rows: minmax(100px, auto);
+}
+.one {
+  grid-column: 1 / 3;
+  grid-row: 1;
+}
+.two {
+  grid-column: 2 / 4;
+  grid-row: 1 / 3;
+}
+.three {
+  grid-row: 2 / 5;
+  grid-column: 1;
+}
+.four {
+  grid-column: 3;
+  grid-row: 3;
+}
+.five {
+  grid-column: 2;
+  grid-row: 4;
+}
+.six {
+  grid-column: 3;
+  grid-row: 4;
+}
+
+ +

{{ EmbedLiveSample('example', '500', '440') }}

+
+ +

參考

+ +

CSS 屬性

+ +
+ +
+ +

CSS 函式

+ +
+ +
+ +

CSS 資料型別

+ +
+ +
+ +

詞匯表條目

+ +
+ +
+ +

指引

+ +
+ +
+ +

外部資源

+ + + +

規範

+ + + + + + + + + + + + + + + + +
格式狀態意見
{{ SpecName('CSS3 Grid') }}{{ Spec2('CSS3 Grid') }}初始定義
+ + diff --git a/files/zh-tw/web/css/css_lists_and_counters/consistent_list_indentation/index.html b/files/zh-tw/web/css/css_lists_and_counters/consistent_list_indentation/index.html new file mode 100644 index 0000000000..cdde84086c --- /dev/null +++ b/files/zh-tw/web/css/css_lists_and_counters/consistent_list_indentation/index.html @@ -0,0 +1,67 @@ +--- +title: 調整列表縮排 +slug: Web/CSS/CSS_Lists_and_Counters/Consistent_list_indentation +tags: + - CSS + - list indent + - 列表 + - 縮排 +translation_of: Web/CSS/CSS_Lists_and_Counters/Consistent_list_indentation +--- +

原文 : Consistent List Indentation

+ + +

  使用 CSS 來協助縮排列表看來簡單實則卻否,原因很簡單 - 各大瀏覽器其實作方式不盡相同。一個很大的原因來自於對距離的掌握,但這很讓人喪志,因為瀏覽器沒有一致的排版方式。舉例來說,倘若你宣告一個 list 沒有 left margin,在 IE 中他可以被移動,但在 Gecko-based 的瀏覽器中他們將很固執的固定在那。

+ +

  為了更徹底明白為何有這種情況發生,了解列表是怎樣被創造的至關重要。

+

創建列表

+

  首先,我們考慮一個最簡單的 list item。他並不屬於任何一個 list 中,並且也沒有項目符號 (意思就是沒有 bullet )。如 Figure 1 所示:

+

Figure 1

+

  這裡的紅點線框是 list 內容的外框。在這裡的例子中, list item 並沒有設定 padding 或 borders。現在我們加上兩個 list item,如圖二:

+

Figure 2

+

  接著我們加上 parent element,這裡我們以 unordered list (i.e., <ul>)為例。根據 CSS box model,這些 list item 都會被包裹在 parent element 的範圍中。如下圖中的紫色外框,他包住了三個 list item 的外圍:

+

Figure 3

+

  然後我們加上 list item markers。因為我們用的是 unordered list,因此使用預設的 filled-circle "bullets"。結果如下:

+

Figure 4

+

  好的,現在看出來了,這些 marker 在 <ul> 空間之外。但更重要的是,這些 marker 其實是在 <li> 之外!這個結果使得 list item 看起來像是附加在 marker 之上。

+

  結論出來了,在瀏覽器(除了 windows 下的 IE)處理列表時, marker 是在 <li> element 的外頭。所以這些個對 list item 的設定並不會對 marker 造成影響,影響的是其後附加的內容。

+

二次縮排

+

  所以我們該如何設定其外觀?現在讓我們來分析一下下們這組設定:

+
ul, li {margin-left: 0; padding-left: 0;}
+

  當套用了這組設定, marker 將會很悲劇的落到畫面之外。

+

  為了避免這種慘劇發生,瀏覽器有三種不同的實作方式來避免:

+
    +
  1. 幫每一個 <li> element 設定 left margin
  2. +
  3. 幫 <ul> element 設定 left margin
  4. +
  5. 幫 <ul> element 設定一些 left padding
  6. +
+

  事後檢視,沒有瀏覽器採用第一種作法。Windows and Macintosh 上的 Internet Explorer 和 Opera 採用第二種作法。Gecko 相關的瀏覽器則使用第三種設計。

+

  現在讓我們來瞧瞧後兩種作法的差異。在 Internet Explorer 及 Opera 中,<ul> element 為了縮排需要被設定了 40 pixel 的 left margin。假如我們此時在 <ul> element 設定背景顏色,其結果如下:

+

Figure 5

+

  Gecko 則不太一樣,他為 <ul> element 設定了 40 pixel 的 left padding。因此造成上圖的程式碼會在 Gecko 中變成下圖:

+

Figure 6

+

  從結果來說,marker 都很好的附著在 <li> element 之前並未消失。唯一的不同點是發生在你替 <ul> element 設定背景顏色時。

+

不變的是 ...

+

  現在我們知道,若你希望在 Gecko, Internet Explorer 和 Opera 都有一樣的 list 外觀, <ul> element 的 left margin 和 left padding 都要設定。你大可不必理會 <li> 的設定。

+

  假如你想要有 Netscape 6.x 的預設風格,寫法如下:

+
ul {margin-left: 0; padding-left: 40px;}
+

  若你對 Explorer/Opera 風格有興趣,可以寫成:

+
ul {margin-left: 40px; padding-left: 0;}
+

  當然啦,你可以不用 pixel 來表示長度,取而代之的可以使用類似 1.25em 的寫法。現在若你想要重設列表,而不打算有任何縮排,可以這樣寫:

+
ul {margin-left: 0; padding-left: 0;}
+

  請注意,這樣的寫法將造成 bullet 被扔在整個列表及其 parent element 之外。當你在 body 中這樣寫,很顯然的你的 bullet 將不會出現在你的視窗內。

+

結論

+

  在這篇文章中我們並未指出哪個瀏覽器對 list 縮排的處理是正確的。之所以會有不同的排版方式只是因為他們採用了不同的排版方法。確定你設定了 list 的 left padding 和 left margin,這樣你比較能寫出跨瀏覽器良好縮排程式。

+

建議

+ +
+

關於此文件

+ +
diff --git a/files/zh-tw/web/css/css_lists_and_counters/index.html b/files/zh-tw/web/css/css_lists_and_counters/index.html new file mode 100644 index 0000000000..08b7fc4bcf --- /dev/null +++ b/files/zh-tw/web/css/css_lists_and_counters/index.html @@ -0,0 +1,127 @@ +--- +title: CSS Lists and Counters +slug: Web/CSS/CSS_Lists_and_Counters +translation_of: Web/CSS/CSS_Lists_and_Counters +--- +
{{CSSRef}}
+ +

CSS Lists and Counters is a module of CSS that defines how lists are laid out, how the list marker can be styled and how authors can create new counters.

+ +

參考

+ +

屬性

+ +
+ +
+ +

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")}}
  • +
+
+
+
+ +

指南

+ +
+
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 traditional list elements or to perform complex counting.
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Lists')}}{{Spec2('CSS3 Lists')}} 
{{SpecName('CSS2.1', 'generate.html')}}{{Spec2('CSS2.1')}}Initial definition
+ +

瀏覽器相容性

+ +

{{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/zh-tw/web/css/css_positioning/index.html b/files/zh-tw/web/css/css_positioning/index.html new file mode 100644 index 0000000000..0fe6fd55d0 --- /dev/null +++ b/files/zh-tw/web/css/css_positioning/index.html @@ -0,0 +1,108 @@ +--- +title: CSS Positioning +slug: Web/CSS/CSS_Positioning +translation_of: Web/CSS/CSS_Positioning +--- +

{{CSSRef}}

+ +

CSS Positioning is a module of CSS that defines how to absolutely and relavitely position elements on the page.

+ +

參考

+ +

CSS 屬性

+ +
+ +
+ +

指南

+ +
+
Understanding CSS z-index
+
Presents the notion of stacking context and explain how z-ordering works, with several examples.
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSS3 Positioning') }}{{ Spec2('CSS3 Positioning') }} 
{{ SpecName('CSS2.1', 'visuren.html') }}{{ Spec2('CSS2.1') }} 
+ +

瀏覽器相容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support1.0{{ CompatGeckoDesktop("1") }}5.06.01.0 (85)
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support1.0{{ CompatGeckoMobile("1") }}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
diff --git a/files/zh-tw/web/css/css_positioning/understanding_z_index/index.html b/files/zh-tw/web/css/css_positioning/understanding_z_index/index.html new file mode 100644 index 0000000000..8bfd77a677 --- /dev/null +++ b/files/zh-tw/web/css/css_positioning/understanding_z_index/index.html @@ -0,0 +1,40 @@ +--- +title: Understanding CSS z-index +slug: Web/CSS/CSS_Positioning/Understanding_z_index +tags: + - Advanced + - CSS + - Guide + - NeedsTranslation + - TopicStub + - Understanding_CSS_z-index + - Web +translation_of: Web/CSS/CSS_Positioning/Understanding_z_index +--- +

Usually HTML pages can be considered two-dimensional, because text, images and other elements are arranged on the page without overlapping. There is a single rendering flow, and all elements are aware of the space taken by others. The {{cssxref("z-index")}} attribute lets you adjust the order of the layering of objects when rendering content.

+
+

In CSS 2.1, each box has a position in three dimensions. In addition to their horizontal and vertical positions, boxes lie along a "z-axis" and are formatted one on top of the other. Z-axis positions are particularly relevant when boxes overlap visually.

+
+

(from CSS 2.1 Section 9.9.1 - Layered presentation)

+

It means that CSS style rules allow you to position boxes on layers in addition to the normal rendering layer (layer 0). The Z position of each layer is expressed as an integer representing the stacking order for rendering. Greater numbers mean closer to the observer. Z position can be controlled with the CSS {{ cssxref("z-index") }} property.

+

Using z-index appears extremely easy: a single property, assigned a single integer number, with an easy-to-understand behaviour. However, when z-index is applied to complex hierarchies of HTML elements, its behaviour can be hard to understand or even unpredictable. This is due to complex stacking rules. In fact a dedicated section has been reserved in the CSS specification CSS-2.1 Appendix E to explain these rules better.

+

This article will try to explain those rules, with some simplification and several examples.

+
    +
  1. Stacking without z-index : Default stacking rules
  2. +
  3. Stacking and float : How floating elements are handled
  4. +
  5. Adding z-index : Using z-index to change default stacking
  6. +
  7. The stacking context : Notes on the stacking context
  8. +
  9. Stacking context example 1 : 2-level HTML hierarchy, z-index on the last level
  10. +
  11. Stacking context example 2 : 2-level HTML hierarchy, z-index on all levels
  12. +
  13. Stacking context example 3 : 3-level HTML hierarchy, z-index on the second level
  14. +
+

Note of the author: Thanks to Wladimir Palant and Rod Whiteley for the review.

+
+

Original Document Information

+ +
+

 

diff --git a/files/zh-tw/web/css/css_positioning/understanding_z_index/stacking_context_example_1/index.html b/files/zh-tw/web/css/css_positioning/understanding_z_index/stacking_context_example_1/index.html new file mode 100644 index 0000000000..26771f0fbb --- /dev/null +++ b/files/zh-tw/web/css/css_positioning/understanding_z_index/stacking_context_example_1/index.html @@ -0,0 +1,139 @@ +--- +title: Stacking context example 1 +slug: Web/CSS/CSS_Positioning/Understanding_z_index/Stacking_context_example_1 +translation_of: Web/CSS/CSS_Positioning/Understanding_z_index/Stacking_context_example_1 +--- +

« CSS « 理解CSS的z-index

+ +

堆疊環境範例1

+ +

讓我們先從一個基本的例子。根堆疊情況下,我們有兩個div(DIV#1和#DIV 3),兩種相對定位的,但是如果沒有的z-index屬性。裡面DIV#1有一個絕對定位的div#2,而在DIV#3有一個絕對定位的div#4,雙方沒有的z-index屬性。

+ +

唯一的堆疊上下文是根上下文。如果沒有Z-指標,要素依次層疊的發生。

+ +

堆疊環境範例1

+ +

如果DIV#2被分配一個正的(非零和非自動)z索引值,它是上述所有其他的DIV呈現。

+ +

堆疊環境範例1

+ +

然後,如果DIV#4也被分配比DIV#2的Z指數正z指數越大,它上面的所有其他的DIV DIV,包括2#呈現。

+ +

堆疊環境範例1

+ +

在最後的例子,你可以看到,DIV#2和#DIV 4不兄弟姐妹,因為它們屬於不同的家長在HTML元素的層次結構。即便如此,DIV#4堆疊相的DIV#2可以通過z索引來控制。碰巧的是,由於DIV#1和#DIV 3不指定任何的z-index值,他們不創造一個堆疊環境。這意味著,所有的內容,包括DIV#2和DIV#4屬於相同根堆疊環境。

+ +

在堆疊上下文而言,DIV#1和DIV#3簡單地同化到根元素,將得到的層次結構如下:

+ + + +
注: DIV#1和#DIV 3不適透亮。重要的是要記住,分配的不透明度小於1到定位的元素隱式創建一個疊加的背景下,就像一個加入的z-index值是非常重要的。這個例子顯示,當父元素不會創建一個堆疊環境會發生什麼。
+ +

示例源代碼

+ +
<!DOCTYPE HTML PUBLIC“ -  // W3C // DTD XHTML 1.0過渡// EN”
+“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
+<HTML>
+<HEAD> <風格類型=“文本/ CSS”>
+
+DIV {字體:12px的宋體; }
+
+span.bold {字體重量:大膽的; }
+
+#DIV1,#{DIV3
+   高度:80px;
+   位置:親屬;
+   邊界:1px的虛線#669966;
+   背景色:#ccffcc;
+   填充左:5px的;
+}
+
+#{DIV2
+   不透明度:0.8;
+   的z-index:1;
+   位置:絕對的;
+   寬度:150像素;
+   高度:200像素;
+   頂:20像素;
+   左:170px;
+   邊界:1px的虛線#990000;
+   背景色:#ffdddd;
+   文本對齊:中心;
+}
+
+#{DIV4
+   不透明度:0.8;
+   的z-index:2;
+   位置:絕對的;
+   寬度:200像素;
+   高度:70px;
+   頂部:65px;
+   左:50像素;
+   邊界:1px的虛線#000099;
+   背景色:#ddddff;
+   文本對齊:左;
+   填充左:10px的;
+}
+
+
+</風格> </ HEAD>
+
+<BODY>
+
+<br />
+
+<DIV ID =“DIV1”>
+<br />的<span class =“黑體”> DIV#1 </ SPAN>
+<br />位置:親屬;
+   <DIV ID =“DIV2”>
+   <br />的<span class =“黑體”> DIV#2 </ SPAN>
+   <br />位置:絕對的;
+   <br />的z-index:1;
+   </ DIV>
+</ DIV>
+
+<br />
+
+<DIV ID =“DIV3”>
+<br />的<span class =“黑體”> DIV#3 </ SPAN>
+<br />位置:親屬;
+   <DIV ID =“DIV4”>
+   <br />的<span class =“黑體”> DIV#4 </ SPAN>
+   <br />位置:絕對的;
+   <br />的z-index:2;
+   </ DIV>
+</ DIV>
+
+</ BODY> </ HTML>
+
+ +

另請參見

+ + + +
+

原始文檔信息

+ + +
+ +

 

diff --git a/files/zh-tw/web/css/css_properties_reference/index.html b/files/zh-tw/web/css/css_properties_reference/index.html new file mode 100644 index 0000000000..74d192427e --- /dev/null +++ b/files/zh-tw/web/css/css_properties_reference/index.html @@ -0,0 +1,317 @@ +--- +title: CSS 屬性參考 +slug: Web/CSS/CSS_Properties_Reference +translation_of: Web/CSS/CSS_Properties_Reference +--- +

常見 CSS 屬性參考

+ +

下列為最為常見的 CSS 屬性基本清單及其對應的 文件物件模型(DOM)屬性——通常由 JavaScript 進行存取:

+ +
備註:  此清單並不完整, 更多屬性請見  CSS 參考文件 與  Mozilla CSS extensions。 CSS參考文件也包含屬性使用範例。
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CSSJavaScript
backgroundbackground
background-attachmentbackgroundAttachment
background-colorbackgroundColor
background-imagebackgroundImage
background-positionbackgroundPosition
background-repeatbackgroundRepeat
borderborder
border-bottomborderBottom
border-bottom-colorborderBottomColor
border-bottom-styleborderBottomStyle
border-bottom-widthborderBottomWidth
border-colorborderColor
border-leftborderLeft
border-left-colorborderLeftColor
border-left-styleborderLeftStyle
border-left-widthborderLeftWidth
border-rightborderRight
border-right-colorborderRightColor
border-right-styleborderRightStyle
border-right-widthborderRightWidth
border-styleborderStyle
border-topborderTop
border-top-colorborderTopColor
border-top-styleborderTopStyle
border-top-widthborderTopWidth
border-widthborderWidth
clearclear
clipclip
colorcolor
cursorcursor
displaydisplay
filterfilter
fontfont
font-familyfontFamily
font-sizefontSize
font-variantfontVariant
font-weightfontWeight
heightheight
leftleft
letter-spacingletterSpacing
line-heightlineHeight
list-stylelistStyle
list-style-imagelistStyleImage
list-style-positionlistStylePosition
list-style-typelistStyleType
marginmargin
margin-bottommarginBottom
margin-leftmarginLeft
margin-rightmarginRight
margin-topmarginTop
overflowoverflow
paddingpadding
padding-bottompaddingBottom
padding-leftpaddingLeft
padding-rightpaddingRight
padding-toppaddingTop
page-break-afterpageBreakAfter
page-break-beforepageBreakBefore
positionposition
floatcssFloat
text-aligntextAlign
text-decorationtextDecoration
text-decoration: blinktextDecorationBlink
text-decoration: line-throughtextDecorationLineThrough
text-decoration: nonetextDecorationNone
text-decoration: overlinetextDecorationOverline
text-decoration: underlinetextDecorationUnderline
text-indenttextIndent
text-transformtextTransform
toptop
vertical-alignverticalAlign
visibilityvisibility
widthwidth
z-indexzIndex
diff --git a/files/zh-tw/web/css/css_selectors/index.html b/files/zh-tw/web/css/css_selectors/index.html new file mode 100644 index 0000000000..5f52beea02 --- /dev/null +++ b/files/zh-tw/web/css/css_selectors/index.html @@ -0,0 +1,123 @@ +--- +title: CSS Selectors +slug: Web/CSS/CSS_Selectors +translation_of: Web/CSS/CSS_Selectors +--- +
{{CSSRef}}
+ +

選擇器可以定義某組 CSS 樣式要套用到哪些元素上。

+ +

基本選擇器

+ +
+
通用選擇器Universal selector
+
用以選擇所有元素。(可選)可以將其限制為特定的名稱空間或所有名稱空間。
+ 語法: * ns|* *|*
+ 範例: * 套用文檔中所有元素。
+
標籤選擇器Type selector
+
用以選擇所有符合指定標籤的元素。
+ 語法: elementname
+ 範例: input 可選出任一 <input> 元素。
+
類別選擇器Class selector
+
用以選擇所有符合指定 class 屬性值的元素。
+ 語法: .classname
+ 範例: .index 可選出任一含有 index 的 class 屬性值之元素。
+
ID選擇器ID selector
+
用以選擇指定 id 屬性值的元素。(一個文件中,每個ID屬性都是唯一的。)
+ 語法: #idname
+ 範例: #toc 會比對含有 ID 是 toc 的元素(可以定義成 id="toc" 或其他類似的定義)。
+
屬性選擇器Attribute selector
+
用以選擇所有符合指定屬性的元素。
+ 語法: [attr] [attr=value] [attr~=value] [attr|=value] [attr^=value] [attr$=value] [attr*=value]
+ 範例: [autoplay] 將會套用含有 autoplay 屬性的元素。(不論這個屬性的值是什麼)。
+
+ +

分組選擇器

+ +
+
選擇器列表(Selector list
+
, 用以將不同的選擇器組合起來的一種方法。
+ 語法: AB
+ 範例: div, span 將同時選擇 <div><span> 元素。
+
+ +

組合選擇器

+ +
+
+
後代選擇器Descendant combinator
+
  (空格) 用以選擇某個元素後代的元素。
+ 語法: A B
+ 範例: div span 套用所有  <div> 元素內部的所有 <span> 元素。
+
子代選擇器Child combinator
+
> 用以選擇某個元素後代的元素。
+ 語法: A > B(B元素不可在A元素的其他元素裡)
+ 範例: ul > li 套用所有 <li> 元素內部的 <ul> 子元素。
+
一般兄弟選擇器General sibling combinator
+
~ combinator selects siblings. This means that the second element follows the first (though not necessarily immediately), and both share the same parent.
+ 語法: A ~ B
+ 範例: p ~ span will match all {{HTMLElement("span")}} elements that follow a {{HTMLElement("p")}}, immediately or not.
+
相鄰兄弟選擇器Adjacent sibling combinator
+
+ 選擇緊接在後的元素,並共享父元素。
+ 語法: A + B
+ 範例: h2 + p 套用所有 緊接在 <h2> 元素後的 <p> 元素,並擁有 <h2> 的父元素。
+
Column combinator {{Experimental_Inline}}
+
The || combinator selects nodes which belong to a column.
+ 語法: A || B
+ 範例: col || td will match all {{HTMLElement("td")}} elements that belong to the scope of the {{HTMLElement("col")}}.
+
+ +

偽選擇器

+ +
+
Pseudo classes
+
The : pseudo allow the selection of elements based on state information that is not contained in the document tree.
+ 範例: a:visited will match all {{HTMLElement("a")}} elements that have been visited by the user.
+
Pseudo elements
+
The :: pseudo represent entities that are not included in HTML.
+ 範例: p::first-line will match the first line of all {{HTMLElement("p")}} elements.
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("CSS4 Selectors")}}{{Spec2("CSS4 Selectors")}}Added the || column combinator, grid structural selectors, logical combinators, location, time-demensional, resource state, linguistic and UI pseudo-classes, modifier for ASCII case-sensitive and case-insensitive attribute value selection.
{{SpecName("CSS3 Selectors")}}{{Spec2("CSS3 Selectors")}}Added the ~ general sibling combinator and tree-structural pseudo-classes.
+ Made pseudo-elements use a :: double-colon prefix. Additional attribute selectors
{{SpecName("CSS2.1", "selector.html")}}{{Spec2("CSS2.1")}}Added the > child and + adjacent sibling combinators.
+ Added the universal and attribute selectors.
{{SpecName("CSS1")}}{{Spec2("CSS1")}}Initial definition.
+ +

See the pseudo-class and pseudo-element specification tables for details on those.

+ +

參見

+ + diff --git a/files/zh-tw/web/css/css_selectors/using_the__colon_target_pseudo-class_in_selectors/index.html b/files/zh-tw/web/css/css_selectors/using_the__colon_target_pseudo-class_in_selectors/index.html new file mode 100644 index 0000000000..e21ca62c5f --- /dev/null +++ b/files/zh-tw/web/css/css_selectors/using_the__colon_target_pseudo-class_in_selectors/index.html @@ -0,0 +1,62 @@ +--- +title: '使用 :target' +slug: 'Web/CSS/CSS_Selectors/Using_the_:target_pseudo-class_in_selectors' +translation_of: 'Web/CSS/CSS_Selectors/Using_the_:target_pseudo-class_in_selectors' +--- +

When a URL points at a specific piece of a document, it can be difficult to ascertain. Find out how you can use some simple CSS to draw attention to the target of a URL and improve the user's experience. As an aid to identifying the destination of a link that points to a specific portion of a document, CSS3 Selectors introduces the {{ Cssxref(":target") }} pseudo-class. Netscape 7.1 introduced support for this pseudo-class into the Netscape family, giving authors a new way to assist users keep oriented within large documents.

+ +

挑選目標

+ +

The pseudo-class {{ Cssxref(":target") }} is used to style the target element of a URI containing a fragment identifier. For example, the URI http://developer.mozilla.org/en/docs/Using_the_:target_selector#Example contains the fragment identifier #Example. In HTML, identifiers are found as the values of either id or name attributes, since the two share the same namespace. Thus, the example URI would point to the heading "Example" in this document.

+ +

Suppose you wish to style any h2 element that is the target of a URI, but do not want any other kind of element to get a target style. This is simple enough:

+ +
h2:target {font-weight: bold;}
+ +

It's also possible to create styles that are specific to a particular fragment of the document. This is done using the same identifying value that is found in the URI. Thus, to add a border to the #Example fragment, we would write:

+ +
#Example:target {border: 1px solid black;}
+ +

選擇所有元素

+ +

If the intent is to create a "blanket" style that will apply to all targeted elements, then the universal selector comes in handy:

+ +
:target {color: red;}
+
+ +

範例

+ +

In the following example, there are five links that point to elements in the same document. Selecting the "First" link, for example, will cause <h1 id="one"> to become the target element. Note that the document may jump to a new scroll position, since target elements are placed on the top of the browser window if possible.

+ +
+
<h4 id="one">...</h4> <p id="two">...</p>
+<div id="three">...</div> <a id="four">...</a> <em id="five">...</em>
+
+<a href="#one">First</a>
+<a href="#two">Second</a>
+<a href="#three">Third</a>
+<a href="#four">Fourth</a>
+<a href="#five">Fifth</a>
+
+ +

結論

+ +

In cases where a fragment identifier points to a portion of the document, readers may become confused about which part of the document they're supposed to be reading. By styling the target of a URI, reader confusion can be reduced or eliminated.

+ + + + + +
+

文檔訊息

+ + +
diff --git a/files/zh-tw/web/css/css_transitions/index.html b/files/zh-tw/web/css/css_transitions/index.html new file mode 100644 index 0000000000..30fb2738c2 --- /dev/null +++ b/files/zh-tw/web/css/css_transitions/index.html @@ -0,0 +1,110 @@ +--- +title: CSS Transitions +slug: Web/CSS/CSS_Transitions +translation_of: Web/CSS/CSS_Transitions +--- +
{{CSSRef}}{{SeeCompatTable}}
+ +

CSS Transitions is a module of CSS that defines how to create smooth transitions between values of given CSS properties. It allows to create them but also to define their evolution, using timing functions.

+ +

參考

+ +

屬性

+ +
+ +
+ +

指南

+ +
+
Using CSS transitions
+
Step-by-step tutorial about how to create smooth transitions using CSS. This article describes each relevant CSS property and explains how they interact.
+
+ +

規範

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Transitions')}}{{Spec2('CSS3 Transitions')}}Initial definition
+ +

瀏覽器相容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1.0 {{property_prefix("-webkit")}}
+ 26.0
{{CompatGeckoDesktop("2.0")}} {{property_prefix("-moz")}}
+ {{CompatGeckoDesktop("16.0")}}
10.011.6 {{property_prefix("-o")}}
+ 12.10 #
3.0 {{property_prefix("-webkit")}}
+ 6.1
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support2.1 {{property_prefix("-webkit")}}{{CompatGeckoMobile("2.0")}} {{property_prefix("-moz")}}
+ {{CompatGeckoMobile("16.0")}}
{{CompatUnknown}}10.0 {{property_prefix("-o")}}
+ 12.10 #
3.2 {{property_prefix("-webkit")}}
+
+ +

參見

+ + diff --git a/files/zh-tw/web/css/css_transitions/using_css_transitions/index.html b/files/zh-tw/web/css/css_transitions/using_css_transitions/index.html new file mode 100644 index 0000000000..ecbdf92487 --- /dev/null +++ b/files/zh-tw/web/css/css_transitions/using_css_transitions/index.html @@ -0,0 +1,384 @@ +--- +title: CSS 轉場 +slug: Web/CSS/CSS_Transitions/Using_CSS_transitions +tags: + - CSS animation + - CSS transition + - CSS 轉場 + - CSS 過渡 +translation_of: Web/CSS/CSS_Transitions/Using_CSS_transitions +--- +

   

+
+

原文 : https://developer.mozilla.org/en/CSS/CSS_transitions

+

 

+
+

{{ SeeCompatTable() }}

+

   CSS transitions 是 CSS3 specification 草案的一部分,他可以用來調整 CSS animation 變動的速度。舉例來說,倘若你設計了一個 element 會由白轉紅,你可以透過 CSS transitions 來控制轉變的時間及變化曲線。

+
+ 注意: CSS transitions specification 目前仍舊以草案形式存在,所以當你要在 Gecko 的系統中使用時,記得加上 "-moz-" 的前綴。此外,為了更好的相容,你還得加上 "-webkit-" 前綴 (給基於 Webkit 技術的瀏覽器)以及 "-o-" (Opera 使用)。舉例來說,你可能會寫出包含有 -moz-transition-webkit-transition 及 -o-transition 的程式。
+

可供調整的 CSS property 清單

+

  CSS transitions 和 CSS animations 中可以用來修改的屬性在 CSS animatable properties 可以看到。這裡頭同時包含了 SVG properties。

+
+ 注意: 這些列出 properties 可能都還會改變,所以請使用已經被支援的那些,以免造成無法預期的結果。
+

CSS transition properties

+

  我們可以透過 {{ cssxref("transition") }} property 來控制 CSS transitions。這可有效避免使用過長的參數來控制你的 transitions,這樣亦減少了 debug 的難度。

+

  下列的 sub-properties 可以協助你控制轉場的性質:

+
+
+ {{ cssxref("transition-property") }}
+
+  定義哪些 CSS properties 會被轉場效果影響。除了這些被你特別指出的 property 名單,其他的轉場一如以往的會在瞬間完成。
+
+ {{ cssxref("transition-duration") }}
+
+ 定義轉場所花費的時間。你可以只定義一個時間給所有 property 使用,也可以給定多組不同時間。
+
+ {{ cssxref("transition-timing-function") }}
+
+ 設定轉場時所依據的貝茲曲線。
+
+ {{ cssxref("transition-delay") }}
+
+ 定義多久之後開始發生轉場。
+
+

使用漸變函式 (transition timing function)

+

  漸變函式可用來定義轉場發生的時間曲線。其規範方式是以四個參數的貝茲曲線代表:

+

+

  CSS transition function manipulator 是一個可以讓你非常容易以視覺化方式了解轉場流程的工具。

+

  除了自行定義之外,尚有幾個已經預先定義好的函式:

+
    +
  • ease, 等同於 cubic-bezier(0.25, 0.1, 0.25, 1.0)
  • +
  • linear, 等同於 cubic-bezier(0.0, 0.0, 1.0, 1.0)
  • +
  • ease-in, 等同於 cubic-bezier(0.42, 0, 1.0, 1.0)
  • +
  • ease-out, 等同於 cubic-bezier(0, 0, 0.58, 1.0)
  • +
  • ease-in-out, 等同於 cubic-bezier(0.42, 0, 0.58, 1.0)
  • +
+

一個 transition timing effect 範例

+

  我們在這直接用範例來說明。

+

  在看程式碼之前,或許你會想先看看實際的執行效果。請挑個有支援 transitions 的瀏覽器,然後看看這個 (而這裡有這個範例的相關 CSS 程式碼)。

+

  首先,先以 HTML 創建這個範例的主要外殼:

+
<ul>
+  <li id="long1">Long, gradual transition...</li>
+  <li id="fast1">Very fast transition...</li>
+  <li id="delay1">Long transition with a 2-second delay...</li>
+  <li id="easeout">Using ease-out timing...</li>
+  <li id="linear">Using linear timing...</li>
+  <li id="cubic1">Using cubic-bezier(0.2, 0.4, 0.7, 0.8)...</li>
+</ul>
+
+

  如你所見,每個 item 都有自己的 ID。剩下的部份交由 CSS 來處理。

+

使用延遲機制

+

  這個範例會在使用者滑鼠移過 element 後兩秒開始四秒的字體大小變化:

+
#delay1 {
+  position: relative;
+  transition-property: font-size;
+  transition-duration: 4s;
+  transition-delay: 2s;
+  font-size: 14px;
+}
+
+#delay1:hover {
+  transition-property: font-size;
+  transition-duration: 4s;
+  transition-delay: 2s;
+  font-size: 36px;
+}
+
+

使用線性轉場函式 (linear transition timing function)

+

  如果你希望動畫的變動是以線性的速率,那你可以寫成:

+
transition-timing-function: linear;
+
+

  此外,還有許多不同的 timing functions 供你選擇,請見 {{ cssxref("transition-timing-function") }}。

+

用貝茲曲線定義 timing function

+

  你可以定義自己想要的 timing function,這要用貝茲曲線 (cubic bezier curve) 的形式定義之:

+
  transition-timing-function: cubic-bezier(0.2, 0.4, 0.7, 0.8);
+
+

  上例中我們定義了一個以 (0.0, 0.0), (0.2, 0.4), (0.7, 0.8) 和 (1.0, 1.0) 描述的貝茲曲線。

+

偵測 transition 的完成

+

  在設計上,當 transition 完成時會觸發一個 event。在 Firefox 中,他是 transitionend ; 在 Opera 中,他是 oTransitionEnd ; 而在 WebKit 中,他是  webkitTransitionEnd。請注意相容性的問題(參閱本頁最下方)。

+

  transitionend event 提供了兩個 properties:

+
+
+ propertyName
+
+ 這指出哪個 CSS property 的 transition 已經完成。
+
+ elapsedTime
+
+ 指出 transition 花費了幾秒。注意,他不受 {{ cssxref("transition-delay") }} 影響。
+
+

  在平常使用上,你可以使用 {{ domxref("element.addEventListener()") }} method 來監控:

+
el.addEventListener("transitionend", updateTransition, true);
+
+
+ 注意: "transitionend" event 若 transition 在執行中被中斷(意指 transition 沒有真正完成)則不會觸發。
+

當 property value list 之間並不等長時 ... ?

+

  如果某個 property 的 list 長度比其他短時,他將會被重複,直到等長。例如:

+
div {
+  transition-property: opacity, left, top, height;
+  transition-duration: 3s, 5s;
+}
+
+

  他會被瀏覽器解釋成:

+
div {
+  transition-property: opacity, left, top, height;
+  transition-duration: 3s, 5s, 3s, 5s;
+}
+

  可以預期地,倘若列出的 value 過多,他會被切斷。例如:

+
div {
+  transition-property: opacity, left;
+  transition-duration: 3s, 5s, 2s, 1s;
+}
+

  那麼他等同於:

+
div {
+  transition-property: opacity, left;
+  transition-duration: 3s, 5s;
+}
+

使用 transitions 來強調選單中的選項

+

  一個使用 CSS 的好時機是用來強調目前使用者滑鼠經過的選單位置。使用 transitions 可以使效果變得更吸引人。

+

  在看實際的程式碼之前,你可以先看實際的範例 (當然你的瀏覽器要能支援 transitions)。相關的 CSS 程式在這裡。 

+

  我們先用 HTML 構建外殼:

+
<div class="sidebar">
+  <p><a class="menuButton" href="home">Home</a></p>
+  <p><a class="menuButton" href="about">About</a></p>
+  <p><a class="menuButton" href="contact">Contact Us</a></p>
+  <p><a class="menuButton" href="links">Links</a></p>
+</div>
+
+

  接著用 CSS 來產生特效:

+
.menuButton {
+  position: relative;
+  transition-property: background-color, color;
+  transition-duration: 1s;
+  transition-timing-function: ease-out;
+  -webkit-transition-property: background-color, color;
+  -webkit-transition-duration: 1s;
+  -o-transition-property: background-color, color;
+  -o-transition-duration: 1s;
+  text-align: left;
+  background-color: grey;
+  left: 5px;
+  top: 5px;
+  height: 26px;
+  color: white;
+  border-color: black;
+  font-family: sans-serif;
+  font-size: 20px;
+  text-decoration: none;
+  -moz-box-shadow: 2px 2px 1px black;
+  padding: 2px 4px;
+  border: solid 1px black;
+}
+
+.menuButton:hover {
+  position: relative;
+  transition-property: background-color, color;
+  transition-duration: 1s;
+  transition-timing-function: ease-out;
+  -webkit-transition-property: background-color, color;
+  -webkit-transition-duration: 1s;
+  -o-transition-property: background-color, color;
+  -o-transition-duration: 1s;
+  background-color:white;
+  color:black;
+  -moz-box-shadow: 2px 2px 1px black;
+}
+
+

  這些 CSS 程式使滑鼠滑過時 (在該 element 的 {{ cssxref(":hover") }} state) 造成背景及文字顏色的改變。

+

使用 transitions 來使 JavaScript 運作的更順暢

+

  Transition 是一種很好的工具,他可以幫助你的 JavaScript 執行結果看起來的更為順暢。舉例來說:

+
<p>Click anywhere to move the ball</p>
+<div id="foo"></div>
+
+

  當你使用 JavaScript 可以將 ball 移動到特定位置:

+
var f = document.getElementById('foo');
+document.addEventListener('click', function(ev){
+    f.style.left = (ev.clientX-25)+'px';
+    f.style.top = (ev.clientY-25)+'px';
+},false);    
+
+

  藉由 CSS,你可以使執行結果更為流暢。我們加入了:

+
p{
+  padding-left:60px;
+}
+#foo{
+  border-radius:50px;
+  width:50px;
+  height:50px;
+  background:#c00;
+  position:absolute;
+  top:0;
+  left:0;
+  -moz-transition: all 1s; 
+  -webkit-transition: all 1s;  
+  -ms-transition: all 1s;  
+  -o-transition: all 1s;  
+  transition: all 1s;  
+}
+
+

  你可以到 http://jsfiddle.net/RwtHn/5/ 看範例。

+

使用 transition events 來替 object 製作動畫

+

  這裡讓我們看個例子,一個內含文字的方塊左右來回移動,並且會在兩種顏色之間做轉變:

+

 

+ +

  在我們仔細研究程式碼之前可以先看範例。同樣地,可以到看其 CSS 的寫法。

+

HTML 程式碼

+

  搭配上面範例的 HTML 程式碼並不複雜:

+
<!DOCTYPE html>
+<html>
+  <head>
+    <title>CSS Transition Demo</title>
+    <link rel="stylesheet" href="transitions.css" type="text/css">
+    <script src="transitions.js" type="text/javascript"></script>
+  </head>
+  <body onload="runDemo()">
+    <div class="slideRight">This is a box!</div>
+  </body>
+</html>
+
+

  這裡唯一要注意的地方是我們用 slideRight 來修飾 "This is a box!"。此外,在這個文件被讀取時,就會觸發 runDemo() function。

+

CSS 程式碼

+

  我們使用 slideRight 和 slideLeft 這兩個 CSS class 來建構動畫 (請參閱 transitions.css )。這裡列出部分:

+
.slideRight {
+  position: absolute;
+  -moz-transition-property: background-color, color, left;
+  -moz-transition-duration: 5s;
+  -webkit-transition-property: background-color, color, left;
+  -webkit-transition-duration: 5s;
+  -o-transition-property: background-color, color, left;
+  -o-transition-duration: 5s;
+  background-color: red;
+  left: 0%;
+  color: black;
+}
+
+

  我們再這明確定義了 position property。這是一件必要的事情,不然動畫將不知道如何開始。

+

  {{ cssxref("transition-property") }} property 指出哪些 CSS properties 會被包含在動畫效果中。在這個例子中是 {{ cssxref("background-color") }}, {{ cssxref("color") }} 以及 {{ cssxref("left") }}。 {{ cssxref("transition-duration") }} property 則說明了整個動畫將歷時 5 秒。

+

  為了相容於 WebKit 及 Opera,當中還定了一些以 "-webkit-" 和 "-o-" 起始的 property。

+

  總的來說, "slideRight" class 定義了最左端點時的狀態 (準備向右滑動)。所以你可以看到 {{ cssxref("left") }} property 是 0% 。

+

  下面我們定義了 "slideLeft" class,他表示最右端時的狀態 (準備向左滑動):

+
.slideLeft {
+  position: absolute;
+  -moz-transition-property: background-color, color, left;
+  -moz-transition-duration: 5s;
+  -webkit-transition-property: background-color, color, left;
+  -webkit-transition-duration: 5s;
+  -o-transition-property: background-color, color, left;
+  -o-transition-duration: 5s;
+  text-align: center;
+  background-color: blue;
+  left: 90%;
+  color: white;
+  width: 100px;
+  height: 100px;
+}
+

JavaScript 程式碼

+

  在定義了左右兩端點的狀態後,現在我們可以準備來描述 animation 了。這可以簡單的透過 JavaScript 達成。

+
+ 注意: 在這裡,倘若 CSS animations 被使用者的瀏覽器支援,那就未必要使用 JavaScript 了。
+

  首先定義 runDemo() function,他將在文件被讀取後立刻執行:

+
function runDemo() {
+  var el = updateTransition();
+
+  // Set up an event handler to reverse the direction
+  // when the transition finishes.
+
+  el.addEventListener("transitionend", updateTransition, true);
+}
+
+

  他呼叫了 updateTransition() function (這待會會定義),並且他捕捉了 "transitionend" event,這使我們能夠知道動畫結束了。

+

  updateTransition() function 內容如下:

+
function updateTransition() {
+  var el = document.querySelector("div.slideLeft");
+
+  if (el) {
+    el.className = "slideRight";
+  } else {
+    el = document.querySelector("div.slideRight");
+    el.className = "slideLeft";
+  }
+
+  return el;
+}
+
+

  這裡的機制很簡單,我們找到 "slideLeft" 而後將他改變成 "slideRight",接著動畫便結束。倘若此時並沒有 "slideLeft",就表示已在右端點,於是執行反向動作。

+

瀏覽器的支援情形

+

{{ CompatibilityTable() }}

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support1.0{{ CompatGeckoDesktop("2") }}1010.53.2
Property-webkit-transition-moz-transition-ms-transition-o-transition-webkit-transition
Transition ended eventwebkitTransitionEndtransitionendMSTransitionEndoTransitionEndwebkitTransitionEnd
+
+
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support2.1{{ CompatGeckoMobile("2") }}{{ CompatUnknown() }}103.2
+
+

更多資訊

+ +

{{ HTML5ArticleTOC() }}

+

{{ languages( { "es": "es/CSS/Transiciones_de_CSS", "ja": "ja/CSS/CSS_transitions" } ) }}

+
+
+

 

diff --git a/files/zh-tw/web/css/cursor/index.html b/files/zh-tw/web/css/cursor/index.html new file mode 100644 index 0000000000..6e20cbbb43 --- /dev/null +++ b/files/zh-tw/web/css/cursor/index.html @@ -0,0 +1,306 @@ +--- +title: cursor +slug: Web/CSS/cursor +translation_of: Web/CSS/cursor +--- +
{{CSSRef}}
+ +

此 cursor CSS 屬性可以指定當滑鼠指標指向哪個物件時,顯示不同的游標.

+ +
{{EmbedInteractiveExample("pages/css/cursor.html")}}
+ + + +

語法

+ +
/* 關鍵字值 */
+cursor: pointer;
+cursor: auto;
+
+/* URL, with a keyword fallback */
+cursor: url(hand.cur), pointer;
+
+/* URL and coordinates, with a keyword fallback */
+cursor: url(cursor1.png) 4 12, auto;
+cursor: url(cursor2.png) 2 2, pointer;
+
+/* 全域值 */
+cursor: inherit;
+cursor: initial;
+cursor: unset;
+
+ +

The cursor property is specified as zero or more <url> values, separated by commas, followed by a single mandatory keyword value. Each <url> should point to an image file. The browser will try to load the first image specified, falling back to the next if it can't, and falling back to the keyword value if no images could be loaded (or if none were specified).

+ +

Each <url> may be optionally followed by a pair of space-separated numbers, which represent <x><y> coordinates. These will set the cursor's hotspot, relative to the top-left corner of the image.

+ +

For example, this specifies two images using <url> values, providing <x><y> coordinates for the second one, and falling back to the progress keyword value if neither image can be loaded:

+ +
cursor: url(one.svg), url(two.svg) 5 5, progress;
+ +

數值

+ +
+
<url>
+
A url(…) or a comma separated list url(…), url(…), …, pointing to an image file. More than one {{cssxref("<url>")}} may be provided as fallbacks, in case some cursor image types are not supported. A non-URL fallback (one or more of the keyword values) must be at the end of the fallback list. See Using URL values for the cursor property for more details.
+
<x> <y> {{experimental_inline}}
+
Optional x- and y-coordinates. Two unitless nonnegative numbers less than 32.
+
關鍵字值
+
+

Move your mouse over values to see their live appearance in your browser:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
分類CSS 值範例備註說明
一般auto The UA will determine the cursor to display based on the current context. E.g., equivalent to text when hovering text.
defaultdefault.gifThe platform-dependent default cursor. Typically an arrow.
none No cursor is rendered.
連結與狀態context-menucontext-menu.pngA context menu is available.
helphelp.gifHelp information is available.
pointerpointer.gifThe cursor is a pointer that indicates a link. Typically an image of a pointing hand.
progressprogress.gifThe program is busy in the background, but the user can still interact with the interface (in contrast to wait).
waitwait.gifThe program is busy, and the user can't interact with the interface (in contrast to progress). Sometimes an image of an hourglass or a watch.
選取cellcell.gifThe table cell or set of cells can be selected.
crosshaircrosshair.gifCross cursor, often used to indicate selection in a bitmap.
texttext.gifThe text can be selected. Typically the shape of an I-beam.
vertical-textvertical-text.gifThe vertical text can be selected. Typically the shape of a sideways I-beam.
拖曳aliasalias.gifAn alias or shortcut is to be created.
copycopy.gifSomething is to be copied.
movemove.gifSomething is to be moved.
no-dropno-drop.gifAn item may not be dropped at the current location.
+ {{bug("275173")}}: On Windows and Mac OS X, no-drop is the same as not-allowed.
not-allowednot-allowed.gifThe requested action will not be carried out.
grabgrab.gifSomething can be grabbed (dragged to be moved).
grabbinggrabbing.gifSomething is being grabbed (dragged to be moved).
改變尺寸與捲軸尺all-scrollall-scroll.gifSomething 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 them.
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.
+ In some environments, an equivalent bidirectional resize cursor is shown. For example, n-resize and s-resize are the same as ns-resize.
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.gifBidirectional resize cursor.
ns-resize6-resize.gif
nesw-resize1-resize.gif
nwse-resize4-resize.gif
縮放zoom-inzoom-in.gif +

Something can be zoomed (magnified) in or out.

+
zoom-outzoom-out.gif
+
+
+ +

公式語法

+ +
{{csssyntax}}
+
+ +

範例

+ +
.foo {
+  cursor: crosshair;
+}
+
+.bar {
+  cursor: zoom-in;
+}
+
+/* A fallback keyword value is required when using a URL */
+.baz {
+  cursor: url("hyper.cur"), auto;
+}
+
+ +

規格

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Basic UI', '#cursor', 'cursor')}}{{Spec2('CSS3 Basic UI')}}Addition of several keywords and the positioning syntax for url().
{{SpecName('CSS2.1', 'ui.html#cursor-props', 'cursor')}}{{Spec2('CSS2.1')}}Initial definition.
+ +

{{cssinfo}}

+ +

瀏覽器相容性

+ + + +

{{Compat("css.properties.cursor")}}

+ +

參照

+ + diff --git a/files/zh-tw/web/css/descendant_combinator/index.html b/files/zh-tw/web/css/descendant_combinator/index.html new file mode 100644 index 0000000000..6fe82cfc8d --- /dev/null +++ b/files/zh-tw/web/css/descendant_combinator/index.html @@ -0,0 +1,121 @@ +--- +title: 後裔選擇器 +slug: Web/CSS/Descendant_combinator +tags: + - CSS + - CSS參考 + - Selectors + - 初學者 + - 選擇器 +translation_of: Web/CSS/Descendant_combinator +--- +

{{CSSRef("Selectors")}}

+ +

簡介

+ +

組合符號 (代表空白, 或更精準地說,代表一或多個空白字元) 結合了兩種選擇器,選擇了只有當第二個選擇器的目標為第一個選擇器目標的後裔時的元素,後裔選擇器跟子選擇器相似,但是不要求披對的元素要是嚴格是父子關係。

+ +

語法

+ +
selector1 selector2 { style properties }
+
+ +

範例

+ +
span { background-color: white; }
+div span { background-color: DodgerBlue; }
+
+ +
<div>
+  <span>Span 1.
+    <span>Span 2.</span>
+  </span>
+</div>
+<span>Span 3.</span>
+
+ +

{{ EmbedLiveSample('Example', 200, 50) }}

+ +

Specifications

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

Browser compatibility

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
diff --git a/files/zh-tw/web/css/grid-row/index.html b/files/zh-tw/web/css/grid-row/index.html new file mode 100644 index 0000000000..d7c3ed1543 --- /dev/null +++ b/files/zh-tw/web/css/grid-row/index.html @@ -0,0 +1,194 @@ +--- +title: grid-row +slug: Web/CSS/grid-row +translation_of: Web/CSS/grid-row +--- +

Summary 

+ +

The grid-row CSS property is a shorthand property for {{cssxref("grid-row-start")}} and {{cssxref("grid-row-end")}} specifying a grid item’s size and location within the grid row by contributing a line, a span, or nothing (automatic) to its grid placement, thereby specifying the inline-start and inline-end edge of its {{glossary("grid areas", "grid area")}}.

+ +

If two <grid-line> values are specified, the grid-row-start longhand is set to the value before the slash, and the grid-row-end longhand is set to the value after the slash.

+ +

{{cssinfo}}

+ +

Syntax

+ +
/* Keyword values */
+grid-row: auto;
+grid-row: auto / auto;
+
+/* <custom-ident> values */
+grid-row: somegridarea;
+grid-row: somegridarea / someothergridarea;
+
+/* <integer> + <custom-ident> values */
+grid-row: somegridarea 4;
+grid-row: 4 somegridarea / 6;
+
+/* span + <integer> + <custom-ident> values */
+grid-row: span 3;
+grid-row: span somegridarea;
+grid-row: 5 somegridarea span;
+grid-row: span 3 / 6;
+grid-row: span somegridarea / span someothergridarea;
+grid-row: 5 somegridarea span / 2 span;
+
+/* Global values */
+grid-row: inherit;
+grid-row: initial;
+grid-row: unset;
+
+ +

Values

+ +
+
auto
+
Is a keyword indicating that the property contributes nothing to the grid item’s placement, indicating auto-placement, an automatic span, or a default span of 1.
+
<custom-ident>
+
If there is a named line with the name '<custom-ident>-start'/'<custom-ident>-end', it contributes the first such line to the grid item’s placement. +

Note: Named grid areas automatically generate implicit named lines of this form, so specifying grid-row: foo; will choose the start/end edge of that named grid area (unless another line named foo-start/foo-end was explicitly specified before it).

+ +

Otherwise, this is treated as if the integer 1 had been specified along with the <custom-ident>.

+
+
<integer> && <custom-ident>?
+
Contributes the nth grid line to the grid item’s placement. If a negative integer is given, it instead counts in reverse, starting from the end edge of the explicit grid. +

If a name is given as a <custom-ident>, only lines with that name are counted. If not enough lines with that name exist, all implicit grid lines are assumed to have that name for the purpose of finding this position.

+ +

An {{cssxref("integer")}} value of 0 is invalid.

+
+
span && [ <integer> || <custom-ident> ]
+
Contributes a grid span to the grid item’s placement such that the corresponding edge of the grid item’s grid area is n lines from the opposite edge. +

If a name is given as a <custom-ident>, only lines with that name are counted. If not enough lines with that name exist, all implicit grid lines on the side of the explicit grid corresponding to the search direction are assumed to have that name for the purpose of counting this span.

+ +

If the <integer> is omitted, it defaults to 1. Negative integers or 0 are invalid.

+
+
+ +

Formal syntax

+ +
{{csssyntax}}
+ +

Example

+ +

HTML Content

+ +
<div id="grid">
+  <div id="item1"></div>
+  <div id="item2"></div>
+  <div id="item3"></div>
+</div>
+ +

CSS Content

+ +
#grid {
+  display: grid;
+  height: 200px;
+  grid-template-columns: 200px;
+  grid-template-rows: repeat(6, 1fr);
+}
+
+#item1 {
+  background-color: lime;
+}
+
+#item2 {
+  background-color: yellow;
+  grid-row: 2 / 4;
+}
+
+#item3 {
+  background-color: blue;
+  grid-row: span 2 / 7;
+}
+
+ +

{{EmbedLiveSample("Example", "200px", "200px")}}

+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("CSS3 Grid", "#propdef-grid-row", "grid-row")}}{{Spec2("CSS3 Grid")}}Initial definition
+ +

Browser compatibility

+ + + +

{{Compat("css.properties.grid-row")}}

+ +

See also

+ + + + diff --git a/files/zh-tw/web/css/grid-template-columns/index.html b/files/zh-tw/web/css/grid-template-columns/index.html new file mode 100644 index 0000000000..31ef2b30b3 --- /dev/null +++ b/files/zh-tw/web/css/grid-template-columns/index.html @@ -0,0 +1,196 @@ +--- +title: 网格模板列 +slug: Web/CSS/grid-template-columns +tags: + - CSS + - CSS網格 + - 列子 +translation_of: Web/CSS/grid-template-columns +--- +

Summary

+ +

The grid-template-columns CSS property defines the line names and track sizing functions of the {{glossary("grid column", "grid columns")}}.

+ +

{{cssinfo}}

+ +

Syntax

+ +
/* Keyword value */
+grid-template-columns: none;
+
+/* <track-list> values */
+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);
+
+/* <auto-track-list> values */
+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];
+
+/* Global values */
+grid-template-columns: inherit;
+grid-template-columns: initial;
+grid-template-columns: unset;
+
+ +

Values

+ +
+
none
+
Is a keyword meaning that there is no explicit grid. Any columns will be implicitly generated and their size will be determined by the {{cssxref("grid-auto-columns")}} property.
+
<length>
+
Is a non-negative length.
+
<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.
+
+ +

Formal syntax

+ +
{{csssyntax}}
+ +

Examples

+ +

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

Result

+ +

{{EmbedLiveSample("Examples", "100%", "20px")}}

+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("CSS3 Grid", "#propdef-grid-template-columns", "grid-template-columns")}}{{Spec2("CSS3 Grid")}}Initial definition
+ +

Browser compatibility

+ + + +

{{Compat("css.properties.grid-template-columns")}}

+ +

See also

+ + + + diff --git a/files/zh-tw/web/css/grid-template/index.html b/files/zh-tw/web/css/grid-template/index.html new file mode 100644 index 0000000000..9363bb9e1e --- /dev/null +++ b/files/zh-tw/web/css/grid-template/index.html @@ -0,0 +1,197 @@ +--- +title: grid-template +slug: Web/CSS/grid-template +translation_of: Web/CSS/grid-template +--- +

grid-templateCSS屬性是一個速記屬性,用於定義{{詞彙表(“網格列”,“網格列”)}},{{詞彙表(“網格行”,“行”)}},和{{詞彙表(“格狀區“,” area“)}}。

+ +
{{EmbedInteractiveExample(“ pages / css / grid-template.html”)}}
+ + + +

作者可以為長期屬性設置值:{{cssxref(“ grid-template-rows”)}},{{cssxref(“ grid-template-columns”)}}和{{cssxref(“ grid-template-areas “)}}。

+ +

句法

+ +
/* Keyword value */
+grid-template: none;
+
+/* grid-template-rows / grid-template-columns values */
+grid-template: 100px 1fr / 50px 1fr;
+grid-template: auto 1fr / auto 1fr auto;
+grid-template: [linename] 100px / [columnname1] 30% [columnname2] 70%;
+grid-template: fit-content(100px) / fit-content(40%);
+
+/* grid-template-areas grid-template-rows / grid-template-column values */
+grid-template: "a a a"
+               "b b b";
+grid-template: "a a a" 20%
+               "b b b" auto;
+grid-template: [header-top] "a a a"     [header-bottom]
+                 [main-top] "b b b" 1fr [main-bottom]
+                            / auto 1fr auto;
+
+/* Global values */
+grid-template: inherit;
+grid-template: initial;
+grid-template: unset;
+
+ +

價值觀

+ +
+
none
+
是將所有三個長期屬性設置為的關鍵字none,表示沒有顯式網格。沒有命名的網格區域。行和列將隱式生成;它們的大小將由{{cssxref(“ grid-auto-rows”)}}和{{cssxref(“ grid-auto-columns”)}}屬性確定。
+
<'grid-template-rows'> / <'grid-template-columns'>
+
將{{cssxref(“ grid-template-rows”)}}和{{cssxref(“ grid-template-columns”)}}設置為指定值,並設置{{cssxref(“ grid-template-areas”)} }至none
+
[ <line-names>? <string> <track-size>? <line-names>? ]+ [ / <explicit-track-list> ]?
+
Sets {{cssxref("grid-template-areas")}} to the strings listed, {{cssxref("grid-template-rows")}} to the track sizes following each string (filling in auto for any missing sizes), and splicing in the named lines defined before/after each size, and {{cssxref("grid-template-columns")}} to the track listing specified after the slash (or none, if not specified).
+ +

Note: The {{cssxref("repeat")}} function isn’t allowed in these track listings, as the tracks are intended to visually line up one-to-one with the rows/columns in the “ASCII art”.

+
+
+ +

Note: The {{cssxref("grid")}} shorthand accepts the same syntax, but also resets the implicit grid properties to their initial values. Use grid (as opposed to grid-template) to prevent these values from cascading in seperately.

+ +

Formal syntax

+ +
{{csssyntax}}
+ +

Examples

+ +

CSS

+ +
#page {
+  display: grid;
+  width: 100%;
+  height: 200px;
+  grid-template: [header-left] "head head" 30px [header-right]
+                 [main-left]   "nav  main" 1fr  [main-right]
+                 [footer-left] "nav  foot" 30px [footer-right]
+                 / 120px 1fr;
+}
+
+header {
+  background-color: lime;
+  grid-area: head;
+}
+
+nav {
+  background-color: lightblue;
+  grid-area: nav;
+}
+
+main {
+  background-color: yellow;
+  grid-area: main;
+}
+
+footer {
+  background-color: red;
+  grid-area: foot;
+}
+ +

HTML

+ +
<section id="page">
+  <header>Header</header>
+  <nav>Navigation</nav>
+  <main>Main area</main>
+  <footer>Footer</footer>
+</section>
+ +

Result

+ +

{{EmbedLiveSample("Examples", "100%", "200px")}}

+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("CSS3 Grid", "#propdef-grid-template", "grid-template")}}{{Spec2("CSS3 Grid")}}Initial definition
+ +

{{cssinfo}}

+ +

Browser compatibility

+ + + +

{{Compat("css.properties.grid-template")}}

+ +

See also

+ + + + diff --git a/files/zh-tw/web/css/height/index.html b/files/zh-tw/web/css/height/index.html new file mode 100644 index 0000000000..139ec496b6 --- /dev/null +++ b/files/zh-tw/web/css/height/index.html @@ -0,0 +1,234 @@ +--- +title: height +slug: Web/CSS/height +translation_of: Web/CSS/height +--- +
{{CSSRef}}
+ +

概要

+ +

高度(height) 的 CSS 屬性指定了元素內容區域的高度。content area 在元素的留白(padding)、邊框(border) 與 邊界(margin) 內。

+ +

{{cssxref("min-height")}} 與 {{cssxref("max-height")}} 的特性比 {{Cssxref("height")}} 更重要。

+ +

{{cssinfo}}

+ +

語法

+ +
/* Keyword value */
+height: auto;
+
+/* <length> values */
+height: 120px;
+height: 10em;
+
+/* <percentage> value */
+height: 75%;
+
+/* Global values */
+height: inherit;
+height: initial;
+height: unset;
+
+ +

+ +
+
<length>
+
查看 {{cssxref("<length>")}} 可用的單位。
+
<percentage>
+
{{cssxref("<percentage>")}} 相對於元素的塊狀高度。如果沒有指定塊狀元素的高度,預設值為 auto。用在 root 元素 (e.g. <html>) 上是相對於初始塊狀元素(即顯示器的尺寸)。
+
border-box {{experimental_inline}}
+
If present, the preceding {{cssxref("<length>")}} or {{cssxref("<percentage>")}} is applied to the element's border box.
+
content-box {{experimental_inline}}
+
{{cssxref("<length>")}} 或 {{cssxref("<percentage>")}} 是應用於元素的 content box.
+
auto
+
瀏覽器將計算並選擇指定元素的高度。
+
fill {{experimental_inline}}
+
Use the fill-available inline size or fill-available block size, as appropriate to the writing mode.
+
max-content {{experimental_inline}}
+
The intrinsic preferred height.
+
min-content {{experimental_inline}}
+
The intrinsic minimum height.
+
available {{experimental_inline}}
+
The containing block height minus vertical margin, border and padding.
+
fit-content {{experimental_inline}}
+
The larger of: +
    +
  • the intrinsic minimum height
  • +
  • the smaller of the intrinsic preferred height and the available height
  • +
+
+
+ +

正式語法

+ +
{{csssyntax}}
+ +

範例

+ +

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('Example')}}

+ +

規格

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
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 definition
{{SpecName('CSS3 Sizing', '#width-height-keywords', 'width')}}{{Spec2('CSS3 Sizing')}}Adds new sizing keywords for width and height.
+ +

瀏覽器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support1.0{{CompatVersionUnknown}}{{CompatGeckoDesktop("1")}}4.07.01.0
fill, fit-content, min-content, max-content{{CompatChrome(46.0)}}{{CompatUnknown}}    
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support1.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1")}}6.06.01.0{{CompatVersionUnknown}}
fill, fit-content, min-content, max-content{{CompatUnknown}}{{CompatChrome(46.0)}}{{CompatUnknown}}    {{CompatChrome(46.0)}}
+
+ +

See also

+ + diff --git a/files/zh-tw/web/css/ime-mode/index.html b/files/zh-tw/web/css/ime-mode/index.html new file mode 100644 index 0000000000..a487af23e0 --- /dev/null +++ b/files/zh-tw/web/css/ime-mode/index.html @@ -0,0 +1,56 @@ +--- +title: ime-mode +slug: Web/CSS/ime-mode +tags: + - CSS +translation_of: Web/CSS/ime-mode +--- +

{{ CSSRef() }} +{{ Fx_minversion_header(3) }} +

+

摘要

+

ime-mode 特性可用以控制某文字輸入欄位的輸入法狀態。 +

+ +

語法

+
ime-mode: <mode>
+
+

特性值

+
auto
不改變輸入法狀態,此為預設值。 +
normal
輸入法設為一般狀態,使用者可在自訂樣式表中蓋過網頁的設定。Internet Explorer 不支援此值。 +
active
輸入法設為啟用狀態。除非使用者刻意關閉、否則此文字欄位將使用輸入法工具。Linux 不支援此值。 +
inactive
輸入法設為關閉狀態,但使用者仍可另行啟用。Linux 不支援此值。 +
disabled
輸入法設為停用狀態,在此欄位中使用者亦無法將其啟用。 +
+

範例

+
<input type="text" name="name" value="initial value" style="ime-mode: disabled">
+
+

此範例在輸入欄位中設定為停用輸入法,在後端資料庫不支援擴充字元集、卻必須讓使用者自行輸入文字時,可以使用。 +

+

備註

+

與 Internet Explorer 不同的地方是,Firefox 實作 ime-mode 時亦允許此特性套用至密碼輸入欄位,但這在理想的使用體驗上有不妥之處、而密碼欄位也應該停用輸入法。若有網站執意將不適切的行為套用至密碼欄位,則使用者可以在自訂 CSS 檔中加上下列設定以強迫調整此功能: +

+
input[type=password] {
+	ime-mode: auto !important;
+}
+
+

{{ Note("一般說來,公開的網站不該自行調整輸入法模式的行為。這個特性主要是給網際應用程式使用的。") }} +

Mac 版的 Gecko 1.9 中,若某欄位設定停用輸入法,則自該欄位移開輸入焦點時並無法自行恢復輸入法狀態,所以若使用 disabled 值,Mac 的使用者可能會碰上麻煩。 +

{{ Note("別僅僅仰賴停用輸入法的招術來避免使用者輸入擴充字元,因為即使輸入法被停用,使用者依然可自他處剪下擴充字元後貼到表單欄位中。") }} +

+

規格出處

+ +

瀏覽器相容性

+

Firefox 3 以後便能同 Internet Explorer 一般支援 ime-mode 特性。 +


+

+
+
+{{ languages( { "en": "en/CSS/ime-mode", "es": "es/CSS/ime-mode", "fr": "fr/CSS/ime-mode", "ja": "ja/CSS/ime-mode" } ) }} diff --git a/files/zh-tw/web/css/index.html b/files/zh-tw/web/css/index.html new file mode 100644 index 0000000000..f894fc2d6a --- /dev/null +++ b/files/zh-tw/web/css/index.html @@ -0,0 +1,100 @@ +--- +title: CSS +slug: Web/CSS +tags: + - CSS + - Cascading Style Sheets + - Design + - Landing + - Layout + - Reference + - Style Sheets + - Styles + - Stylesheets + - 樣式表 + - 版面配置 + - 設計 +translation_of: Web/CSS +--- +

層疊樣式表(Cascading Style Sheets, CSS)是用來描述 HTMLXML(包含 SVGXHTML 等各種 XML 變形)文件外觀的樣式表語言。CSS 會描述文件裡的結構化元素,該如何呈現在螢幕、紙、語音報讀、或其他媒介上。

+ +

CSS開放網路的核心語言之一,具有標準化的 W3C 規範。歷經不同層級的開發,CSS1 目前已被棄用、CSS2.1 是建議規範,而 CSS3 目前被分作數個較小的模組,持續在標準化的路上行進。

+ +
+ + +
+
+

教學

+ +

我們的 CSS 學習專區有很多從頭教起的 CSS 模組。你不需要背景知識。

+ +
+
CSS 介紹
+
此模組讓你理解 CSS 工作原理,包含選擇器與屬性、撰寫 CSS 規則、在 HTML 套用 CSS、如何在 CSS 指定長度、色彩、還有其它單位、階層與繼承、box model 基礎、以及針對 CSS 除錯。
+
文字樣式
+
在這裡我們專注在文字樣式的基礎,包含設定字體、粗細、斜體、行距、字距、陰影以及其他文字屬性。最後以應用自訂字體、樣式化列表、樣式化連結結束。
+
樣式化盒子
+
接著,我們關注樣式化盒子,這是網頁排版中一個基礎的環節。在這個系列中我們會複習盒子模型,然後操作盒子的排版,像是設定留白、邊框、邊距、背景顏色或圖片以及其他特色,還有一些酷炫的功能像是陰影、過濾器。
+
CSS 排版
+
到了這裡,我們已經看完 CSS 的基礎(樣式化文字、樣式化與操作盒子使你的內容可以合適的展示)。現在該來看看如何把你的盒子放在相對於可視區正確的地方。我們已經擁有必要的知識,所以你可以更深入了解 CSS 排版、看不同的顯示設定、傳統排版方法如浮動或定位、新的排版方法如彈性盒子。
+
+
+ +
+

參考

+ + + +

CSS 開發工具

+ + + +

Meta 錯誤

+ +
    +
  • Firefox: {{bug(1323667)}}
  • +
+
+
+
+ +

參見

+ + diff --git a/files/zh-tw/web/css/inheritance/index.html b/files/zh-tw/web/css/inheritance/index.html new file mode 100644 index 0000000000..f67ad62107 --- /dev/null +++ b/files/zh-tw/web/css/inheritance/index.html @@ -0,0 +1,48 @@ +--- +title: 繼承 +slug: Web/CSS/inheritance +translation_of: Web/CSS/inheritance +--- +

摘要

+ +

每個 CSS property definition 都寫道是否這個屬性預設有繼承: ("Inherited: Yes") 或是 預設沒有繼承: ("Inherited: no"). 這個設定將會在沒有位屬性標註值時發生.

+ +

繼承屬性

+ +

When no value for an inherited property has been specified on an element, the element gets the computed value of that property on its parent element. Only the root element of the document gets the initial value given in the property's summary.

+ +

A typical example of an inherited property is the {{ Cssxref("color") }} property. Given the style rules:

+ +
p { color: green }
+ +

HTML:

+ +
<p>This paragraph has <em>emphasized text</em> in it.</p>
+ +

the words "emphasized text" will appear green, since the em element has inherited the value of the {{ Cssxref("color") }} property from the p element. It does not get the initial value of the property (which is the color that is used for the root element when the page specifies no color).

+ +

非繼承屬性

+ +

When no value for an non-inherited property (sometimes called a reset property in Mozilla code) has been specified on an element, the element gets the initial value of that property (as specified in the property's summary).

+ +

A typical example of a non-inherited property is the {{ Cssxref("border") }} property. Given the style rules:

+ +
 p { border: medium solid }
+ +

HTML:

+ +
  <p>This paragraph has <em>emphasized text</em> in it.</p>
+ +

the words "emphasized text" will not have a border (since the initial value of {{ Cssxref("border-style") }} is none).

+ +

+ +

{{ Cssxref("inherit") }} 關鍵字允許作者準確地去標註. 這個在繼承和非繼承屬性都是有效的.

+ +

參見

+ + diff --git a/files/zh-tw/web/css/line-break/index.html b/files/zh-tw/web/css/line-break/index.html new file mode 100644 index 0000000000..f7e073e100 --- /dev/null +++ b/files/zh-tw/web/css/line-break/index.html @@ -0,0 +1,71 @@ +--- +title: line-break +slug: Web/CSS/line-break +translation_of: Web/CSS/line-break +--- +
{{CSSRef}}
+ +

line-break CSS 屬性能夠設定在中文、日文和韓文(CJK) 的文字中,遇到標點或符號時該如何斷行。

+ +
/* Keyword values */
+line-break: auto;
+line-break: loose;
+line-break: normal;
+line-break: strict;
+line-break: anywhere;
+
+/* Global values */
+line-break: inherit;
+line-break: initial;
+line-break: unset;
+
+ +
{{cssinfo}}
+ +

Syntax

+ +

Values

+ +
+
auto
+
以預設的斷行規則斷開文字。
+
loose
+
Break text using the least restrictive line break rule. Typically used for short lines, such as in newspapers.
+
normal
+
Break text using the most common line break rule.
+
strict
+
Break text using the most stringent line break rule.
+
anywhere 
+
+

There is a soft wrap opportunity around every typographic character unit, including around any punctuation character or preserved white spaces, or in the middle of words, disregarding any prohibition against line breaks, even those introduced by characters with the GL, WJ, or ZWJ character class or mandated by the word-break property. The different wrapping opportunities must not be prioritized. Hyphenation is not applied.

+
+
+ +

Formal syntax

+ +
{{csssyntax}}
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Text', '#line-break-property', 'line-break')}}{{Spec2('CSS3 Text')}}Initial definition
+ +

Browser compatibility

+ + + +

{{Compat("css.properties.line-break")}}

diff --git a/files/zh-tw/web/css/media_queries/index.html b/files/zh-tw/web/css/media_queries/index.html new file mode 100644 index 0000000000..41339e07bc --- /dev/null +++ b/files/zh-tw/web/css/media_queries/index.html @@ -0,0 +1,112 @@ +--- +title: Media queries +slug: Web/CSS/Media_Queries +translation_of: Web/CSS/Media_Queries +--- +
{{CSSRef}}
+ +

Media Queries is a module of CSS that defines expressions allowing to tailor presentations to a specific range of output devices without changing the content itself.

+ +

參考

+ +

At-rules

+ +
+ +
+ +

指南

+ +
+
Using media queries
+
Presents what media queries are doing and explains the possible expressions.
+
Testing media queries
+
Explains how to test a media query programmatically, from JavaScript.
+
+ +

規範

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

瀏覽器相容性

+ +

{{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/zh-tw/web/css/media_queries/testing_media_queries/index.html b/files/zh-tw/web/css/media_queries/testing_media_queries/index.html new file mode 100644 index 0000000000..5c61c6483f --- /dev/null +++ b/files/zh-tw/web/css/media_queries/testing_media_queries/index.html @@ -0,0 +1,118 @@ +--- +title: 測試 media queries +slug: Web/CSS/Media_Queries/Testing_media_queries +translation_of: Web/CSS/Media_Queries/Testing_media_queries +--- +

{{SeeCompatTable}}

+ +

DOM 提供了一個用程式去測試 media query 的方法:那就是透過 {{domxref("MediaQueryList") }} 物件;透過 {{domxref("MediaQueryList") }} 物件上的屬性和方法,我們可以得知、觀察目前 media query 的狀態。

+ +

創建 media query list 物件

+ +

透過傳入目標 medai query 到 {{domxref("window.matchMedia") }} 方法,我們將可以取得相對應的 MediaQueryList 物件。

+ +

以下範例將取得偵測螢幕方向的 MediaQueryList 物件:

+ +
var mql = window.matchMedia("(orientation: portrait)");
+
+ +

檢查 media query 結果

+ +

讀取 MediaQueryList 物件 的 matches 屬性就可以得知測試結果:

+ +
if (mql.matches) {
+  /* The device is currently in portrait orientation */
+} else {
+  /* The device is currently in landscape orientation */
+}
+
+ +

接收測試結果通知

+ +

當我們想要動態依據 media query 測試狀況執行對應處理,除了持續定期偵測外,還有一個更有效率的途徑:那就是註冊 media query 的事件處理器 (listener)。只要呼叫 MediaQueryList 物件上 addListener 方法,傳入符合 {{domxref("MediaQueryListListener") }} 介面的 listener 便完成事件註冊

+ +
var mql = window.matchMedia("(orientation: portrait)");
+mql.addListener(handleOrientationChange);
+handleOrientationChange(mql);
+
+ +

上面我們替螢幕方向 media query 註冊了一個 listener。請注意,在第一次註冊後,listener 會立刻被呼叫一次,這是為了初始化準備,因為我們可能預設 UI 是針對 'portait' 模式,但目前卻是 'landscape' 模式,所以這個第一次呼叫將給予我們作初始化調整的空間。

+ +

下面handleOrientationChange() 方法便是我們針對螢幕方向變化的 listener

+ +
function handleOrientationChange(mql) {
+  if (mql.matches) {
+    /* The device is currently in portrait orientation */
+  } else {
+    /* The device is currently in landscape orientation */
+  }
+}
+
+ +

停止接收測試結果通知

+ +

當我們不需要接受通知時,只需要呼叫 removeListener 方法,然後傳入欲移除的 listener 即可:

+ +
mql.removeListener(handleOrientationChange);
+
+ +

瀏覽器相容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support9{{CompatGeckoDesktop("6.0") }}1012.15.1
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support3.0{{CompatUnknown}}1012.15
+
+ +

 

+ +

延伸閱讀

+ + diff --git a/files/zh-tw/web/css/object-fit/index.html b/files/zh-tw/web/css/object-fit/index.html new file mode 100644 index 0000000000..e6b73dc0b9 --- /dev/null +++ b/files/zh-tw/web/css/object-fit/index.html @@ -0,0 +1,217 @@ +--- +title: object-fit +slug: Web/CSS/object-fit +translation_of: Web/CSS/object-fit +--- +
{{CSSRef}}
+ +

Summary

+ +

The object-fit CSS property specifies how the contents of a replaced element should be fitted to the box established by its used height and width.

+ +

物件契合(object-fit)CSS屬性能指定置換元素(replaced element)的內容要如何契合、安裝到其使用的高度和寬度已確定的框。

+ +

 

+ +

{{cssinfo}}

+ +

Syntax

+ +
/* Keyword values */
+object-fit: fill;
+object-fit: contain;
+object-fit: cover;
+object-fit: none;
+object-fit: scale-down;
+
+/* Global values */
+object-fit: inherit;
+object-fit: initial;
+object-fit: unset;
+
+ +

Values

+ +
+
fill
+
The replaced content is sized to fill the element’s content box: the object’s concrete object size is the element’s used width and height.
+
contain
+
The replaced content is sized to maintain its aspect ratio while fitting within the element’s content box: its concrete object size is resolved as a contain constraint against the element’s used width and height.
+
cover
+
The replaced content is sized to maintain its aspect ratio while filling the element’s entire content box: its concrete object size is resolved as a cover constraint against the element’s used width and height.
+
none
+
The replaced content is not resized to fit inside the element’s content box: the object’s concrete object size is determined using the default sizing algorithm with no specified size, and a default object size equal to the replaced element’s used width and height.
+
scale-down
+
The content is sized as if none or contain were specified, whichever would result in a smaller concrete object size.
+
+ +

Formal syntax

+ +
{{csssyntax}}
+ +

Example

+ +

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

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

+ + diff --git a/files/zh-tw/web/css/pseudo-classes/index.html b/files/zh-tw/web/css/pseudo-classes/index.html new file mode 100644 index 0000000000..1a222e59cd --- /dev/null +++ b/files/zh-tw/web/css/pseudo-classes/index.html @@ -0,0 +1,129 @@ +--- +title: 虛擬類別 +slug: Web/CSS/Pseudo-classes +translation_of: Web/CSS/Pseudo-classes +--- +

{{ CSSRef() }}

+ +

CSS 虛擬類別(pseudo-class)的元素,在特殊狀態下被選取的話,會作為關鍵字被加到選擇器裡面。例如 {{ Cssxref(":hover") }} 會讓用戶的滑鼠停在某個元素的時候,套用指定選擇器的樣式。

+ +

虛擬類別與 {{ Cssxref("pseudo-elements") }} 能讓你不只能給文件樹(document tree)本身的相關內容套用樣式,還能給諸如瀏覽歷史({{ cssxref(":visited") }})、內容的狀態({{ cssxref(":checked") }})、還有滑鼠的位置(像 {{ cssxref(":hover") }} 就能讓偵測滑鼠是否在元件上)之類的外部相關因素套用樣式。

+ +

語法

+ +
selector:pseudo-class {
+  property: value;
+}
+
+ +

基本虛擬類別的目錄

+ +
+ +
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
規範狀態註解
{{ SpecName('Fullscreen') }}{{ Spec2('Fullscreen') }}定義 :fullscreen
{{ SpecName('HTML WHATWG') }}{{ Spec2('HTML WHATWG') }}在 {{ SpecName('HTML5 W3C') }} 並沒有改變。
{{SpecName('CSS4 Selectors')}}{{Spec2('CSS4 Selectors')}}定義 :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(), and :matches().
+ 沒有針對 {{SpecName('CSS3 Selectors')}} 與 {{SpecName('HTML5 W3C')}} 虛擬類別的重大更改(though semantic meaning not taken over)
{{ SpecName('HTML5 W3C') }}{{ Spec2('HTML5 W3C') }}定義以下 HTML context 的語意含義: :link, :visited, :active, :enabled, :disabled, :checked, and :indeterminate.
+ 定義 :default, :valid, :invalid, :in-range, :out-of-range, :required, :optional, :read-only, :read-write, and :dir().
{{ SpecName('CSS3 Basic UI') }}{{ Spec2('CSS3 Basic UI') }}定義 :default, :valid, :invalid, :in-range, :out-of-range, :required, :optional, :read-only, :read-write,但沒有語意含義的定義。
{{SpecName('CSS3 Selectors')}}{{Spec2('CSS3 Selectors')}}定義 :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, :not().
+ 定義 :enabled, :disabled, :checked, :indeterminate 的語法,但沒有語意含義的定義。
+ 在 {{SpecName('CSS2.1')}} 並沒有明顯改變。
{{SpecName('CSS2.1')}}{{Spec2('CSS2.1')}}定義 :lang(), :first-child, :hover, :focus.
+ 在 {{SpecName('CSS1')}} 並沒有明顯改變。
{{SpecName('CSS1')}}{{Spec2('CSS1')}}定義 :link, :visited, :active,但沒有語意含義的定義。
+ +

參閱

+ + diff --git a/files/zh-tw/web/css/radial-gradient()/index.html b/files/zh-tw/web/css/radial-gradient()/index.html new file mode 100644 index 0000000000..bd054abab3 --- /dev/null +++ b/files/zh-tw/web/css/radial-gradient()/index.html @@ -0,0 +1,183 @@ +--- +title: radial-gradient() +slug: Web/CSS/radial-gradient() +translation_of: Web/CSS/radial-gradient() +--- +
{{CSSRef}}
+ +

CSS radial-gradient() 函數創建了一個圖片,其由一個從原點輻射開的在兩個或者多個顏色之前的漸變組成。這個方法得到的是一個CSS<gradient>數據類型的物件,其是 <image> 的一種。

+ +
{{EmbedInteractiveExample("pages/css/function-radial-gradient.html")}}
+ + + +

As with any gradient, a radial gradient has no intrinsic dimensions; i.e., it has no natural or preferred size, nor a preferred ratio. Its concrete size will match the size of the element it applies to.

+ +

To create a radial gradient that repeats so as to fill its container, use the {{cssxref("repeating-radial-gradient")}} function instead.

+ +

Because <gradient>s belong to the <image> data type, they can only be used where <image>s can be used. For this reason, radial-gradient() won't work on {{Cssxref("background-color")}} and other properties that use the {{cssxref("<color>")}} data type.

+ +

Composition of a radial gradient

+ +

向量漸變(Radial gradients)由其中心點、邊緣形狀輪廓及位置、色值結束點(color stops)定義而成。

+ +

To create a smooth gradient, the radial-gradient() function draws a series of concentric shapes radiating out from the center to the ending shape (and potentially beyond). The ending shape may be either a circle or an ellipse.

+ +

Color-stop points are positioned on a virtual gradient ray that extends horizontally from the center towards the right. Percentage-based color-stop positions are relative to the intersection between the ending shape and this gradient ray, which represents 100%. Each shape is a single color determined by the color on the gradient ray it intersects.

+ +

Syntax

+ +
/* A gradient at the center of its container,
+   starting red, changing to blue, and finishing green */
+radial-gradient(circle at center, red 0, blue, green 100%)
+ +

Values

+ +
+
{{cssxref("<position>")}}
+
The position of the gradient, interpreted in the same way as {{cssxref("background-position")}} or {{cssxref("transform-origin")}}. If unspecified, it defaults to center.
+
<shape>
+
The gradient's shape. The value can be circle (meaning that the gradient's shape is a circle with constant radius) or ellipse (meaning that the shape is an axis-aligned ellipse). If unspecified, it defaults to ellipse.
+
<extent-keyword>
+
A keyword describing how big the ending shape must be. The possible values are: + + + + + + + + + + + + + + + + + + + + + + + + + +
KeywordDescription
closest-sideThe gradient's ending shape meets the side of the box closest to its center (for circles) or meets both the vertical and horizontal sides closest to the center (for ellipses).
closest-cornerThe gradient's ending shape is sized so that it exactly meets the closest corner of the box from its center.
farthest-sideSimilar to closest-side, except the ending shape is sized to meet the side of the box farthest from its center (or vertical and horizontal sides).
farthest-cornerThe default value, the gradient's ending shape is sized so that it exactly meets the farthest corner of the box from its center.
+ +
+

Note: Early implementations of this function included other keywords (cover and contain) as synonyms of the standard farthest-corner and closest-side, respectively. Use the standard keywords only, as some implementations have already dropped those older variants.

+
+
+
<linear-color-stop>
+
A color-stop's {{cssxref("<color>")}} value, followed by an one or two optional stop positions (either a {{cssxref("<percentage>")}} or a {{cssxref("<length>")}} along the gradient's axis). A percentage of 0%, or a length of 0, represents the center of the gradient; the value 100% represents the intersection of the ending shape with the virtual gradient ray. Percentage values in between are linearly positioned on the gradient ray. Including two stop positions is equivalent to declaring two color stops with the same color at the two positions.
+
<color-hint>
+
Th color-hint is an interpolation hint defining how the gradient progresses between adjacent color stops. The length defines at which point between two color stops the gradient color should reach the midpoint of the color transition. If omitted, the midpoint of the color transition is the midpoint between two color stops.
+
+ +

Formal syntax

+ +
radial-gradient(
+  [ [ circle || <length> ]                         [ at <position> ]? , |
+    [ ellipse || [ <length> | <percentage> ]{2} ]  [ at <position> ]? , |
+    [ [ circle | ellipse ] || <extent-keyword> ] [at <position> ]? , |
+    at <position> ,
+  ]?
+  <color-stop-list> [ , <color-stop-list> ]+
+)
+where <extent-keyword> = closest-corner | closest-side | farthest-corner | farthest-side
+   and <color-stop-list> = [ <linear-color-stop> [, <color-hint>? ]? ]#, <linear-color-stop>
+   and <linear-color-stop> = <color> [ <color-stop-length> ]?
+   and <color-stop-length> = [ <percentage> | <length> ]{1,2}
+   and <color-hint> = [ <percentage> | <length> ]
+
+ +
+

Note that negative <length>'s are not allowed, however browsers had implemented negative lengths which are now being removed. See the Firefox site compat note.

+
+ +

Examples

+ +

Simple gradient

+ + + +
.radial-gradient {
+  background-image: radial-gradient(cyan 0%, transparent 20%, salmon 40%);
+} 
+ +

{{EmbedLiveSample('Simple_gradient', 120, 120)}}

+ +

Non-centered gradient

+ + + +
.radial-gradient {
+  background-image: radial-gradient(farthest-corner at 40px 40px,
+      #f35 0%, #43e 100%);
+}
+ +

{{EmbedLiveSample('Non-centered_gradient', 240, 120)}}

+ +
+

Note: Please see Using CSS gradients for more examples.

+
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Images', '#radial-gradients', 'radial-gradients()')}}{{Spec2('CSS3 Images')}}Initial definition.
+ +

Browser compatibility

+ + + +
{{Compat("css.types.image.gradient.radial-gradient")}}
+ +

Quantum CSS notes

+ +

Gecko used to have a long-standing bug whereby radial gradients like radial-gradient(circle gold,red) would work, even though they shouldn't because of the missing comma between circle and gold. Also, {{cssxref("calc")}} expressions were rejected — causing the value to be invalid — when used as the radius component of a radial-gradient() function ({{bug(1376019)}}). Firefox's new parallel CSS engine (also known as Quantum CSS or Stylo, released in Firefox 57) fixed these bugs.

+ +

See also

+ + diff --git a/files/zh-tw/web/css/reference/index.html b/files/zh-tw/web/css/reference/index.html new file mode 100644 index 0000000000..2b2dfc4455 --- /dev/null +++ b/files/zh-tw/web/css/reference/index.html @@ -0,0 +1,211 @@ +--- +title: CSS 參考文件 +slug: Web/CSS/Reference +translation_of: Web/CSS/Reference +--- +

Use this CSS reference to browse an alphabetical index of all the standard CSS properties, pseudo-classes, pseudo-elements, data types, and at-rules. You can also browse a list of all the CSS selectors organized by type and a list of key CSS concepts. Also included is a brief DOM-CSS / CSSOM reference.

+ +

基本語法規則

+ +

Style rule syntax

+ +
selectorlist {
+  property: value;
+  [more property:value; pairs]
+}
+
+... where selectorlist is: selector[:pseudo-class] [::pseudo-element] [, more selectorlists]
+
+See selector, pseudo-class, pseudo-element lists below.
+
+ +

Style rule examples

+ +
strong {
+  color: red;
+}
+
+div.menu-bar li:hover > ul {
+  display: block;
+}
+
+ +

For a beginner-level introduction to the syntax of CSS selectors, please see this tutorial. Be aware that any CSS syntax error in a rule definition invalidates the entire rule. Invalid rules are ignored by the browser. Note that CSS rule definitions are entirely (ASCII) text-based, whereas DOM-CSS / CSSOM (the rule management system) is object-based.

+ +

At-rule syntax

+ +

As the structure of at-rules varies widely, please see At-rule to find the syntax of the specific one you want.

+ +

Keyword index

+ +
+

Note: The property names in this index do not include the JavaScript names where they differ from the CSS standard names.

+
+ +
{{CSS_Ref}}
+ +

Selectors

+ +

Basic selectors

+ + + +

Combinators

+ + + +

Pseudo-classes

+ +
+ +
+ +

Pseudo-elements

+ +
+ +
+ +
+

See also: A complete list of selectors in the Selectors Level 3 specification.

+
+ +

Concepts

+ +

Syntax and semantics

+ + + +

Values

+ + + +

Layout

+ + + +

DOM-CSS / CSSOM

+ +

Major object types

+ + + +

Important methods

+ + + +

See also

+ + diff --git a/files/zh-tw/web/css/replaced_element/index.html b/files/zh-tw/web/css/replaced_element/index.html new file mode 100644 index 0000000000..10e6def514 --- /dev/null +++ b/files/zh-tw/web/css/replaced_element/index.html @@ -0,0 +1,20 @@ +--- +title: 置換元素 (Replaced element) +slug: Web/CSS/Replaced_element +translation_of: Web/CSS/Replaced_element +--- +
{{CSSRef()}}
+ +

摘要

+ +

CSS 中所謂的「置換元素 (Replaced element)」,即是該元素所呈現的內容不在 CSS 的控制範圍之內。這類外部物件所呈現的內容均獨立於 CSS 之外。常見的置換元素包含 {{HTMLElement("img")}}、{{HTMLElement("object")}}、{{HTMLElement("video")}},或如 {{HTMLElement("textarea")}} 與 {{HTMLElement("input")}} 的表單元素。某些元素 (像是 {{HTMLElement("audio")}} 或 {{HTMLElement("canvas")}}) 只有在特殊情況下才是置替換元素。若是透過 CSS {{cssxref("content")}} 屬性所插入的物件,則稱為「不具名置換元素 (Anonymous replaced elements)」。

+ +

在某些情況下,CSS 會特別處理置換元素,如計算邊距空白 (Margin) 與某些 auto 的值。

+ +

另需注意的是,某些置換元素本身就具備固定尺寸 (Intrinsic dimension) 或已定義的基準線 (Baseline),並可由 CSS 的某些屬性 (如 {{cssxref("vertical-align")}}) 所利用。

+ +

另可參閱

+ + diff --git a/files/zh-tw/web/css/ruby-position/index.html b/files/zh-tw/web/css/ruby-position/index.html new file mode 100644 index 0000000000..6caff70d64 --- /dev/null +++ b/files/zh-tw/web/css/ruby-position/index.html @@ -0,0 +1,112 @@ +--- +title: ruby-position +slug: Web/CSS/ruby-position +translation_of: Web/CSS/ruby-position +--- +
{{CSSRef}}{{SeeCompatTable}}
+ +

CSS 的 ruby-position 屬性定義了 ruby 元素與該基礎元素(base element)相關聯的位置。它能在元素上方(over)、下方(under)、兩個字符之間、抑或右方(inter-character)。

+ +
/* 關鍵字值 */
+ruby-position: over;
+ruby-position: under;
+ruby-position: inter-character;
+
+/* 全域值 */
+ruby-position: inherit;
+ruby-position: initial;
+ruby-position: unset;
+
+ +

{{cssinfo}}

+ +

語法

+ +

屬性值

+ +
+
over
+
Over example如果文件以橫式排列,該關鍵字會指引旁註標記(ruby)出現在主文的上方。如果文件以直式排列,則會出現在主文的右方。
+
under
+
Under example如果文件以橫式排列,該關鍵字會指引旁註標記出現在在主文的下方。如果文件以直式排列,則會出現在主文的左方。
+
inter-character
+
該關鍵字會指引旁註標記出現在在主文的兩個字符的中間。
+
+ +

正式語法

+ +
{{csssyntax}}
+ +

示例

+ +

HTML 會因為 ruby-position 的值不同,而作出不同的渲染:

+ +
<ruby>
+  <rb>超電磁砲</rb>
+  <rp>(</rp><rt>レールガン</rt><rp>)</rp>
+</ruby>
+
+ +

旁註標記定位到主文上方

+ + + +
ruby {
+    ruby-position:over;
+}
+ +

它會給出如下結果:

+ +

{{EmbedLiveSample("旁註標記定位到主文上方", 100, 40)}}

+ +

旁註標記定位到主文下方

+ + + +
ruby {
+    ruby-position:under;
+}
+ +

它會給出如下結果:

+ +

{{EmbedLiveSample("旁註標記定位到主文下方", 100, 40)}}

+ +

規範

+ + + + + + + + + + + + + + + + +
規範狀態註解
{{ SpecName('CSS3 Ruby', '#rubypos', 'ruby-position') }}{{ Spec2('CSS3 Ruby') }}初始定義
+ +

瀏覽器相容性

+ + + +

{{Compat("css.properties.ruby-position")}}

+ +

參見

+ + diff --git a/files/zh-tw/web/css/shorthand_properties/index.html b/files/zh-tw/web/css/shorthand_properties/index.html new file mode 100644 index 0000000000..2e880da57e --- /dev/null +++ b/files/zh-tw/web/css/shorthand_properties/index.html @@ -0,0 +1,138 @@ +--- +title: 特性簡寫 +slug: Web/CSS/Shorthand_properties +translation_of: Web/CSS/Shorthand_properties +--- +

定義

+ +

特性簡寫,是一種可以同時設定許多其他 CSS 屬性值的 CSS 屬性。 使用特性簡寫,網頁開發者可以寫出更簡潔、且通常更具可讀性的樣式表,省時又省力。

+ +

CSS 規範中定義,特性簡寫用來組合作用於相同主題的常見性質。舉例來說,CSS {{cssxref("background")}} 這個性質是個特性簡寫,可同時定義 {{cssxref("background-color")}}, {{cssxref("background-image")}}, {{cssxref("background-repeat")}}, 和 {{cssxref("background-position")}} 等屬性。同樣的,最常用的字體相關屬性,可以使用 {{cssxref("font")}} 來定義;圍繞在方塊周圍的邊界,則可簡單地以 {{cssxref("margin")}} 簡寫來定義。

+ +

需謹慎之處

+ +

即便特性簡寫非常易於使用,仍有幾個需要銘記在心的情況:

+ +
    +
  1. 未指明的值會被設為預設值。這聽起來真的很怪,但他的確會覆寫先前的設定值。比如: + +
    background-color: red;
    +background: url(images/bg.gif) no-repeat top right;
    + 不會將背景設為紅色,而是使用 {{cssxref("background-color")}} 的預設值 transparent,由於較後面的規則為優先。
  2. +
  3. 只有獨立的屬性可以被繼承。就如同遺失的值會被預設值取代一樣,不可能讓缺漏的值再去繼承個別屬性。關鍵字 inherit 可以用於屬性,但只能整體繼承,而不能用於個別值上。意思是,如果要繼承某個特定的值,就必須使用完整的語句,搭配 inherit 關鍵字
  4. +
  5. 簡寫屬性試著不強迫使用特定順序,在那些屬性有許多不同類型的值的狀況下的確很方便。但是在許多屬性具有類似值時就沒這麼簡單了,此時會以以下規則處理: +
      +
    1. 關於區塊的簡寫性質,諸如 {{cssxref("border-style")}}, {{cssxref("margin")}} 或 {{cssxref("padding")}},就會使用連貫的1~4個值來定義下列這些邊: + + + + + + + + + + + + + + + + + + + +
      border1.png單值語法:border-width: 1em — 這個唯一的值定義所有四邊
      border2.png雙值語法:border-width: 1em 2em — 第一個值代表垂直部分,也就是上和下邊;第二個值則是指水平部分,也就是左右邊。
      border3.png三值語法:border-width: 1em 2em 3em — 第一個值代表上邊,第二個值代表兩旁的邊,而第三個值代表下邊。
      border4.png +

      四值語法:border-width: 1em 2em 3em 4em — 這四個值分別代表上、右、下、左邊,順時針的方向由上開始排列(可以以 trouble 來記憶,即英文首文字的縮寫 TRBL)

      +
      +
    2. +
    3. 與之相似地,關於區塊角落的屬性,像是 {{cssxref("border-radius")}},也會使用連貫的1~4個值來代表四個角落: + + + + + + + + + + + + + + + + + + + +
      corner1.png單值語法:border-radius: 1em — 這唯一的值代表了所有角落。
      corner2.png雙值語法:border-radius: 1em 2em — 第一個值代表左上和右下,第二個值則是右上及左下角。
      corner3.png三值語法:border-radius: 1em 2em 3em — 第一個值代表左上,第二個值代表右上及左下,第三個值則是右下的角落。
      corner4.png +

      四值語法:border-radius: 1em 2em 3em 4em — 這四個值分別代表左上、右上、右下、左下,由左上開始的順時針排序。

      +
      +
    4. +
    +
  6. +
+ +

背景屬性

+ +

背景會有下列這些屬性:

+ +
background-color: #000;
+background-image: url(images/bg.gif);
+background-repeat: no-repeat;
+background-position: top right;
+ +

可以簡寫為一句宣告:

+ +
background: #000 url(images/bg.gif) no-repeat top right;
+ +

(寫成簡化屬性的效果,完全等同於上方未簡化的屬性,外加 background-attachment: scroll 及其他 CSS3 中額外增加的屬性。)

+ +

字體屬性

+ +

下列的宣告:

+ +
font-style: italic;
+font-weight: bold;
+font-size: .8em;
+line-height: 1.2;
+font-family: Arial, sans-serif;
+ +

可以簡寫成這樣:

+ +
font: italic bold .8em/1.2 Arial, sans-serif;
+ +

簡化定義的效果完全等同於未簡化前的屬性效果,加上 font-variant: normalfont-size-adjust: none (CSS2.0 / CSS3) 及 font-stretch: normal (CSS3) 等屬性。

+ +

邊框屬性

+ +

邊框的寬度、顏色、樣式可以簡寫成一句宣告。舉例來說:

+ +
border-width: 1px;
+border-style: solid;
+border-color: #000;
+ +

可以寫成:

+ +
border: 1px solid #000;
+ +

邊界與內距屬性

+ +

margin 和 padding 的簡化版本大致相同。下列的 CSS 宣告:

+ +
margin-top: 10px;
+margin-right: 5px;
+margin-bottom: 10px;
+margin-left: 5px;
+ +

等同於下面的宣告(注意值的排序是順時鐘的順序:上,右,下,左 (TRBL,可以「trouble」這個單字的諧音來記憶)

+ +
margin: 10px 5px 10px 5px;
+ +

相關連結

+ + diff --git a/files/zh-tw/web/css/syntax/index.html b/files/zh-tw/web/css/syntax/index.html new file mode 100644 index 0000000000..c777095cb0 --- /dev/null +++ b/files/zh-tw/web/css/syntax/index.html @@ -0,0 +1,74 @@ +--- +title: 語法 +slug: Web/CSS/Syntax +translation_of: Web/CSS/Syntax +--- +
{{cssref}}
+ +

串接式樣式表 (CSS) 語言的基礎目標是是讓瀏覽器引擎用特定的功能將元素寫在頁面上,像是顏色、位置與裝飾。CSS 語法反映出了目的,而它的基本組成為:

+ + + +

CSS 宣告

+ +

設定特定參數值給 CSS 屬性是 CSS 語言的核心功能。一對屬性與參數叫做宣告,而為了適當的排版與套用樣式,任何 CSS 引擎會演算每個頁面上的元素該套用哪個宣告。

+ +

在 CSS 中屬性與參數都預設為不區分大小寫。它們由冒號區隔,':' (U+003A COLON),而在屬性與參數前、中間與後面並不需要有空白,空白會被忽略。

+ +

css syntax - declaration.png

+ +

在 CSS 中有超過100種不同的屬性與接近無限個不同的參數。並非所有的屬性與參數組都是被准許的,且每個屬性定義了哪些是有效的參數。當一個參數對屬性無效的時候,宣告會被認為是無效的且會完全被 CSS 引擎忽略。

+ +

CSS 宣告區塊

+ +

Declarations are grouped in blocks, that is in a structure delimited by an opening brace, '{' (U+007B LEFT CURLY BRACKET), and a closing one, '}' (U+007D RIGHT CURLY BRACKET). Blocks sometimes can be nested, so opening and closing braces must be matched.

+ +

css syntax - block.png

+ +

Such blocks are naturally called declaration blocks and declarations inside them are separated by a semi-colon, ';' (U+003B SEMICOLON). A declaration block may be empty, that is containing null declaration. White spaces around declarations are ignored. The last declaration of a block doesn't need to be terminated by a semi-colon, though it is often considered good style to do it as it prevents forgetting to add it when extending the block with another declaration.

+ +

css syntax - declarations block.png

+ +
The content of a CSS declaration block, that is a list of semi-colon-separated declarations, without the initial and closing braces, can be put inside an HTML {{htmlattrxref("style")}} attribute.
+ +

CSS rulesets

+ +

If style sheets could only apply a declaration to each element of a Web page, they would be pretty useless. The real goal is to apply different declarations to different parts of the document.

+ +

CSS allows this by associating conditions with declarations blocks. Each (valid) declaration block is preceded by one or more comma-separated selectors which are conditions selecting some elements of the page. The pair selector group-declarations block is called a ruleset, or often simply a rule.

+ +

css syntax - ruleset.png

+ +

As an element of the page may be matched by several selectors, and therefore by several rules potentially containing a given property several times, with different values, the CSS standard defines which one has precedence over the other and must be applied: this is called the cascade algorithm.

+ +
It is important to note that even if a ruleset characterized by a group of selectors is a kind of shorthand replacing rulesets with a single selector each, this doesn't apply to the validity of the ruleset itself.
+
+This leads to an important consequence: if one single basic selector is invalid, like when using an unknown pseudo-element or pseudo-class, the whole selector is invalid and therefore the entire rule is ignored (as invalid too).
+ +

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 two kinds of statements:

+ + + +

Any statement which isn't a ruleset 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 the browser runs 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 conditional group rules. That was very restrictive and this restriction was lifted in CSS Conditionals Level 3. Now, though still experimental and not supported by every browser, conditional group rules can contain a wider range of content: rulesets but also some, but not all, at-rules.

+ +

See also

+ + diff --git a/files/zh-tw/web/css/transform-function/index.html b/files/zh-tw/web/css/transform-function/index.html new file mode 100644 index 0000000000..73b08839ed --- /dev/null +++ b/files/zh-tw/web/css/transform-function/index.html @@ -0,0 +1,894 @@ +--- +title: transform-function +slug: Web/CSS/transform-function +translation_of: Web/CSS/transform-function +--- +

{{ CSSRef("CSS Transforms") }}The <transform-function> CSS data type denotes a function applied to an element's representation in order to modify it. Usually such transform may be expressed by matrices and the resulting images can be determined using matrix multiplication on each point.

+ +

Coordinates for 2D graphics

+ +

There are several coordinate models used when describing transformation. The most common are the Cartesian coordinate system and homogeneous coordinates.

+ +

笛卡兒坐標系

+ +

+ +

In Cartesian coordinates each point of the Euclidian space is described using two values, the abscissa and the ordinate. The origin, the (0, 0) is the top-left corner of the element. Unlike the usual geometric convention, and like most cases in computer graphics, the y-axis goes to the bottom. Each point is mathematically described using the vector notation (x,y).

+ +

Each linear function is described using a 2x2 matrix like:

+ +
+

ac bd

+
+ +

Applying the transformation consists in doing, for each point, the matrix multiplication between both:

+ +
.
+ +

It is possible to apply several transformations in a row:

+ +
.
+ +

With this notation, it is possible to describe, and therefore composite, most usual transformations: rotations, scaling, or skewing. In fact all transformations that are linear functions can be described. One major transformation is not linear and therefore must be special-cased when using this notation: translation. The translation vector (tx, ty) must be expressed separately, as two more parameters.

+ +

Möbius' homogeneous coordinates in projective geometry leading to 3x3 transformation matrices, though more complex and unusual for non-specialists, doesn't suffer from the translation limitation as these can be expressed as linear functions in this algebra, removing the need for special cases.

+ +

Coordinates for 3D graphics

+ +

Functions defining transformations

+ +

matrix()

+ +

The matrix() CSS function specifies a homogeneous 2D transformation matrix comprised of the specified six values. The constant values of such matrices are implied and not passed as parameters; the other parameters are described in the column-major order.

+ +

matrix(a, b, c, d, tx, ty) is a shorthand for matrix3d(a, b, 0, 0, c, d, 0, 0, 0, 0, 1, 0, tx, ty, 0, 1).

+ +
Note: Until Firefox 16, Gecko accepted a {{cssxref("<length>")}} value for tx and ty.
+ +

表達式

+ +
matrix(a, b, c, d, tx, ty)
+
+ +

+ +
+
a b c d
+
Are {{cssxref("<number>")}} describing the linear transformation.
+
tx ty
+
Are {{cssxref("<number>")}} describing the translation to apply.
+
+ + + + + + + + + + + + + + + + + + + + + +
Cartesian coordinates on ℝ2Homogeneous coordinates on ℝℙ2Cartesian coordinates on ℝ3Homogeneous coordinates on ℝℙ3
ac bd actybdtx001 actybdtx001 ac0txbd0ty00100001
[a b c d tx ty]
+ +

matrix3d()

+ +

The matrix3d() CSS function describes a 3D transform as a 4x4 homogeneous matrix. The 16 parameters are described in the column-major order.

+ +
Note: Until Firefox 16, Gecko accepted a {{cssxref("<length>")}} value for a4, b4 and c4.
+ +

表達式

+ +
matrix3d(a1, b1, c1, d1, a2, b2, c2, d2, a3, b3, c3, d3, a4, b4, c4, d4)
+ +

+ +
+
a1 b1 c1 d1 a2 b2 c2 d2 a3 b3 c3 d3 d4
+
Are {{cssxref("<number>")}} describing the linear transformation.
+
a4 b4 c4
+
Are {{cssxref("<number>")}} describing the translation to apply.
+
+ + + + + + + + + + + + + + + + + +
Cartesian coordinates on ℝ2Homogeneous coordinates on ℝℙ2Cartesian coordinates on ℝ3Homogeneous coordinates on ℝℙ3
This transform applies to the 3D space and cannot be represented on the plan.Cartesian-coordinate matrix doesn't allow to represent a generic 3d affine transforms as translations are not linear transforms.a1a2a3a4b1b2b3b4c1c2c3c4d1d2d3d4
+ +

perspective()

+ +

The perspective() CSS function defines the distance between the z=0 plane and the user in order to give to the 3D-positioned element some perspective. Each 3D element with z>0 becomes larger; each 3D-element with z<0 becomes smaller. The strength of the effect is determined by the value of this property.

+ +

表達式

+ +
perspective(l)
+
+ +

+ +
+
l
+
Is a {{cssxref("<length>")}} giving the distance from the user to the z=0 plane. It is used to apply a perspective transform to the element. If it is 0 or a negative value, no perspective transform is applied.
+
+ + + + + + + + + + + + + + + + + +
Cartesian coordinates on ℝ2Homogeneous coordinates on ℝℙ2Cartesian coordinates on ℝ3Homogeneous coordinates on ℝℙ3
+

This transform applies to the 3D space and cannot be represented on the plan.

+
A perspective is not a linear transform in ℝ3 and cannot be represented using a matrix in the Cartesian coordinates system. 100001000010001/d1
+ +

rotate()

+ +

The rotate() CSS function defines a transformation that moves the element around a fixed point (as specified by the {{ Cssxref("transform-origin") }} property) without deforming it. The amount of movement is defined by the specified angle; if positive, the movement will be clockwise, if negative, it will be counter-clockwise. A rotation by 180° is called point reflection.

+ +

表達式

+ +
rotate(a)
+
+ +

+ +
+
a
+
Is an {{ cssxref("<angle>") }} representing the angle of the rotation. A positive angle denotes a clockwise rotation, a negative angle a counter-clockwise one.
+
+ + + + + + + + + + + + + + + + + + + + + +
Cartesian coordinates on ℝ2Homogeneous coordinates on ℝℙ2Cartesian coordinates on ℝ3Homogeneous coordinates on ℝℙ3
cos(a)-sin(a) sin(a)cos(a) cos(a)-sin(a)0sin(a)cos(a)0001 cos(a)-sin(a)0sin(a)cos(a)0001 cos(a)-sin(a)00sin(a)cos(a)0000100001
[cos(a) sin(a) -sin(a) cos(a) 0 0]
+ +

rotate3d()

+ +

The rotate3d()CSS function defines a transformation that moves the element around a fixed axis without deforming it. The amount of movement is defined by the specified angle; if positive, the movement will be clockwise, if negative, it will be counter-clockwise.

+ +

In the 3D space, rotations have three degrees of liberty, describing an axis of rotation. The axis of rotation is defined by an [x, y, z] vector and pass by the origin (as defined by the {{ cssxref("transform-origin") }} CSS property. If the vector is not normalized, that is the sum of the square of its three coordinates is not 1, it will be normalized internally. A non-normalizable vector, like the null vector, [0, 0, 0], will cause the rotation not to be applied, without invaliding the whole CSS property.

+ +
In opposition to rotations in the plane, the composition of 3D rotations is usually not commutative; it means that the order in which the rotations are applied is crucial.
+ +

表達式

+ +
rotate3d(x, y, z, a)
+
+ +

+ +
+
x
+
Is a {{cssxref("<number>")}} describing the x-coordinate of the vector denoting the axis of rotation.
+
y
+
Is a {{cssxref("<number>")}} describing the y-coordinate of the vector denoting the axis of rotation.
+
z
+
Is a {{cssxref("<number>")}} describing the z-coordinate of the vector denoting the axis of rotation.
+
a
+
Is an {{ cssxref("<angle>") }} representing the angle of the rotation. A positive angle denotes a clockwise rotation, a negative angle a counter-clockwise one.
+
+ + + + + + + + + + + + + + + + + +
Cartesian coordinates on ℝ2Homogeneous coordinates on ℝℙ2Cartesian coordinates on ℝ3Homogeneous coordinates on ℝℙ3
This transform applies to the 3D space and cannot be represented on the plane. 1+(1-cos(a))(x2-1)z·sin(a)+xy(1-cos(a))-y·sin(a)+xz·(1-cos(a))-z·sin(a)+xy·(1-cos(a))1+(1-cos(a))(y2-1)x·sin(a)+yz·(1-cos(a))ysin(a) + xz(1-cos(a))-xsin(a)+yz(1-cos(a))1+(1-cos(a))(z2-1)t0001
+ +

rotateX()

+ +

The rotateX()CSS function defines a transformation that moves the element around the abscissa without deforming it. The amount of movement is defined by the specified angle; if positive, the movement will be clockwise, if negative, it will be counter-clockwise.

+ +

The axis of rotation passes by the origin, defined by {{ cssxref("transform-origin") }} CSS property.

+ +

rotateX(a)is a shorthand for rotate3D(1, 0, 0, a).

+ +
In opposition to rotations in the plane, the composition of 3D rotations is usually not commutative; it means that the order in which the rotations are applied is crucial.
+ +

表達式

+ +
rotateX(a)
+
+ +

+ +
+
a
+
Is an {{ cssxref("<angle>") }} representing the angle of the rotation. A positive angle denotes a clockwise rotation, a negative angle a counter-clockwise one.
+
+ + + + + + + + + + + + + + + + + +
Cartesian coordinates on ℝ2Homogeneous coordinates on ℝℙ2Cartesian coordinates on ℝ3Homogeneous coordinates on ℝℙ3
This transform applies to the 3D space and cannot be represented on the plane. 1000cos(a)-sin(a)0sin(a)cos(a) 10000cos(a)-sin(a)00sin(a)cos(a)00001
+ +

rotateY()

+ +

The rotateY()CSS function defines a transformation that moves the element around the ordinate without deforming it. The amount of movement is defined by the specified angle; if positive, the movement will be clockwise, if negative, it will be counter-clockwise.

+ +

The axis of rotation passes by the origin, defined by {{ cssxref("transform-origin") }} CSS property.

+ +

rotateY(a)is a shorthand for rotate3D(0, 1, 0, a).

+ +
In opposition to rotations in the plane, the composition of 3D rotations is usually not commutative; it means that the order in which the rotations are applied is crucial.
+ +

表達式

+ +
rotateY(a)
+
+ +

+ +
+
a
+
Is an {{ cssxref("<angle>") }} representing the angle of the rotation. A positive angle denotes a clockwise rotation, a negative angle a counter-clockwise one.
+
+ + + + + + + + + + + + + + + + + +
Cartesian coordinates on ℝ2Homogeneous coordinates on ℝℙ2Cartesian coordinates on ℝ3Homogeneous coordinates on ℝℙ3
This transform applies to the 3D space and cannot be represented on the plane. cos(a)0sin(a)010-sin(a)0cos(a) cos(a)0sin(a)00100-sin(a)0cos(a)00001
+ +

rotateZ()

+ +

The rotateZ()CSS function defines a transformation that moves the element around the z-axis without deforming it. The amount of movement is defined by the specified angle; if positive, the movement will be clockwise, if negative, it will be counter-clockwise.

+ +

The axis of rotation passes by the origin, defined by {{ cssxref("transform-origin") }} CSS property.

+ +

rotateZ(a)is a shorthand for rotate3D(0, 0, 1, a).

+ +
In opposition to rotations in the plane, the composition of 3D rotations is usually not commutative; it means that the order in which the rotations are applied is crucial.
+ +

表達式

+ +
rotateZ(a)
+
+ +

+ +
+
a
+
Is an {{ cssxref("<angle>") }} representing the angle of the rotation. A positive angle denotes a clockwise rotation, a negative angle a counter-clockwise one.
+
+ + + + + + + + + + + + + + + + + +
Cartesian coordinates on ℝ2Homogeneous coordinates on ℝℙ2Cartesian coordinates on ℝ3Homogeneous coordinates on ℝℙ3
This transform applies to the 3D space and cannot be represented on the plane. cos(a)-sin(a)0sin(a)cos(a)0001 cos(a)-sin(a)00sin(a)cos(a)0000000001
+ +

scale()

+ +

+ +

The scale() CSS function modifies the size of the element. It can either augment or decrease its size and as the amount of scaling is defined by a vector, it can do so more in one direction than in another one.

+ +

This transformation is characterized by a vector whose coordinates define how much scaling is done in each direction. If both coordinates of the vector are equal, the scaling is uniform, or isotropic, and the shape of the element is preserved. In that case, the scaling function defines a homothetic transformation.

+ +

When outside the ]-1, 1[ range, the scaling enlarges the element in the direction of the coordinate; when inside the range, it shrinks the element in that direction. When equal to 1 it does nothing and when negative it performs a point reflection and the size modification.

+ +
The scale() function only applies the transformation in the Euclidian plane (in 2D). To scale in the space, the scale3D() function has to be used.
+ +

表達式

+ +
scale(sx) or
+scale(sx, sy)
+
+ +

+ +
+
sx
+
Is a {{cssxref("<number>")}} representing the abscissa of the scaling vector.
+
sy
+
Is a {{cssxref("<number>")}} representing the ordinate of the scaling vector. If not present, its default value is sx, leading to a uniform scaling preserving the shape of the element.
+
+ + + + + + + + + + + + + + + + + + + + + +
Cartesian coordinates on ℝ2Homogeneous coordinates on ℝℙ2Cartesian coordinates on ℝ3Homogeneous coordinates on ℝℙ3
sx0 0sy sx000sy0001 sx000sy0001 sx0000sy0000100001
[sx 0 0 sy 0 0]
+ +

scale3d()

+ +

The scale3d() CSS function modifies the size of an element. Because the amount of scaling is defined by a vector, it can resize different dimensions at different scales.

+ +

This transformation is characterized by a vector whose coordinates define how much scaling is done in each direction. If all three coordinates of the vector are equal, the scaling is uniform, or isotropic, and the shape of the element is preserved. In that case, the scaling function defines a homothetic transformation.

+ +

When outside the [-1, 1] range, the scaling enlarges the element in the direction of the coordinate; when inside the range, it shrinks the element in that direction. When equal to 1 it does nothing and when negative it performs a point reflection and the size modification.

+ +

表達式

+ +
scale3d(sx, sy, sz)
+
+ +

+ +
+
sx
+
Is a {{cssxref("<number>")}} representing the abscissa of the scaling vector.
+
sy
+
Is a {{cssxref("<number>")}} representing the ordinate of the scaling vector.
+
sz
+
Is a {{cssxref("<number>")}} representing the z-component of the scaling vector.
+
+ + + + + + + + + + + + + + + + + +
Cartesian coordinates on ℝ2Homogeneous coordinates on ℝℙ2Cartesian coordinates on ℝ3Homogeneous coordinates on ℝℙ3
This transform applies to the 3D space and cannot be represented on the plane. sx000sy000sz sx0000sy0000sz00001
+ +

scaleX()

+ +

The scaleX() CSS function modifies the abscissa of each element point by a constant factor, except if this scale factor is 1, in which case the function is the identity transform. The scaling is not isotropic and the angles of the element are not conserved.

+ +

scaleX(sx) is a shorthand for scale(sx, 1) or for scale3d(sx, 1, 1).

+ +

scaleX(-1) defines an axial symmetry with a vertical axis passing by the origin (as specified by the transform-origin property).

+ +

表達式

+ +
scaleX(s)
+
+ +

+ +
+
s
+
Is a {{cssxref("<number>")}} representing the scaling factor to apply on the abscissa of each point of the element.
+
+ + + + + + + + + + + + + + + + + + + + + +
Cartesian coordinates on ℝ2Homogeneous coordinates on ℝℙ2Cartesian coordinates on ℝ3Homogeneous coordinates on ℝℙ3
s0 01 s00010001 s00010001 s000010000100001
[s 0 0 1 0 0]
+ +

scaleY()

+ +

+ +

The scaleY() CSS function modifies the ordinate of each element point by a constant factor except if this scale factor is 1, in which case the function is the identity transform. The scaling is not isotropic and the angles of the element are not conserved.

+ +

scaleY(sy) is a shorthand for scale(1, sy) or for scale3d(1, sy, 1).

+ +

scaleY(-1) defines an axial symmetry with a horizontal axis passing by the origin (as specified by the transform-origin property).

+ +

表達式

+ +
scaleY(s)
+
+ +

+ +
+
s
+
Is a {{cssxref("<number>")}} representing the scaling factor to apply on the ordinate of each point of the element.
+
+ + + + + + + + + + + + + + + + + + + + + +
Cartesian coordinates on ℝ2Homogeneous coordinates on ℝℙ2Cartesian coordinates on ℝ3Homogeneous coordinates on ℝℙ3
10 0s 1000s0001 1000s0001 10000s0000100001
[1 0 0 s 0 0]
+ +

scaleZ()

+ +

The scaleZ() CSS function modifies the z-coordinate of each element point by a constant factor, except if this scale factor is 1, in which case the function is the identity transform. The scaling is not isotropic and the angles of the element are not conserved.

+ +

scaleZ(sz) is a shorthand for scale3d(1, 1, sz).

+ +

scaleZ(-1) defines an axial symmetry along the z-axis passing by the origin (as specified by the transform-origin property).

+ +

表達式

+ +
scaleZ(s)
+
+ +

+ +
+
s
+
Is a {{cssxref("<number>")}} representing the scaling factor to apply on the z-coordinate of each point of the element.
+
+ + + + + + + + + + + + + + + + + +
Cartesian coordinates on ℝ2Homogeneous coordinates on ℝℙ2Cartesian coordinates on ℝ3Homogeneous coordinates on ℝℙ3
This transform applies to the 3D space and cannot be represented on the plane. 10001000s 1000010000s00001
+ +

skew()

+ +

The skew() CSS function is a shear mapping, or transvection, distorting each point of an element by a certain angle in each direction. It is done by increasing each coordinate by a value proportionate to the specified angle and to the distance to the origin. The more far from the origin, the more away the point is, the greater will be the value added to it.

+ +

表達式

+ +
skew(ax)       or
+skew(ax, ay)
+
+ +

+ +
+
ax
+
Is an {{ cssxref("<angle>") }} representing the angle to use to distort the element along the abscissa.
+
ay
+
Is an {{ cssxref("<angle>") }} representing the angle to use to distort the element along the ordinate.
+
+ + + + + + + + + + + + + + + + + + + + + +
Cartesian coordinates on ℝ2Homogeneous coordinates on ℝℙ2Cartesian coordinates on ℝ3Homogeneous coordinates on ℝℙ3
1tan(ax)tan(ay)1 1tan(ax)0tan(ay)10001 1tan(ax)0tan(ay)10001 1tan(ax)00tan(ay)10000100001
[1 tan(ay) tan(ax) 1 0 0]
+ +

skewX()

+ +

The skewX() CSS function is a horizontal shear mapping distorting each point of an element by a certain angle in the horizontal direction. It is done by increasing the abscissa coordinate by a value proportionate to the specified angle and to the distance to the origin. The more far from the origin, the more away the point is, the greater will be the value added to it.

+ +

表達式

+ +
skewX(a)
+
+ +

+ +
+
a
+
Is an {{ cssxref("<angle>") }} representing the angle to use to distort the element along the abscissa.
+
+ + + + + + + + + + + + + + + + + + + + + +
Cartesian coordinates on ℝ2Homogeneous coordinates on ℝℙ2Cartesian coordinates on ℝ3Homogeneous coordinates on ℝℙ3
1tan(ay)01 1tan(ay)0010001 1tan(ay)0010001 1tan(ay)00010000100001
[1 0 tan(a) 1 0 0]
+ +

skewY()

+ +

The skewY() CSS function is a vertical shear mapping distorting each point of an element by a certain angle in the vertical direction. It is done by increasing the ordinate coordinate by a value proportionate to the specified angle and to the distance to the origin. The more far from the origin, the more away the point is, the greater will be the value added to it.

+ +

表達式

+ +
skewY(a)
+
+ +

+ +
+
a
+
Is an {{ cssxref("<angle>") }} representing the angle to use to distort the element along the ordinate.
+
+ + + + + + + + + + + + + + + + + + + + + +
Cartesian coordinates on ℝ2Homogeneous coordinates on ℝℙ2Cartesian coordinates on ℝ3Homogeneous coordinates on ℝℙ3
10tan(ax)1 100tan(ax)10001 100tan(ax)10001 1000tan(ax)10000100001
[1 tan(a) 0 1 0 0]
+ +

translate()

+ +

The translate() CSS function moves the position of the element on the plane. This transformation is characterized by a vector whose coordinates define how much it moves in each direction.

+ +

Syntax

+ +
translate(tx)       or
+translate(tx, ty)
+
+ +

+ +
+
tx
+
Is a {{cssxref("<length>")}} representing the abscissa of the translating vector.
+
ty
+
Is a {{cssxref("<length>")}} representing the ordinate of the translating vector. If missing, it is assumed to be equals to txtranslate(2) means translate(2, 2).
+
+ + + + + + + + + + + + + + + + + + + + + +
Cartesian coordinates on ℝ2Homogeneous coordinates on ℝℙ2Cartesian coordinates on ℝ3Homogeneous coordinates on ℝℙ3
+

A translation is not a linear transform in ℝ2 and cannot be represented using a matrix in the cartesian coordinates system.

+
10tx01ty001 10tx01ty001 100tx010ty00100001
[1 0 0 1 tx ty]
+ +

translate3d()

+ +

The translate3d() CSS function moves the position of the element in the 3D space. This transformation is characterized by a 3-dimension vector whose coordinates define how much it moves in each direction.

+ +

表達式

+ +
translate3d(tx, ty, tz)
+
+ +

+ +
+
tx
+
Is a {{cssxref("<length>")}} representing the abscissa of the translating vector.
+
ty
+
Is a {{cssxref("<length>")}} representing the ordinate of the translating vector.
+
tz
+
Is a {{cssxref("<length>")}} representing the z component of the translating vector. It can't be a {{cssxref("<percentage>")}} value; in that case the property containing the transform is considered invalid.
+
+ + + + + + + + + + + + + + + + + +
Cartesian coordinates on ℝ2Homogeneous coordinates on ℝℙ2Cartesian coordinates on ℝ3Homogeneous coordinates on ℝℙ3
+

This transform applies to the 3D space and cannot be represented on the plane.

+
A translation is not a linear transform in ℝ3 and cannot be represented using a matrix in the Cartesian coordinates system. 100tx010ty001tz0001
+ +

translateX()

+ +

The translateX() CSS function moves the element horizontally on the plane. This transformation is characterized by a {{cssxref("<length>")}} defining how much it moves horizontally.

+ +

translateX(tx) is a shortcut for translate(tx, 0).

+ +

表達式

+ +
translateX(t)
+
+ +

+ +
+
t
+
Is a {{cssxref("<length>")}} representing the abscissa of the translating vector.
+
+ + + + + + + + + + + + + + + + + + + + + +
Cartesian coordinates on ℝ2Homogeneous coordinates on ℝℙ2Cartesian coordinates on ℝ3Homogeneous coordinates on ℝℙ3
+

A translation is not a linear transform in ℝ2 and cannot be represented using a matrix in the cartesian coordinates system.

+
10t010001 10t010001 100t010000100001
[1 0 0 1 t 0]
+ +

translateY()

+ +

The translateY() CSS function moves the element vertically on the plane. This transformation is characterized by a {{cssxref("<length>")}} defining how much it moves vertically.

+ +

translateY(ty) is a shortcut for translate(0, ty).

+ +

Syntax

+ +
translateY(t)
+
+ +

+ +
+
t
+
Is a {{cssxref("<length>")}} representing the ordinate of the translating vector.
+
+ + + + + + + + + + + + + + + + + + + + + +
Cartesian coordinates on ℝ2Homogeneous coordinates on ℝℙ2Cartesian coordinates on ℝ3Homogeneous coordinates on ℝℙ3
+

A translation is not a linear transform in ℝ2 and cannot be represented using a matrix in the cartesian coordinates system.

+
10001t001 10001t001 1000010t00100001
[1 0 0 1 0 t]
+ +

translateZ()

+ +

The translateZ() CSS function moves the element along the z-axis of the 3D space. This transformation is characterized by a {{cssxref("<length>")}} defining how much it moves.

+ +

translateZ(tz) is a shorthand for translate3d(0, 0, tz).

+ +

表達式

+ +
translateZ(t)
+
+ +

+ +
+
t
+
Is a {{cssxref("<length>")}} representing the z-component of the translating vector. It can't be a {{cssxref("<percentage>")}} value; in that case the property containing the transform is considered invalid.
+
+ + + + + + + + + + + + + + + + + +
Cartesian coordinates on ℝ2Homogeneous coordinates on ℝℙ2Cartesian coordinates on ℝ3Homogeneous coordinates on ℝℙ3
This transform applies to the 3D space and cannot be represented on the plane.A translation is not a linear transform in ℝ3 and cannot be represented using a matrix in the Cartesian coordinates system. 10000100001t0001
+ +

 

diff --git a/files/zh-tw/web/css/transform-function/translate3d()/index.html b/files/zh-tw/web/css/transform-function/translate3d()/index.html new file mode 100644 index 0000000000..149980d71d --- /dev/null +++ b/files/zh-tw/web/css/transform-function/translate3d()/index.html @@ -0,0 +1,116 @@ +--- +title: translate3d() +slug: Web/CSS/transform-function/translate3d() +translation_of: Web/CSS/transform-function/translate3d() +--- +
{{CSSRef}}
+ +

translate3d() CSS 函式以 3D 場境的方式定位元素。其結果為 {{cssxref("<transform-function>")}} 資料型別。

+ +
{{EmbedInteractiveExample("pages/css/function-translate3d.html")}}
+ + + +

這個轉場的特徵是三維向量,其坐標則定義元素的方向該如何移動。

+ +

語法

+ +
translate3d(tx, ty, tz)
+
+ +

數值

+ +
+
tx
+
其 {{cssxref("<length>")}} 代表平移向量的橫坐標。
+
ty
+
其 {{cssxref("<length>")}} 代表平移向量的縱坐標。
+
tz
+
其 {{cssxref("<length>")}} 代表平移向量的 z 分量。數值不能是 {{cssxref("<percentage>")}}:否則,此轉場的屬性無效。
+
+ + + + + + + + + + + + + + + + + +
2 上的笛卡兒座標(Cartesian coordinate)ℝℙ2 上的齊次坐標(homogeneous coordinates)3 上的笛卡兒座標ℝℙ3 上的齊次坐標
+

This transformation applies to the 3D space and can't be represented on the plane.

+
A translation is not a linear transformation in ℝ3 and can't be represented using a Cartesian-coordinate matrix. 100tx010ty001tz0001
+ +

示例

+ +

使用單軸平移

+ +

HTML

+ +
<div>Static</div>
+<div class="moved">Moved</div>
+<div>Static</div>
+ +

CSS

+ +
div {
+  width: 60px;
+  height: 60px;
+  background-color: skyblue;
+}
+
+.moved {
+  /* Equivalent to perspective(500px) translateX(10px) */
+  transform: perspective(500px) translate3d(10px, 0, 0px);
+  background-color: pink;
+}
+
+ +

結果

+ +

{{EmbedLiveSample("Using_a_single_axis_translation", 250, 250)}}

+ +

Combining z-axis and x-axis translation

+ +

HTML

+ +
<div>Static</div>
+<div class="moved">Moved</div>
+<div>Static</div>
+ +

CSS

+ +
div {
+  width: 60px;
+  height: 60px;
+  background-color: skyblue;
+}
+
+.moved {
+  transform: perspective(500px) translate3d(10px, 0, 100px);
+  background-color: pink;
+}
+
+ +

結果

+ +

{{EmbedLiveSample("Combining_z-axis_and_x-axis_translation", 250, 250)}}

+ +

瀏覽器相容性

+ +

請參見 <transform-function>

+ +

參見

+ + diff --git a/files/zh-tw/web/css/transform-origin/index.html b/files/zh-tw/web/css/transform-origin/index.html new file mode 100644 index 0000000000..2cfccb1716 --- /dev/null +++ b/files/zh-tw/web/css/transform-origin/index.html @@ -0,0 +1,455 @@ +--- +title: transform-origin +slug: Web/CSS/transform-origin +tags: + - CSS +translation_of: Web/CSS/transform-origin +--- +
{{ CSSRef }}
+ +

CSS 內的transform-origin屬性可以設定元素變化的原點。

+ +
{{EmbedInteractiveExample("pages/css/transform-origin.html")}}
+ + + +

變化原點指的是應用變化的點。舉例來說, rotate()函數的原點為旋轉中心。 (This property is applied by first translating the element by the negated value of the property, then applying the element's transform, then translating by the property value.)

+ +

語法

+ +
/* One-value syntax */
+transform-origin: 2px;
+transform-origin: bottom;
+
+/* x-offset | y-offset */
+transform-origin: 3cm 2px;
+
+/* x-offset-keyword | y-offset */
+transform-origin: left 2px;
+
+/* x-offset-keyword | y-offset-keyword */
+transform-origin: right top;
+
+/* y-offset-keyword | x-offset-keyword */
+transform-origin: top right;
+
+/* x-offset | y-offset | z-offset */
+transform-origin: 2px 30% 10px;
+
+/* x-offset-keyword | y-offset | z-offset */
+transform-origin: left 5px -3px;
+
+/* x-offset-keyword | y-offset-keyword | z-offset */
+transform-origin: right bottom 2cm;
+
+/* y-offset-keyword | x-offset-keyword | z-offset */
+transform-origin: bottom right 2cm;
+
+/* Global values */
+transform-origin: inherit;
+transform-origin: initial;
+transform-origin: unset;
+
+ +

The transform-origin p屬性可以使用多次,每一次都代表著一個偏移量。若未設定偏移量,則重置為其對應的 初始值

+ +

If two or more values are defined and either no value is a keyword, or the only used keyword is center, then the first value represents the horizontal offset and the second represents the vertical offset.

+ + + +

Values

+ +
+
x-offset
+
Is a {{cssxref("<length>")}} or a {{cssxref("<percentage>")}} describing how far from the left edge of the box the origin of the transform is set.
+
offset-keyword
+
Is one of the left, right, top, bottom, or center keyword describing the corresponding offset.
+
y-offset
+
Is a {{cssxref("<length>")}} or a {{cssxref("<percentage>")}} describing how far from the top edge of the box the origin of the transform is set.
+
x-offset-keyword
+
Is one of the left, right, or center keyword describing how far from the left edge of the box the origin of the transform is set.
+
y-offset-keyword
+
Is one of the top, bottom, or center keyword describing how far from the top edge of the box the origin of the transform is set.
+
z-offset
+
Is a {{cssxref("<length>")}} (and never a {{cssxref("<percentage>")}} which would make the statement invalid) describing how far from the user eye the z=0 origin is set.
+
+ +

The keywords are convenience shorthands and match the following {{cssxref("<percentage>")}} values:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
KeywordValue
left0%
center50%
right100%
top0%
bottom100%
+ +

Formal syntax

+ +
{{csssyntax}}
+ +

Examples

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CodeSample
+

transform: none;

+
+ + +
{{EmbedLiveSample('transform_none', '', 120, '', '', 'no-button') }}
+
+

transform: rotate(30deg);

+
+ + +
{{EmbedLiveSample('transform_rotate_only', '', 120, '', '', 'no-button') }}
+
+

transform: rotate(30deg);
+ transform-origin: 0 0;

+
+ + +
{{EmbedLiveSample('transform_rotate', '', 120, '', '', 'no-button') }}
+
+

transform: rotate(30deg);
+ transform-origin: 100% 100%;

+
+ + +
{{EmbedLiveSample('transform_rotate_with_percentage', '', 120, '', '', 'no-button') }}
+
+

transform: rotate(30deg);
+ transform-origin: -1em -3em;

+
+ + +
{{EmbedLiveSample('transform_rotate_with_em', '', 120, '', '', 'no-button') }}
+
+

transform: scale(1.7);

+
+ + +
{{EmbedLiveSample('transform_scale_only', '', 120, '', '', 'no-button') }}
+
+

transform: scale(1.7);
+ transform-origin: 0 0;

+
+ + +
{{EmbedLiveSample('transform_scale_without_origin', '', 120, '', '', 'no-button') }}
+
+

transform: scale(1.7);
+ transform-origin: 100% -30%;

+
+ + +
{{EmbedLiveSample('transform_scale', '', 120, '', '', 'no-button') }}
+
+

transform: skewX(50deg);
+ transform-origin: 100% -30%;

+
+ + +
{{EmbedLiveSample('transform_skew_x', '', 120, '', '', 'no-button') }}
+
+

transform: skewY(50deg);
+ transform-origin: 100% -30%;

+
+ + +
{{EmbedLiveSample('transform_skew_y', '', 120, '', '', 'no-button') }}
+
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSS3 Transforms', '#transform-origin-property', 'transform-origin') }}{{ Spec2('CSS3 Transforms') }} 
+ +

{{Cssinfo}}

+ +

Browser compatibility

+ + + +

{{Compat("css.properties.transform-origin")}}

+ +

See also

+ + diff --git a/files/zh-tw/web/css/transform/index.html b/files/zh-tw/web/css/transform/index.html new file mode 100644 index 0000000000..7b1f9ee11b --- /dev/null +++ b/files/zh-tw/web/css/transform/index.html @@ -0,0 +1,159 @@ +--- +title: transform +slug: Web/CSS/transform +tags: + - CSS + - CSS Property + - NeedsBrowserCompatibility + - Reference + - Transforms +translation_of: Web/CSS/transform +--- +
{{CSSRef}}
+ +

transform CSS 屬性可以讓你修改 CSS 可視化格式模型(visual formatting model)的空間維度。使用此屬性,元素可以被平移、旋轉、縮放和傾斜。

+ +
{{EmbedInteractiveExample("pages/css/transform.html")}}
+ +

如果這個屬性的值不是 none,將會建立一個 stacking context。在這個情況下,此元素將被其所包含的 position: fixed 元素當成一個 containing block。

+ +
+

只有可以變形的元素可以被變形,這包括所有被CSS box model掌管輸出的元素,除了視覺格式化模型, table-column boxestable-colunm-group boxes

+
+ +

語法

+ +
/* Keyword values */
+transform: none;
+
+/* Function values */
+transform: matrix(1.0, 2.0, 3.0, 4.0, 5.0, 6.0);
+transform: matrix3d(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
+transform: perspective(17px);
+transform: rotate(0.5turn);
+transform: rotate3d(1, 2.0, 3.0, 10deg);
+transform: rotateX(10deg);
+transform: rotateY(10deg);
+transform: rotateZ(10deg);
+transform: translate(12px, 50%);
+transform: translate3d(12px, 50%, 3em);
+transform: translateX(2em);
+transform: translateY(3in);
+transform: translateZ(2px);
+transform: scale(2, 0.5);
+transform: scale3d(2.5, 1.2, 0.3);
+transform: scaleX(2);
+transform: scaleY(0.5);
+transform: scaleZ(0.3);
+transform: skew(30deg, 20deg);
+transform: skewX(30deg);
+transform: skewY(1.07rad);
+
+/* Multiple function values */
+transform: translateX(10px) rotate(10deg) translateY(5px);
+transform: perspective(500px) translate(10px, 0, 20px) rotateY(3deg);
+
+/* Global values */
+transform: inherit;
+transform: initial;
+transform: unset;
+ +

transform 屬性可能被指定為關鍵字值 none 或著一或多個 <transform-function> 值。

+ +

+ +
+
{{cssxref("<transform-function>")}}
+
可使用一個或多個 CSS transform functions。複合的transforms 會由左至右的順序來套用。
+
none
+
設定為沒有套用任何 transform。
+
+ +

可使用性問題

+ +

改變尺寸和伸縮的動畫會影響網頁普遍的可使用性,因為它們可能促發一些頭痛的問題。如果你想要在網頁中提供這樣的功能,最好在網頁中放上給使用者關閉這些功能的控制開關。

+ +

另外也可考慮使用{{cssxref("@media/prefers-reduced-motion", "prefers-reduced-motion")}} 這個媒體功能來寫一個在系統設定端的媒體詢問,讓使用者在減少了動畫偏好之後可以關閉該使用者網頁的動畫功能。

+ +

瞭解更多:

+ + + +

正式定義

+ +

{{CSSInfo}}

+ +

標準語法

+ +
{{csssyntax}}
+ +

範例

+ +

平移、旋轉元素

+ + + +

HTML

+ + + +
<p>Transformed element</p>
+ +

CSS

+ +
p {
+  border: solid red;
+  transform: translate(100px) rotate(20deg);
+  transform-origin: 0 -250px;
+}
+ +

結果

+ +

{{EmbedLiveSample("Translating_and_rotating_an_element", "400", "160")}}

+ +

更多範例

+ +

請參考使用 CSS transforms 以及 {{cssxref("<transform-function>")}} 的更多範例。

+ +

規範

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS Transforms 2', '#transform-functions', 'transform')}}{{Spec2('CSS Transforms 2')}}Adds 3D transform functions.
{{SpecName('CSS3 Transforms', '#transform-property', 'transform')}}{{Spec2('CSS3 Transforms')}}Initial definition.
+ +

{{cssinfo}}

+ +

瀏覽器相容性

+ + + +

{{Compat("css.properties.transform")}}

+ +

參見

+ + diff --git a/files/zh-tw/web/css/transition-duration/index.html b/files/zh-tw/web/css/transition-duration/index.html new file mode 100644 index 0000000000..f29fa166ca --- /dev/null +++ b/files/zh-tw/web/css/transition-duration/index.html @@ -0,0 +1,342 @@ +--- +title: transition-duration +slug: Web/CSS/transition-duration +tags: + - CSS + - CSS Property + - CSS 轉場 + - Reference +translation_of: Web/CSS/transition-duration +--- +
{{CSSRef}}
+ +

transition-duration CSS 屬性指定轉場動畫所需經歷的時間,以秒或是毫秒為單位。默認值為0,表示沒有任何轉場動畫。

+ +
{{EmbedInteractiveExample("pages/css/transition-duration.html")}}
+ + + +

你可以指定多個時間長度,每一個時間長度都會被應用在{{ cssxref("transition-property") }} 設定的對應屬性上(which acts as a master list.) 如果指定的時間長度的數量比對應屬性的數量少,那麼時間長度就會被重複使用。反之,多餘的時間長度就會被刪去。而這兩種情況之下的CSS宣告都是有效的。

+ +

語法

+ +
/* <time> 值 */
+transition-duration: 6s;
+transition-duration: 120ms;
+transition-duration: 1s, 15s;
+transition-duration: 10s, 30s, 230ms;
+
+/* 全域值 */
+transition-duration: inherit;
+transition-duration: initial;
+transition-duration: unset;
+
+ +

+ +
+
<time>
+
{{cssxref("<time>")}}類型表示轉場動畫從舊狀態轉至新狀態所需要的時間。如果時間長度為0,表示沒有任何轉場,狀態之間會立即改變。若時間長度為負值則無效。
+
+ +

正式語法

+ +
{{csssyntax}}
+ +

範例

+ +
+
+

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

規範

+ + + + + + + + + + + + + + + + +
規範狀態備註
{{ SpecName('CSS3 Transitions', '#transition-duration', 'transition-duration') }}{{ Spec2('CSS3 Transitions') }}Initial definition
+ +

{{cssinfo}}

+ +

瀏覽器支援情形

+ + + +

{{Compat("css.properties.transition-duration")}}

+ +

更多資訊

+ + diff --git a/files/zh-tw/web/css/transition-timing-function/index.html b/files/zh-tw/web/css/transition-timing-function/index.html new file mode 100644 index 0000000000..492a4e3c3e --- /dev/null +++ b/files/zh-tw/web/css/transition-timing-function/index.html @@ -0,0 +1,605 @@ +--- +title: transition-timing-function +slug: Web/CSS/transition-timing-function +translation_of: Web/CSS/transition-timing-function +--- +
{{CSSRef}}
+ +

transition-timing-function CSS 屬性用於表示各個被動畫特效影響的屬性的區間值計算方式。

+ +
{{EmbedInteractiveExample("pages/css/transition-timing-function.html")}}
+ + + +

 

+ +

本質上,這個屬性讓你使用加速度曲線來表示動畫變換的速度。

+ +

而每個可以動畫化的屬性使用一個 {{cssxref("<timing-function>")}} 作為加速度曲線。

+ +

 

+ +

你也許有許多時間函數,而你可以透過使用 {{ cssxref("transition-property") }} 屬性來個別設置。如果有前述清單的數量超過時間函數的數量,則會使用預設值 ease;如果少於那多餘的時間函數會被忽略,在這兩種情況,CSS 宣告總會有效。

+ +

語法

+ +
/* Keyword */
+transition-timing-function: ease;
+transition-timing-function: ease-in;
+transition-timing-function: ease-out;
+transition-timing-function: ease-in-out;
+transition-timing-function: linear;
+transition-timing-function: step-start;
+transition-timing-function: step-end;
+
+/* 函數 */
+transition-timing-function: steps(4, end);
+transition-timing-function: cubic-bezier(0.1, 0.7, 1.0, 0.1);
+transition-timing-function: frames(10);
+
+/* 多個函數 */
+transition-timing-function: ease, step-start, cubic-bezier(0.1, 0.7, 1.0, 0.1);
+
+/* 全域值 */
+transition-timing-function: inherit;
+transition-timing-function: initial;
+transition-timing-function: unset;
+
+/* 包含 transition-property */
+transition-property: width, height;
+transition-timing-function: ease-in, ease-out; // ease-in to width and ease-out to height
+
+
+ +

+ +
+
<timing-function>
+
每個 {{cssxref("<timing-function>")}} 連結到對應的動畫化屬性,請參考 {{ cssxref("transition-property") }}。
+
+ +

公式語法

+ +
{{csssyntax}}
+ +

範例

+ +
+
+

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: ease-in

+ +
+
 <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-in;
+    transition-property: width height background-color font-size left top color;
+    transition-duration:2s;
+    transition-timing-function: ease-in;
+}
+.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-in;
+    transition-property: width height background-color font-size left top color;
+    transition-duration:2s;
+    transition-timing-function: ease-in;
+}
+
+ +
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_easein",275,150)}}
+
+ +
+

transition-timing-function: ease-out

+ +
+
 <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-out;
+    transition-property: width height background-color font-size left top color;
+    transition-duration:2s;
+    transition-timing-function: ease-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-timing-function: ease-out;
+    transition-property: width height background-color font-size left top color;
+    transition-duration:2s;
+    transition-timing-function: ease-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("ttf_easeout",275,150)}}
+
+ +
+

transition-timing-function: ease-in-out

+ +
+
 <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-in-out;
+    transition-property: width height background-color font-size left top color;
+    transition-duration:2s;
+    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-timing-function: ease-in-out;
+    transition-property: width height background-color font-size left top 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("ttf_easeinout",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-start

+ +
+
 <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-start;
+    transition-property: width height background-color font-size left top color;
+    transition-duration:2s;
+    transition-timing-function: step-start;
+}
+.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-start;
+    transition-property: width height background-color font-size left top color;
+    transition-duration:2s;
+    transition-timing-function: step-start;
+}
+
+ +
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_stepstart",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)}}
+
+ +

規格

+ + + + + + + + + + + + + + + + +
規格狀態備註
{{ SpecName('CSS3 Transitions', '#transition-timing-function-property', 'transition-timing-function') }}{{ Spec2('CSS3 Transitions') }}初始定義
+ +

{{cssinfo}}

+ +

相容性

+ + + +

{{Compat("css.properties.transition-timing-function")}}

+ +

看更多

+ + diff --git a/files/zh-tw/web/css/transition/index.html b/files/zh-tw/web/css/transition/index.html new file mode 100644 index 0000000000..3e5b3c042c --- /dev/null +++ b/files/zh-tw/web/css/transition/index.html @@ -0,0 +1,106 @@ +--- +title: transition +slug: Web/CSS/transition +tags: + - CSS + - CSS Property + - CSS轉場 + - Reference +translation_of: Web/CSS/transition +--- +
{{CSSRef}}
+ +

transition CSS 屬性是 {{ cssxref("transition-property") }}, {{ cssxref("transition-duration") }}, {{ cssxref("transition-timing-function") }}, and {{ cssxref("transition-delay") }}的 特性簡寫

+ +
{{EmbedInteractiveExample("pages/css/transition.html")}}
+ + + +

Transitions 讓你可以定義元件在兩個狀態之間切換的轉場效果。兩個不同狀態可以使用虛擬類別 定義,像是{{cssxref(":hover")}} 或 {{cssxref(":active")}} 亦或是 使用JavaScript設定的狀態變化。

+ +

語法

+ +
/* Apply to 1 property */
+/* property name | duration */
+transition: margin-right 4s;
+
+/* property name | duration | delay */
+transition: margin-right 4s 1s;
+
+/* property name | duration | timing function */
+transition: margin-right 4s ease-in-out;
+
+/* property name | duration | timing function | delay */
+transition: margin-right 4s ease-in-out 1s;
+
+/* Apply to 2 properties */
+transition: margin-right 4s, color 1s;
+
+/* Apply to all changed properties */
+transition: all 0.5s ease-out;
+
+/* Global values */
+transition: inherit;
+transition: initial;
+transition: unset;
+
+ +

transition 屬性可以包含一個或多個轉場設定,每一項設定都以逗點分開。

+ +

每一項設定都描述著每一項屬性所對應的轉場效果(或是all 及 none這兩個特殊值) 。其包含了:

+ + + +

當每個轉場設定不等長時,請參見 當property values list 之間不等長時... 。簡而言之,多餘的描述(超過實際被執行的數量)會直接被忽略。

+ +

標準語法

+ +
{{csssyntax}}
+ +

範例

+ +

CSS 轉場 有更多範例。

+ +

規範

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{ SpecName('CSS3 Transitions', '#transition-shorthand-property', 'transition') }}{{ Spec2('CSS3 Transitions') }}Initial definition
+ +

{{cssinfo}}

+ +

瀏覽器支援情況

+ + + +

{{Compat("css.properties.transition")}}

+ +

更多資訊

+ + diff --git a/files/zh-tw/web/css/type_selectors/index.html b/files/zh-tw/web/css/type_selectors/index.html new file mode 100644 index 0000000000..6a6bb32e89 --- /dev/null +++ b/files/zh-tw/web/css/type_selectors/index.html @@ -0,0 +1,79 @@ +--- +title: 元素選擇器 +slug: Web/CSS/Type_selectors +translation_of: Web/CSS/Type_selectors +--- +
{{CSSRef}}
+CSS 元素選擇器 (也稱 型態選擇器)依照 Node 節點名稱選取匹配的 Element 元素。換句話說,此選擇器選取在 Document 文件內所有指定該型態的元素。
+ +
 
+ +
/* 全部的 <a> 元素。*/
+a {
+  color: red;
+}
+ +

語法

+ +
element { style properties }
+
+ +

範例

+ +

CSS

+ +
span {
+  background-color: skyblue;
+}
+
+ +

HTML

+ +
<span>Here's a span with some text.</span>
+<p>Here's a p with some text.</p>
+<span>Here's a span with more text.</span>
+
+ +

Result

+ +

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

+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS4 Selectors', '#type-selectors', 'Type (tag name) selector')}}{{Spec2('CSS4 Selectors')}}No changes
{{SpecName('CSS3 Selectors', '#type-selectors', 'type selectors')}}{{Spec2('CSS3 Selectors')}}No changes
{{SpecName('CSS2.1', 'selector.html#type-selectors', 'type selectors')}}{{Spec2('CSS2.1')}} 
{{SpecName('CSS1', '#basic-concepts', 'type selectors')}}{{Spec2('CSS1')}}Initial definition
+ +

Browser compatibility

+ + + +

{{Compat("css.selectors.type")}}

diff --git a/files/zh-tw/web/css/white-space/index.html b/files/zh-tw/web/css/white-space/index.html new file mode 100644 index 0000000000..eef166cc0e --- /dev/null +++ b/files/zh-tw/web/css/white-space/index.html @@ -0,0 +1,425 @@ +--- +title: white-space +slug: Web/CSS/white-space +translation_of: Web/CSS/white-space +--- +
{{CSSRef}}
+ +

此 CSS white-space 屬性決定如何處理元素內的空白字元。

+ +
+

提醒:如果要讓文字本身斷行,請改用 {{cssxref("overflow-wrap")}}、{{cssxref("word-break")}} 或 {{cssxref("hyphens")}}。

+
+ +
/* Keyword values */
+white-space: normal;
+white-space: nowrap;
+white-space: pre;
+white-space: pre-wrap;
+white-space: pre-line;
+
+/* Global values */
+white-space: inherit;
+white-space: initial;
+white-space: unset;
+
+ + + +

{{EmbedLiveSample("white-space", "100%", 530, "", "", "example-outcome-frame")}}

+ +

{{cssinfo}}

+ +

Syntax

+ +

 white-space 的特性值為下列其中之一。

+ +

Values

+ +
+
normal
+
連續的空白字元會被合併(collapse),換行字元被視為空白字元。換行只在被文字空間限制時發生。
+
nowrap
+
對待空白字元的方式跟 normal 一樣,且會強制不換行。
+
pre
+
連續的空白字元都會被保留。換行在有換行字元以及{{HTMLElement("br")}}時發生。
+
pre-wrap
+
連續的空白字元都會被保留。換行會在換行字元、有{{HTMLElement("br")}}元素以及被文字空間限制時發生。
+
pre-line
+
連續的空白字元會被合併(collapse)。換行在換行字元、 {{HTMLElement("br")}}以及被文字空間限制時發生。
+
+ +

下列表格整理了各項 white-space 值的行為:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
 New linesSpaces and tabsText wrapping
normalCollapseCollapseWrap
nowrapCollapseCollapseNo wrap
prePreservePreserveNo wrap
pre-wrapPreservePreserveWrap
pre-linePreserveCollapseWrap
+ +

Formal syntax

+ +
{{csssyntax}}
+ +

Examples

+ +

Basic example

+ +
code {
+  white-space: pre;
+}
+ +

Line breaks inside {{HTMLElement("pre")}} elements

+ +
pre {
+  word-wrap: break-word;      /* IE 5.5-7 */
+  white-space: -moz-pre-wrap; /* Firefox 1.0-2.0 */
+  white-space: pre-wrap;      /* Modern browsers */
+}
+ +

See it in action

+ + + +

Source

+ +
    <p>    Lorem ipsum dolor sit amet, consectetur adipiscing 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.</p>
+
+ +

CSS + Result

+ +

{{ EmbedLiveSample('See_in_action', '80%', '500px') }}

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Text', '#propdef-white-space', 'white-space')}}{{Spec2('CSS3 Text')}}Precisely defines the breaking algorithms.
{{SpecName('CSS2.1', 'text.html#white-space-prop', 'white-space')}}{{Spec2('CSS2.1')}}Initial definition.
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support (normal and nowrap)1.0{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.0")}}5.5[1]4.01.0 (85)
pre1.0{{CompatVersionUnknown}}1.06.04.01.0 (85)
pre-wrap1.0{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.0")}}{{property_prefix("-moz")}}
+ {{CompatGeckoDesktop("1.9")}}
8.08.03.0 (522)
pre-line1.0{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.1")}}8.09.53.0 (522)
Support on <textarea>1.0{{CompatUnknown}}{{CompatGeckoDesktop("36")}}5.54.01.0 (85)
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Internet Explorer 5.5+ supports {{Cssxref("word-wrap")}}: break-word;.

+ +

See also

+ + diff --git a/files/zh-tw/web/css/width/index.html b/files/zh-tw/web/css/width/index.html new file mode 100644 index 0000000000..9459dd32e9 --- /dev/null +++ b/files/zh-tw/web/css/width/index.html @@ -0,0 +1,294 @@ +--- +title: width +slug: Web/CSS/width +translation_of: Web/CSS/width +--- +
{{CSSRef}}
+ +

The width CSS property specifies the width of an element. By default, the property defines the width of the content area. If {{cssxref("box-sizing")}} is set to border-box, however, it instead determines the width of the border area.

+ +
/* <length> values */
+width: 300px;
+width: 25em;
+
+/* <percentage> value */
+width: 75%;
+
+/* Keyword values */
+width: 25em border-box;
+width: 75% content-box;
+width: max-content;
+width: min-content;
+width: available;
+width: fit-content;
+width: auto;
+
+/* Global values */
+width: inherit;
+width: initial;
+width: unset;
+
+ + + +
{{EmbedLiveSample("width", "100%", 660, "", "", "example-outcome-frame")}}
+ +
+

注意: {{cssxref("min-width")}} 和 {{cssxref("max-width")}} 會覆寫 {{cssxref("width")}}.

+
+ +
{{cssinfo}}
+ +

Syntax

+ +

The width property is specified as either:

+ + + +

Values

+ +
+
{{cssxref("<length>")}}
+
Defines the width as an absolute value.
+
{{cssxref("<percentage>")}}
+
Defines the width as a percentage of the containing block's width. If the width of the containing block depends on the width of the element, the resulting layout is undefined.
+
border-box {{experimental_inline}}
+
If present, the preceding {{cssxref("<length>")}} or {{cssxref("<percentage>")}} is applied to the element's border box.
+
content-box {{experimental_inline}}
+
If present, the preceding {{cssxref("<length>")}} or {{cssxref("<percentage>")}} is applied to the element's content box.
+
auto
+
The browser will calculate and select a width for the specified element.
+
fill {{experimental_inline}}
+
Use the fill-available inline size or fill-available block size, as appropriate to the writing mode.
+
max-content {{experimental_inline}}
+
The intrinsic preferred width.
+
min-content {{experimental_inline}}
+
The intrinsic minimum width.
+
available {{experimental_inline}}
+
The containing block width minus horizontal margin, border and padding.
+
fit-content {{experimental_inline}}
+
The larger of: +
    +
  • the intrinsic minimum width
  • +
  • the smaller of the intrinsic preferred width and the available width
  • +
+
+
+ +

Formal syntax

+ +
{{csssyntax}}
+ +

範例

+ +

預設寬度

+ +
p.goldie {
+  background: gold;
+}
+ +
<p class="goldie">The Mozilla community produces a lot of great software.</p>
+ +

{{EmbedLiveSample('Default_width', '500px', '64px')}}

+ +

像素和相對大小

+ +
.px_length {
+  width: 200px;
+  background-color: red;
+  color: white;
+  border: 1px solid black;
+}
+
+.em_length {
+  width: 20em;
+  background-color: white;
+  color: red;
+  border: 1px solid black;
+}
+
+ +
<div class="px_length">Width measured in px</div>
+<div class="em_length">Width measured in em</div>
+ +

{{EmbedLiveSample('Pixels_and_ems', '500px', '64px')}}

+ +

百分比

+ +
.percent {
+  width: 20%;
+  background-color: silver;
+  border: 1px solid red;
+}
+ +
<div class="percent">Width in percentage</div>
+ +

{{EmbedLiveSample('Percentage', '500px', '64px')}}

+ +

內容最大值

+ +
p.maxgreen {
+  background: lightgreen;
+  width: intrinsic;           /* Safari/WebKit uses a non-standard name */
+  width: -moz-max-content;    /* Firefox/Gecko */
+  width: -webkit-max-content; /* Chrome */
+}
+ +
<p class="maxgreen">The Mozilla community produces a lot of great software.</p>
+ +

{{EmbedLiveSample('max-content_2', '500px', '64px')}}

+ +

內容最小值

+ +
p.minblue {
+  background: lightblue;
+  width: -moz-min-content;    /* Firefox */
+  width: -webkit-min-content; /* Chrome */
+}
+ +
<p class="minblue">The Mozilla community produces a lot of great software.</p>
+ +

{{EmbedLiveSample('min-content_2', '500px', '155px')}}

+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('CSS3 Box', '#the-width-and-height-properties', 'width')}}{{Spec2('CSS3 Box')}}Added the max-content, min-content, available, fit-content, border-box, content-box keywords.
{{SpecName('CSS3 Transitions', '#animatable-css', 'width')}}{{Spec2('CSS3 Transitions')}}Lists width as animatable.
{{SpecName('CSS2.1', 'visudet.html#the-width-property', 'width')}}{{Spec2('CSS2.1')}}Precises on which element it applies to.
{{SpecName('CSS1', '#width', 'width')}}{{Spec2('CSS1')}}Initial definition.
{{SpecName('CSS3 Sizing', '#width-height-keywords', 'width')}}{{Spec2('CSS3 Sizing')}}Adds new sizing keywords for width and height.
+ +

瀏覽器相容性

+ + + +

{{Compat("css.properties.width")}}

+ +

參考

+ + diff --git a/files/zh-tw/web/demos_of_open_web_technologies/index.html b/files/zh-tw/web/demos_of_open_web_technologies/index.html new file mode 100644 index 0000000000..5baa250a38 --- /dev/null +++ b/files/zh-tw/web/demos_of_open_web_technologies/index.html @@ -0,0 +1,144 @@ +--- +title: Demos of open web technologies +slug: Web/Demos_of_open_web_technologies +tags: + - 影片 + - 網站 + - 網頁 + - 設計 +translation_of: Web/Demos_of_open_web_technologies +--- +

Mozilla 支援豐富、廣泛且扣人心弦的網路公開技術,並且我們鼓勵使用他們。這個頁面提供一些展示這些有趣技術的連結,包含那些曾經在 Demo Studio 有人氣的,但現在已經落伍了的技術。如果你知道有關於新的網路公開技術,不錯的展示或是應用程式,請將連結加到下方適合的區塊中。

+ +

2D 繪圖

+ +

Canvas

+ + + +

SVG

+ + + +

影片

+ + + +

3D 繪圖

+ +

WebGL

+ + + +

虛擬實境 ( Virtual Reality )

+ + + +

CSS

+ + + +

轉換 ( Transformations )

+ + + +

遊戲

+ + + +

HTML

+ + + +

Web APIs

+ + + +

提示工具的 API

+ + + + + +

網路 API

+ + + +

檔案的 API

+ + + +

Web Workers

+ + diff --git a/files/zh-tw/web/events/abort/index.html b/files/zh-tw/web/events/abort/index.html new file mode 100644 index 0000000000..a2d9d86059 --- /dev/null +++ b/files/zh-tw/web/events/abort/index.html @@ -0,0 +1,67 @@ +--- +title: abort +slug: Web/Events/abort +translation_of: Web/API/HTMLMediaElement/abort_event +--- +

當資源載入被拒絕時將會觸發abort事件。

+ +

一般資訊

+ +
+
規範
+
DOM L3
+
介面
+
若由使用者介面產生,為UIEvent,否則為Event。
+
是否向上(冒泡)
+
+
是否為可取消
+
+
目標對象
+
Element
+
預設行為
+
+
+ +

屬性

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
屬性型態描述
target {{readonlyInline}}EventTarget事件的目標對象 (DOM樹中最頂層的對象)。
type {{readonlyInline}}DOMString事件的型態。
bubbles {{readonlyInline}}Boolean事件是否向上冒泡。
cancelable {{readonlyInline}}Boolean事件是否能夠取消。
view {{readonlyInline}}WindowProxydocument.defaultView (該文檔(Document)的window)
detail {{readonlyInline}}long (float)0.
diff --git a/files/zh-tw/web/events/domcontentloaded/index.html b/files/zh-tw/web/events/domcontentloaded/index.html new file mode 100644 index 0000000000..0ec78423ec --- /dev/null +++ b/files/zh-tw/web/events/domcontentloaded/index.html @@ -0,0 +1,133 @@ +--- +title: DOMContentLoaded +slug: Web/Events/DOMContentLoaded +translation_of: Web/API/Window/DOMContentLoaded_event +--- +

DOMContentLoaded事件是當document被完整的讀取跟解析後就會被觸發,不會等待 stylesheets, 圖片和subframes完成讀取  (load事件可以用來作為判斷頁面已經完整讀取的方法).

+ +
+

Note: Stylesheet loads block script execution, 如果 <script> 被放在 <link rel="stylesheet" ...>後面的話, 須等到前面的stylesheet載入並完成解析,此時 DOMContentLoaded才會被觸發。

+
+ +

Speeding up

+ +

If you want DOM to get parsed as fast as possible after the user had requested the page, some things you could do is turn your JavaScript asynchronous and to optimize loading of stylesheets which if used as usual, slow down page load due to being loaded in parallel, "stealing" traffic from the main html document.

+ +

General info

+ +
+
Specification
+
HTML5
+
Interface
+
Event
+
Bubbles
+
Yes
+
Cancelable
+
Yes (although specified as a simple event that isn't cancelable)
+
Target
+
Document
+
Default Action
+
None.
+
+ +

屬性

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
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}}{{jsxref("Boolean")}}Whether the event normally bubbles or not.
cancelable {{readonlyInline}}{{jsxref("Boolean")}}Whether the event is cancellable or not.
+ +

瀏覽器相容性

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support0.2{{ CompatGeckoDesktop("1") }}9.09.03.1
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatVersionUnknown() }}{{ CompatGeckoMobile("1") }}{{ CompatUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

Bubbling for this event is supported by at least Gecko 1.9.2, Chrome 6, and Safari 4.

+ +

Cross-browser fallback

+ +

Internet Explorer 8 supports the <code>readystatechange</code> event, which can be used to detect that the DOM is ready. In earlier version of Internet Explorer, this state can be detected by regularily trying to execute <code>document.documentElement.doScroll("left");</code>, as this snippet will throw an error until the DOM is ready.

+ +

General-purpose JS libraries such as jQuery offer cross-browser methods to detect that the DOM is ready. There are also standalone scripts that offer this feature : contentloaded.js (supports only one listener) and jquery.documentReady.js (doesn't depend on jQuery, despite its name).

+ + + + diff --git a/files/zh-tw/web/events/index.html b/files/zh-tw/web/events/index.html new file mode 100644 index 0000000000..569afb05e4 --- /dev/null +++ b/files/zh-tw/web/events/index.html @@ -0,0 +1,1928 @@ +--- +title: Event reference +slug: Web/Events +tags: + - NeedsTag + - NeedsTranslation + - TopicStub +translation_of: Web/Events +--- +

事件為一些有趣事情,發生後會被傳出以通知code。每個事件被表示為一個根據{{domxref("Event")}}所定義的物件,且可能會有額外自訂欄位與(或)函式來描述發生了什麼事。事件可以表示從使用者互動到自動通知等渲染model所有的事情。

+ +

Events are sent to notify code of interesting things that have taken place. Each event is represented by an object which is based on the {{domxref("Event")}} interface, and may have additional custom fields and/or functions used to get additional information about what happened. Events can represent everything from basic user interactions to automated notifications of things happening in the rendering model.

+ +

This article offers a list of events that can be sent; some are standard events defined in official specifications, while others are events used internally by specific browsers; for example, Mozilla-specific events are listed so that add-ons can use them to interact with the browser.no

+ +

標準事件

+ +

以下事件是由官方的 Web 標準規範中所定義,且應適用於所有的瀏覽器。下面的清單將列出事件和其所有傳送給事件的物件的 interface (所以你可以看到每個事件需要提供哪些資料)以及事件的定義規範。

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
事件名稱事件類型規範觸發時機
{{event("abort")}}{{domxref("UIEvent")}}DOM L3The loading of a resource has been aborted.
abort{{domxref("ProgressEvent")}}Progress and XMLHttpRequestProgression has been terminated (not due to an error).
abort{{domxref("Event")}}IndexedDBA transaction has been aborted.
{{event("afterprint")}} {{gecko_minversion_inline("6")}}{{domxref("Event")}}HTML5The associated document has started printing or the print preview has been closed.
{{event("animationend")}}{{domxref("AnimationEvent")}}CSS AnimationsA CSS animation has completed.
{{event("animationiteration")}}{{domxref("AnimationEvent")}}CSS AnimationsA CSS animation is repeated.
{{event("animationstart")}}{{domxref("AnimationEvent")}}CSS AnimationsA CSS animation has started.
{{event("audioprocess")}}{{domxref("AudioProcessingEvent")}}{{SpecName('Web Audio API', '#AudioProcessingEvent', 'audioprocess')}}The input buffer of a {{domxref("ScriptProcessorNode")}} is ready to be processed.
{{event("beforeprint")}} {{gecko_minversion_inline("6")}}{{domxref("Event")}}HTML5The associated document is about to be printed or previewed for printing.
{{event("beforeunload")}}{{domxref("BeforeUnloadEvent")}}HTML5
{{event("beginEvent")}}{{domxref("TimeEvent")}}SVGA SMIL animation element begins.
blockedIndexedDBAn open connection to a database is blocking a versionchange transaction on the same database.
{{event("blur")}}{{domxref("FocusEvent")}}DOM L3An element has lost focus (does not bubble).
{{event("cached")}}{{domxref("Event")}}OfflineThe resources listed in the manifest have been downloaded, and the application is now cached.
{{event("canplay")}}{{domxref("Event")}}HTML5 mediaThe user agent can play the media, but estimates that not enough data has been loaded to play the media up to its end without having to stop for further buffering of content.
{{event("canplaythrough")}}{{domxref("Event")}}HTML5 mediaThe user agent can play the media, and estimates that enough data has been loaded to play the media up to its end without having to stop for further buffering of content.
{{event("change")}}{{domxref("Event")}}DOM L2, HTML5An element loses focus and its value changed since gaining focus.
{{event("chargingchange")}}{{domxref("Event")}}Battery statusThe battery begins or stops charging.
{{event("chargingtimechange")}}{{domxref("Event")}}Battery statusThe chargingTime attribute has been updated.
{{event("checking")}}{{domxref("Event")}}OfflineThe user agent is checking for an update, or attempting to download the cache manifest for the first time.
{{event("click")}}{{domxref("MouseEvent")}}DOM L3A pointing device button has been pressed and released on an element.
close{{domxref("Event")}}WebSocketA WebSocket connection has been closed.
{{event("compassneedscalibration")}}{{domxref("SensorEvent")}}OrientationThe compass used to obtain orientation data is in need of calibration.
{{event("compositionend")}}{{domxref("CompositionEvent")}}DOM L3The composition of a passage of text has been completed or canceled.
{{event("compositionstart")}}{{domxref("CompositionEvent")}}DOM L3The composition of a passage of text is prepared (similar to keydown for a keyboard input, but works with other inputs such as speech recognition).
{{event("compositionupdate")}}{{domxref("CompositionEvent")}}DOM L3A character is added to a passage of text being composed.
completeIndexedDBThe transaction successfully completed.
{{event("contextmenu")}}{{domxref("MouseEvent")}}HTML5The right button of the mouse is clicked (before the context menu is displayed).
{{event("copy")}}{{domxref("ClipboardEvent")}}ClipboardThe text selection has been added to the clipboard.
{{event("cut")}}{{domxref("ClipboardEvent")}}ClipboardThe text selection has been removed from the document and added to the clipboard.
{{event("dblclick")}}{{domxref("MouseEvent")}}DOM L3A pointing device button is clicked twice on an element.
{{event("devicehumidity")}}{{domxref("SensorEvent")}}SensorFresh data is available from a humidity sensor.
{{event("devicelight")}}{{domxref("SensorEvent")}}SensorFresh data is available from a light sensor.
{{event("devicemotion")}}{{domxref("SensorEvent")}}OrientationFresh data is available from a motion sensor.
{{event("devicenoise")}}{{domxref("SensorEvent")}}SensorFresh data is available from a noise sensor.
{{event("deviceorientation")}}{{domxref("SensorEvent")}}OrientationFresh data is available from an orientation sensor.
{{event("devicepressure")}}{{domxref("SensorEvent")}}SensorFresh data is available from a pressure sensor.
{{event("deviceproximity")}}{{domxref("SensorEvent")}}SensorFresh data is available from a proximity sensor (indicates an approximated distance between the device and a nearby object).
{{event("devicetemperature")}}{{domxref("SensorEvent")}}SensorFresh data is available from a temperature sensor.
{{event("dischargingtimechange")}}{{domxref("Event")}}Battery statusThe dischargingTime attribute has been updated.
DOMActivate {{deprecated_inline}}{{domxref("UIEvent")}}DOM L3A button, link or state changing element is activated (use {{event("click")}} instead).
DOMAttributeNameChanged {{deprecated_inline}}{{domxref("MutationNameEvent")}}DOM L3 RemovedThe name of an attribute changed (use mutation observers instead).
DOMAttrModified {{deprecated_inline}}{{domxref("MutationEvent")}}DOM L3The value of an attribute has been modified (use mutation observers instead).
DOMCharacterDataModified {{deprecated_inline}}{{domxref("MutationEvent")}}DOM L3A text or another CharacterData has changed (use mutation observers instead).
{{event("DOMContentLoaded")}}{{domxref("Event")}}HTML5The document has finished loading (but not its dependent resources).
DOMElementNameChanged {{deprecated_inline}}{{domxref("MutationNameEvent")}}DOM L3 RemovedThe name of an element changed (use mutation observers instead).
DOMFocusIn {{deprecated_inline}}{{domxref("FocusEvent")}}DOM L3An element has received focus (use {{event("focus")}} or {{event("focusin")}} instead).
DOMFocusOut {{deprecated_inline}}{{domxref("FocusEvent")}}DOM L3An element has lost focus (use {{event("blur")}} or {{event("focusout")}} instead).
DOMNodeInserted {{deprecated_inline}}{{domxref("MutationEvent")}}DOM L3A node has been added as a child of another node (use mutation observers instead).
DOMNodeInsertedIntoDocument {{deprecated_inline}}{{domxref("MutationEvent")}}DOM L3A node has been inserted into the document (use mutation observers instead).
DOMNodeRemoved {{deprecated_inline}}{{domxref("MutationEvent")}}DOM L3A node has been removed from its parent node (use mutation observers instead).
DOMNodeRemovedFromDocument {{deprecated_inline}}{{domxref("MutationEvent")}}DOM L3A node has been removed from the document (use mutation observers instead).
DOMSubtreeModified {{deprecated_inline}}{{domxref("MutationEvent")}}DOM L3A change happened in the document (use mutation observers instead).
{{event("downloading")}}{{domxref("Event")}}OfflineThe user agent has found an update and is fetching it, or is downloading the resources listed by the cache manifest for the first time.
{{event("drag")}}{{domxref("DragEvent")}}HTML5An element or text selection is being dragged (every 350ms).
{{event("dragend")}}{{domxref("DragEvent")}}HTML5A drag operation is being ended (by releasing a mouse button or hitting the escape key).
{{event("dragenter")}}{{domxref("DragEvent")}}HTML5A dragged element or text selection enters a valid drop target.
{{event("dragleave")}}{{domxref("DragEvent")}}HTML5A dragged element or text selection enters a valid drop target.
{{event("dragover")}}{{domxref("DragEvent")}}HTML5An element or text selection is being dragged over a valid drop target (every 350ms).
{{event("dragstart")}}{{domxref("DragEvent")}}HTML5The user starts dragging an element or text selection.
{{event("drop")}}{{domxref("DragEvent")}}HTML5An element is dropped on a valid drop target.
{{event("durationchange")}}{{domxref("Event")}}HTML5 mediaThe duration attribute has been updated.
{{event("emptied")}}{{domxref("Event")}}HTML5 mediaThe media has become empty; for example, this event is sent if the media has already been loaded (or partially loaded), and the load() method is called to reload it.
{{event("ended")}}{{domxref("Event")}}HTML5 mediaPlayback has stopped because the end of the media was reached.
{{event("ended_(Web_Audio)", "ended")}}{{domxref("Event")}}{{SpecName("Web Audio API")}}
{{event("endEvent")}}{{domxref("TimeEvent")}}SVGA SMIL animation element ends.
{{event("error")}}{{domxref("UIEvent")}}DOM L3A resource failed to load.
{{event("error")}}{{domxref("ProgressEvent")}}Progress and XMLHttpRequestProgression has failed.
{{event("error")}}{{domxref("Event")}}OfflineAn error occurred while downloading the cache manifest or updating the content of the application.
{{event("error")}}{{domxref("Event")}}WebSocketA WebSocket connection has been closed with prejudice (some data couldn't be sent for example).
{{event("error")}}{{domxref("Event")}}Server Sent EventsAn event source connection has been failed.
{{event("error")}}{{domxref("Event")}}IndexedDBA request caused an error and failed.
{{event("focus")}}{{domxref("FocusEvent")}}DOM L3An element has received focus (does not bubble).
{{event("focusin")}}{{domxref("FocusEvent")}}DOM L3An element is about to receive focus (bubbles).
{{event("focusout")}}{{domxref("FocusEvent")}}DOM L3An element is about to loose focus (bubbles).
{{event("fullscreenchange")}}{{domxref("Event")}}Full ScreenAn element was turned to fullscreen mode or back to normal mode.
{{event("fullscreenerror")}}{{domxref("Event")}}Full ScreenIt was impossible to switch to fullscreen mode for technical reasons or because the permission was denied.
{{event("gamepadconnected")}}{{domxref("GamepadEvent")}}GamepadA gamepad has been connected.
{{event("gamepaddisconnected")}}{{domxref("GamepadEvent")}}GamepadA gamepad has been disconnected.
{{event("hashchange")}}{{domxref("HashChangeEvent")}}HTML5The fragment identifier of the URL has changed (the part of the URL after the #).
{{event("input")}}{{domxref("Event")}}HTML5The value of an element changes or the content of an element with the attribute contenteditable is modified.
{{event("invalid")}}{{domxref("Event")}}HTML5A submittable element has been checked and doesn't satisfy its constraints.
{{event("keydown")}}{{domxref("KeyboardEvent")}}DOM L3A key is pressed down.
{{event("keypress")}}{{domxref("KeyboardEvent")}}DOM L3A key is pressed down and that key normally produces a character value (use input instead).
{{event("keyup")}}{{domxref("KeyboardEvent")}}DOM L3A key is released.
{{event("levelchange")}}{{domxref("Event")}}Battery statusThe level attribute has been updated.
{{event("load")}}{{domxref("UIEvent")}}DOM L3A resource and its dependent resources have finished loading.
load{{domxref("ProgressEvent")}}Progress and XMLHttpRequestProgression has been successful.
{{event("loadeddata")}}{{domxref("Event")}}HTML5 mediaThe first frame of the media has finished loading.
{{event("loadedmetadata")}}{{domxref("Event")}}HTML5 mediaThe metadata has been loaded.
{{event("loadend")}}{{domxref("ProgressEvent")}}Progress and XMLHttpRequestProgress has stopped (after "error", "abort" or "load" have been dispatched).
{{event("loadstart")}}{{domxref("ProgressEvent")}}Progress and XMLHttpRequestProgress has begun.
message{{domxref("MessageEvent")}}WebSocketA message is received through a WebSocket.
message{{domxref("MessageEvent")}}Web WorkersA message is received from a Web Worker.
message{{domxref("MessageEvent")}}Web MessagingA message is received from a child (i)frame or a parent window.
message{{domxref("MessageEvent")}}Server Sent EventsA message is received through an event source.
{{event("mousedown")}}{{domxref("MouseEvent")}}DOM L3A pointing device button (usually a mouse) is pressed on an element.
{{event("mouseenter")}}{{domxref("MouseEvent")}}DOM L3A pointing device is moved onto the element that has the listener attached.
{{event("mouseleave")}}{{domxref("MouseEvent")}}DOM L3A pointing device is moved off the element that has the listener attached.
{{event("mousemove")}}{{domxref("MouseEvent")}}DOM L3A pointing device is moved over an element.
{{event("mouseout")}}{{domxref("MouseEvent")}}DOM L3A pointing device is moved off the element that has the listener attached or off one of its children.
{{event("mouseover")}}{{domxref("MouseEvent")}}DOM L3A pointing device is moved onto the element that has the listener attached or onto one of its children.
{{event("mouseup")}}{{domxref("MouseEvent")}}DOM L3A pointing device button is released over an element.
{{event("noupdate")}}{{domxref("Event")}}OfflineThe manifest hadn't changed.
{{event("obsolete")}}{{domxref("Event")}}OfflineThe manifest was found to have become a 404 or 410 page, so the application cache is being deleted.
{{event("offline")}}{{domxref("Event")}}HTML5 offlineThe browser has lost access to the network.
{{event("online")}}{{domxref("Event")}}HTML5 offlineThe browser has gained access to the network (but particular websites might be unreachable).
open{{domxref("Event")}}WebSocketA WebSocket connection has been established.
open{{domxref("Event")}}Server Sent EventsAn event source connection has been established.
{{event("orientationchange")}}{{domxref("Event")}}Screen OrientationThe orientation of the device (portrait/landscape) has changed
{{event("pagehide")}}{{domxref("PageTransitionEvent")}}HTML5A session history entry is being traversed from.
{{event("pageshow")}}{{domxref("PageTransitionEvent")}}HTML5A session history entry is being traversed to.
{{event("paste")}}{{domxref("ClipboardEvent")}}ClipboardData has been transfered from the system clipboard to the document.
{{event("pause")}}{{domxref("Event")}}HTML5 mediaPlayback has been paused.
{{event("pointerlockchange")}}{{domxref("Event")}}Pointer LockThe pointer was locked or released.
{{event("pointerlockerror")}}{{domxref("Event")}}Pointer LockIt was impossible to lock the pointer for technical reasons or because the permission was denied.
{{event("play")}}{{domxref("Event")}}HTML5 mediaPlayback has begun.
{{event("playing")}}{{domxref("Event")}}HTML5 mediaPlayback is ready to start after having been paused or delayed due to lack of data.
{{event("popstate")}}{{domxref("PopStateEvent")}}HTML5A session history entry is being navigated to (in certain cases).
{{event("progress")}}{{domxref("ProgressEvent")}}Progress and XMLHttpRequestIn progress.
progress{{domxref("ProgressEvent")}}OfflineThe user agent is downloading resources listed by the manifest.
{{event("ratechange")}}{{domxref("Event")}}HTML5 mediaThe playback rate has changed.
{{event("readystatechange")}}{{domxref("Event")}}HTML5 and XMLHttpRequestThe readyState attribute of a document has changed.
{{event("repeatEvent")}}{{domxref("TimeEvent")}}SVGA SMIL animation element is repeated.
{{event("reset")}}{{domxref("Event")}}DOM L2, HTML5A form is reset.
{{event("resize")}}{{domxref("UIEvent")}}DOM L3The document view has been resized.
{{event("scroll")}}{{domxref("UIEvent")}}DOM L3The document view or an element has been scrolled.
{{event("seeked")}}{{domxref("Event")}}HTML5 mediaA seek operation completed.
{{event("seeking")}}{{domxref("Event")}}HTML5 mediaA seek operation began.
{{event("select")}}{{domxref("UIEvent")}}DOM L3Some text is being selected.
{{event("show")}}{{domxref("MouseEvent")}}HTML5A contextmenu event was fired on/bubbled to an element that has a contextmenu attribute
{{event("stalled")}}{{domxref("Event")}}HTML5 mediaThe user agent is trying to fetch media data, but data is unexpectedly not forthcoming.
{{event("storage")}}{{domxref("StorageEvent")}}Web StorageA storage area (localStorage or sessionStorage) has changed.
{{event("submit")}}{{domxref("Event")}}DOM L2, HTML5A form is submitted.
success{{domxref("Event")}}IndexedDBA request successfully completed.
{{event("suspend")}}{{domxref("Event")}}HTML5 mediaMedia data loading has been suspended.
{{event("SVGAbort")}}{{domxref("SVGEvent")}}SVGPage loading has been stopped before the SVG was loaded.
{{event("SVGError")}}{{domxref("SVGEvent")}}SVGAn error has occurred before the SVG was loaded.
{{event("SVGLoad")}}{{domxref("SVGEvent")}}SVGAn SVG document has been loaded and parsed.
{{event("SVGResize")}}{{domxref("SVGEvent")}}SVGAn SVG document is being resized.
{{event("SVGScroll")}}{{domxref("SVGEvent")}}SVGAn SVG document is being scrolled.
{{event("SVGUnload")}}{{domxref("SVGEvent")}}SVGAn SVG document has been removed from a window or frame.
{{event("SVGZoom")}}{{domxref("SVGZoomEvent")}}SVGAn SVG document is being zoomed.
{{event("timeout")}}{{domxref("ProgressEvent")}}XMLHttpRequest
{{event("timeupdate")}}{{domxref("Event")}}HTML5 mediaThe time indicated by the currentTime attribute has been updated.
{{event("touchcancel")}}{{domxref("TouchEvent")}}Touch EventsA touch point has been disrupted in an implementation-specific manners (too many touch points for example).
{{event("touchend")}}{{domxref("TouchEvent")}}Touch EventsA touch point is removed from the touch surface.
{{event("touchenter")}}{{domxref("TouchEvent")}}Touch Events RemovedA touch point is moved onto the interactive area of an element.
{{event("touchleave")}}{{domxref("TouchEvent")}}Touch Events RemovedA touch point is moved off the interactive area of an element.
{{event("touchmove")}}{{domxref("TouchEvent")}}Touch EventsA touch point is moved along the touch surface.
{{event("touchstart")}}{{domxref("TouchEvent")}}Touch EventsA touch point is placed on the touch surface.
{{event("transitionend")}}{{domxref("TransitionEvent")}}CSS TransitionsA CSS transition has completed.
{{event("unload")}}{{domxref("UIEvent")}}DOM L3The document or a dependent resource is being unloaded.
{{event("updateready")}}{{domxref("Event")}}OfflineThe resources listed in the manifest have been newly redownloaded, and the script can use swapCache() to switch to the new cache.
upgradeneededIndexedDBAn attempt was made to open a database with a version number higher than its current version. A versionchange transaction has been created.
{{event("userproximity")}}{{domxref("SensorEvent")}}SensorFresh data is available from a proximity sensor (indicates whether the nearby object is near the device or not).
versionchangeIndexedDBA versionchange transaction completed.
{{event("visibilitychange")}}{{domxref("Event")}}Page visibilityThe content of a tab has become visible or has been hidden.
{{event("volumechange")}}{{domxref("Event")}}HTML5 mediaThe volume has changed.
{{event("waiting")}}{{domxref("Event")}}HTML5 mediaPlayback has stopped because of a temporary lack of data.
{{event("wheel")}} {{gecko_minversion_inline("17")}}{{domxref("WheelEvent")}}DOM L3A wheel button of a pointing device is rotated in any direction.
+ +

非標準事件

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
事件名稱事件類型規範觸發時機
{{event("afterscriptexecute")}}{{domxref("Event")}}Mozilla SpecificA script has been executed.
{{event("beforescriptexecute")}}{{domxref("Event")}}Mozilla SpecificA script is about to be executed.
{{event("cardstatechange")}}Firefox OS specificThe {{domxref("MozMobileConnection.cardState")}} property changes value.
{{event("connectionInfoUpdate")}}Firefox OS specificThe informations about the signal strength and the link speed have been updated.
{{event("cfstatechange")}}Firefox OS specificThe call forwarding state changes.
{{event("datachange")}}Firefox OS specificThe {{domxref("MozMobileConnection.data")}} object changes values.
{{event("dataerror")}}Firefox OS specificThe {{domxref("MozMobileConnection.data")}} object receive an error from the RIL.
{{event("DOMMouseScroll")}} {{deprecated_inline}}Mozilla specificThe wheel button of a pointing device is rotated (detail attribute is a number of lines). (use {{event("wheel")}} instead)
dragdrop {{deprecated_inline}}DragEventMozilla specificAn element is dropped (use {{event("drop")}} instead).
dragexit {{deprecated_inline}}DragEventMozilla specificA drag operation is being ended(use {{event("dragend")}} instead).
draggesture {{deprecated_inline}}DragEventMozilla specificThe user starts dragging an element or text selection (use {{event("dragstart")}} instead).
{{event("icccardlockerror")}}Firefox OS specificthe {{domxref("MozMobileConnection.unlockCardLock()")}} or {{domxref("MozMobileConnection.setCardLock()")}} methods fails.
{{event("iccinfochange")}}Firefox OS specificThe {{domxref("MozMobileConnection.iccInfo")}} object changes.
{{event("localized")}}Mozilla SpecificThe page has been localized using data-l10n-* attributes.
{{event("mousewheel")}} {{deprecated_inline}}IE inventedThe wheel button of a pointing device is rotated.
{{event("MozAudioAvailable")}}{{domxref("Event")}}Mozilla specificThe audio buffer is full and the corresponding raw samples are available.
{{event("MozGamepadAxisMove")}}To be specifiedA gampad axis is moving.
{{event("MozGamepadButtonDown")}}To be specifiedA gamepad button is pressed down.
{{event("MozGamepadButtonUp")}}To be specifiedA gamepad button is released.
{{event("MozMousePixelScroll")}} {{deprecated_inline}}Mozilla specificThe wheel button of a pointing device is rotated (detail attribute is a number of pixels). (use wheel instead)
{{event("MozOrientation")}} {{deprecated_inline}}Mozilla specificFresh data is available from an orientation sensor (see deviceorientation).
{{event("MozScrolledAreaChanged")}}{{domxref("UIEvent")}}Mozilla specificThe document view has been scrolled or resized.
{{event("moztimechange")}}Mozilla specificThe time of the device has been changed.
MozTouchDown {{deprecated_inline}}Mozilla specificA touch point is placed on the touch surface (use touchstart instead).
MozTouchMove {{deprecated_inline}}Mozilla specificA touch point is moved along the touch surface (use touchmove instead).
MozTouchUp {{deprecated_inline}}Mozilla specificA touch point is removed from the touch surface (use touchend instead).
onalerting{{domxref("CallEvent")}}To be specifiedThe correspondent is being alerted (his/her phone is ringing).
onbusy{{domxref("CallEvent")}}To be specifiedThe line of the correspondent is busy.
oncallschanged{{domxref("CallEvent")}}To be specifiedA call has been added or removed from the list of current calls.
onconnected{{domxref("CallEvent")}}To be specifiedA call has been connected.
onconnecting{{domxref("CallEvent")}}To be specifiedA call is about to connect.
ondelivered{{domxref("SMSEvent")}}To be specifiedAn SMS has been successfully delivered.
ondialing{{domxref("CallEvent")}}To be specifiedThe number of a correspondent has been dialed.
{{event("ondisabled")}}Firefox OS specificWifi has been disabled on the device.
ondisconnected{{domxref("CallEvent")}}To be specifiedA call has been disconnected.
ondisconnecting{{domxref("CallEvent")}}To be specifiedA call is about to disconnect.
{{event("onenabled")}}Firefox OS specificWifi has been enabled on the device.
onerror{{domxref("CallEvent")}}To be specifiedAn error occurred.
onheld{{domxref("CallEvent")}}To be specifiedA call has been held.
onholding{{domxref("CallEvent")}}To be specifiedA call is about to be held.
onincoming{{domxref("CallEvent")}}To be specifiedA call is being received.
onreceived{{domxref("SMSEvent")}}To be specifiedAn SMS has been received.
onresuming{{domxref("CallEvent")}}To be specifiedA call is about to resume.
onsent{{domxref("SMSEvent")}}To be specifiedAn SMS has been sent.
onstatechange{{domxref("CallEvent")}}To be specifiedThe state of a call has changed.
onstatuschangeFirefox OS specificThe status of the Wifi connection changed.
{{event("overflow")}}{{domxref("UIEvent")}}Mozilla specificAn element has been overflowed by its content or has been rendered for the first time in this state (only works for elements styled with overflow != visible).
{{event("smartcard-insert")}}Mozilla specificA smartcard has been inserted.
{{event("smartcard-remove")}}Mozilla specificA smartcard has been removed.
{{event("stkcommand")}}Firefox OS specificThe STK Proactive Command is issued from ICC.
{{event("stksessionend")}}Firefox OS specificThe STK Session is terminated by ICC.
textMozilla SpecificA generic composition event occurred.
{{event("underflow")}}"{{domxref("UIEvent")}}Mozilla specificAn element is no longer overflowed by its content (only works for elements styled with overflow != visible).
uploadprogress {{deprecated_inline}}{{domxref("ProgressEvent")}}Mozilla SpecificUpload is in progress (see {{event("progress")}}).
{{event("ussdreceived")}}Firefox OS specificA new USSD message is received
{{event("voicechange")}}Firefox OS specificThe {{domxref("MozMobileConnection.voice")}} object changes values.
+ +

Mozilla 專屬事件

+ +
+

Note: 以下事件從未在網頁上觸發。它們僅在能在 chrome content context 上使用。

+
+ +

XUL 事件

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
事件名稱事件類型規範觸發時機
{{event("broadcast")}}XULAn observer noticed a change to the attributes of a watched broadcaster.
{{event("CheckboxStateChange")}}XULThe state of a checkbox has been changed either by a user action or by a script (useful for accessibility).
closeXULThe close button of the window has been clicked.
{{event("command")}}XULAn element has been activated.
{{event("commandupdate")}}XULA command update occurred on a commandset element.
{{event("DOMMenuItemActive")}}XULA menu or menuitem has been hovered or highlighted.
{{event("DOMMenuItemInactive")}}XULA menu or menuitem is no longer hovered or highlighted.
{{event("popuphidden")}}PopupEventXULA menupopup, panel or tooltip has been hidden.
{{event("popuphiding")}}PopupEventXULA menupopup, panel or tooltip is about to be hidden.
{{event("popupshowing")}}PopupEventXULA menupopup, panel or tooltip is about to become visible.
{{event("popupshown")}}PopupEventXULA menupopup, panel or tooltip has become visible.
{{event("RadioStateChange")}}XULThe state of a radio has been changed either by a user action or by a script (useful for accessibility).
{{event("ValueChange")}}XULThe value of an element has changed (a progress bar for example, useful for accessibility).
+ +

附加元件專屬事件

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
事件名稱事件類型規範觸發時機
MozSwipeGestureAddons specificA touch point is swiped across the touch surface
MozMagnifyGestureStartAddons specificTwo touch points start to move away from each other.
MozMagnifyGestureUpdateAddons specificTwo touch points move away from each other (after a MozMagnifyGestureStart).
MozMagnifyGestureAddons specificTwo touch points moved away from each other (after a sequence of MozMagnifyGestureUpdate).
MozRotateGestureStartAddons specificTwo touch points start to rotate around a point.
MozRotateGestureUpdateAddons specificTwo touch points rotate around a point (after a MozRotateGestureStart).
MozRotateGestureAddons specificTwo touch points rotate around a point (after a sequence of MozRotateGestureUpdate).
MozTapGestureAddons specificTwo touch points are tapped on the touch surface.
MozPressTapGestureAddons specificA "press-tap" gesture happened on the touch surface (first finger down, second finger down, second finger up, first finger up).
MozEdgeUIGestureAddons specificA touch point is swiped across the touch surface to invoke the edge UI (Win8 only).
MozAfterPaintAddons specificContent has been repainted.
MozBeforeResizeAddons specificA window is about to be resized.
DOMPopupBlockedAddons specificA popup has been blocked
DOMWindowCreatedAddons specificA window has been created.
DOMWindowCloseAddons specificA window is about to be closed.
DOMTitleChangedAddons specifcThe title of a window has changed.
DOMLinkAddedAddons specifcA link has been added a document.
DOMLinkRemovedAddons specifcA link has been removed inside from a document.
DOMMetaAddedAddons specificA meta element has been added to a document.
DOMMetaRemovedAddons specificA meta element has been removed from a document.
DOMWillOpenModalDialogAddons specificA modal dialog is about to open.
DOMModalDialogClosedAddons specificA modal dialog has been closed.
DOMAutoCompleteAddons specificThe content of an element has been auto-completed.
DOMFrameContentLoadedAddons specificThe frame has finished loading (but not its dependent resources).
AlertActiveAddons specificA notification element is shown.
AlertCloseAddons specificA notification element is closed.
fullscreenAddons specificBrowser fullscreen mode has been entered or left.
sizemodechangeAddons specificWindow has entered/left fullscreen mode, or has been minimized/unminimized.
MozEnteredDomFullscreenAddons specificDOM fullscreen mode has been entered.
SSWindowClosingAddons specificThe session store will stop tracking this window.
SSTabClosingAddons specificThe session store will stop tracking this tab.
SSTabRestoringAddons specificA tab is about to be restored.
SSTabRestoredAddons specificA tab has been restored.
SSWindowStateReadyAddons specificA window state has switched to "ready".
SSWindowStateBusyAddons specificA window state has switched to "busy".
tabviewsearchenabledAddons specificThe search feature of Panorama has been activated
tabviewsearchdisabledAddons specificThe search feature of Panorama has been deactivated
tabviewframeinitializedAddons specificThe frame container of Panorama has been initialized
tabviewshownAddons specificThe Panorama tab has been shown
tabviewhiddenAddons specificThe Panorama tab has been hidden
TabOpenAddons specificA tab has been opened.
TabCloseAddons specificA tab has been closed.
TabSelectAddons specificA tab has been selected.
TabShowAddons specificA tab has been shown.
TabHideAddons specificA tab has been hidden.
TabPinnedAddons specificA tab has been pinned.
TabUnpinnedAddons specificA tab has been unpinned.
+ +

開發者工具(Developer tool )專屬事件

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
事件名稱事件類型規範觸發時機
CssRuleViewRefresheddevtools specificThe "Rules" view of the style inspector has been updated.
CssRuleViewChangeddevtools specificThe "Rules" view of the style inspector has been changed.
CssRuleViewCSSLinkClickeddevtools specificA link to a CSS file has been clicked in the "Rules" view of the style inspector.
+ +

事件分類

+ +

動畫事件(Animation events)

+ +

{{event("animationend")}}, {{event("animationiteration")}}, {{event("animationstart")}}, {{event("beginEvent")}}, {{event("endEvent")}}, {{event("repeatEvent")}}

+ +

電池相關事件(Battery events)

+ +

{{event("chargingchange")}} {{event("chargingtimechange")}}, {{event("dischargingtimechange")}} {{event("levelchange")}}

+ +

電話事件(Call events)

+ +

{{event("alerting")}}, {{event("busy")}}, {{event("callschanged")}} {{event("cfstatechange")}}, {{event("connected")}}, {{event("connecting")}}, {{event("dialing")}}, {{event("disconnected")}}, {{event("disconnecting")}}, {{event("error_(Telephony)","error")}}, {{event("held")}}, {{event("holding")}}, {{event("incoming")}}, {{event("resuming")}}, {{event("statechange")}}, {{event("voicechange")}}

+ +

CSS 事件

+ +

CssRuleViewRefreshedCssRuleViewChangedCssRuleViewCSSLinkClicked, {{event("transitionend")}}

+ +

資料庫事件

+ +

abortblockedcomplete, {{event("error")}} (link), successupgradeneededversionchange

+ +

Document 事件

+ +

DOMLinkAddedDOMLinkRemovedDOMMetaAddedDOMMetaRemoved,DOMWillOpenModalDialogDOMModalDialogClosed, {{event("unload")}}

+ +

DOM mutation events

+ +

DOMAttributeNameChangedDOMAttrModifiedDOMCharacterDataModified, {{event("DOMContentLoaded")}}, DOMElementNameChangedDOMNodeInserted,DOMNodeInsertedIntoDocumentDOMNodeRemovedDOMNodeRemovedFromDocument,DOMSubtreeModified

+ +

拖曳事件

+ +

{{event("drag")}}, dragdrop, {{event("dragend")}}, {{event("dragenter")}}, dragexitdraggesture, {{event("dragleave")}}, {{event("dragover")}}, {{event("dragstart")}}, {{event("drop")}}

+ +

元素相關事件

+ +

{{event("invalid")}}, {{event("overflow")}}, {{event("underflow")}}, DOMAutoComplete, {{event("command")}}, {{event("commandupdate")}}

+ +

Focus events

+ +

{{event("blur")}}, {{event("change")}}, DOMFocusInDOMFocusOut, {{event("focus")}}, {{event("focusin")}}, {{event("focusout")}}

+ +

表單相關事件

+ +

{{event("reset")}}, {{event("submit")}}

+ +

Frame 相關事件

+ +

{{event("mozbrowserclose")}}, {{event("mozbrowsercontextmenu")}}, {{event("mozbrowsererror")}}, {{event("mozbrowsericonchange")}}, {{event("mozbrowserlocationchange")}}, {{event("mozbrowserloadend")}}, {{event("mozbrowserloadstart")}}, {{event("mozbrowseropenwindow")}}, {{event("mozbrowsersecuritychange")}}, {{event("mozbrowsershowmodalprompt")}} (link), {{event("mozbrowsertitlechange")}}, DOMFrameContentLoaded

+ +

Input device events

+ +

{{event("click")}}, {{event("contextmenu")}}, {{event("DOMMouseScroll")}}, {{event("dblclick")}}, {{event("gamepadconnected")}}, {{event("gamepaddisconnected")}}, {{event("keydown")}}, {{event("keypress")}}, {{event("keyup")}}, {{event("MozGamepadButtonDown")}}, {{event("MozGamepadButtonUp")}}, {{event("mousedown")}}, {{event("mouseenter")}}, {{event("mouseleave")}}, {{event("mousemove")}}, {{event("mouseout")}}, {{event("mouseover")}}, {{event("mouseup")}}, {{event("mousewheel")}}, {{event("MozMousePixelScroll")}}, {{event("pointerlockchange")}}, {{event("pointerlockerror")}},{{event("wheel")}}

+ +

多媒體事件

+ +

{{event("audioprocess")}}, {{event("canplay")}}, {{event("canplaythrough")}}, {{event("durationchange")}}, {{event("emptied")}}, {{event("ended")}}, {{event("ended_(Web_Audio)", "ended")}}, {{event("loadeddata")}}, {{event("loadedmetadata")}}, {{event("MozAudioAvailable")}}, {{event("pause")}}, {{event("play")}}, {{event("playing")}}, {{event("ratechange")}}, {{event("seeked")}}, {{event("seeking")}}, {{event("stalled")}}, {{event("suspend")}}, {{event("timeupdate")}}, {{event("volumechange")}}, {{event("waiting")}}, {{event("complete")}}

+ +

目錄事件

+ +

{{event("DOMMenuItemActive")}}, {{event("DOMMenuItemInactive")}}

+ +

網路相關事件

+ +

{{event("datachange")}}, {{event("dataerror")}}, {{event("disabled")}}, {{event("enabled")}}, {{event("offline")}}, {{event("online")}}, {{event("statuschange")}}, {{event("connectionInfoUpdate")}},

+ +

Notification events

+ +

AlertActiveAlertClose

+ +

Pointer events

+ +

{{event("pointerover")}}, {{event("pointerenter")}}, {{event("pointerdown")}}, {{event("pointermove")}}, {{event("pointerup")}}, {{event("pointercancel")}}, {{event("pointerout")}}, {{event("pointerleave")}}, {{event("gotpointercapture")}}, {{event("lostpointercapture")}}

+ + + +

{{event("popuphidden")}}, {{event("popuphiding")}}, {{event("popupshowing")}}, {{event("popupshown")}}, DOMPopupBlocked

+ +

列印相關事件

+ +

{{event("afterprint")}}, {{event("beforeprint")}}

+ +

Progress events

+ +

abort, {{event("error")}}, load, {{event("loadend")}}, {{event("loadstart")}}, {{event("progress")}},progress, {{event("timeout")}}, uploadprogress

+ +

Resource events

+ +

{{event("abort")}}, {{event("cached")}}, {{event("error")}}, {{event("load")}}

+ +

Script events

+ +

{{event("afterscriptexecute")}}, {{event("beforescriptexecute")}}

+ +

Sensor events

+ +

{{event("compassneedscalibration")}}, {{event("devicelight")}}, {{event("devicemotion")}}, {{event("deviceorientation")}}, {{event("deviceproximity")}}, {{event("MozOrientation")}}, {{event("orientationchange")}}, {{event("userproximity")}}

+ +

Session history events

+ +

{{event("pagehide")}}, {{event("pageshow")}}, {{event("popstate")}}

+ +

Smartcard events

+ +

{{event("icccardlockerror")}}, {{event("iccinfochange")}}, {{event("smartcard-insert")}}, {{event("smartcard-remove")}}, {{event("stkcommand")}}, {{event("stksessionend")}}, {{event("cardstatechange")}}

+ +

SMS and USSD events

+ +

{{event("delivered")}}, {{event("received")}}, {{event("sent")}}, {{event("ussdreceived")}}

+ +

Storage events

+ +

{{event("change")}} (see {{anch("Non-standard events")}}), {{event("storage")}}

+ +

SVG 事件

+ +

{{event("SVGAbort")}}, {{event("SVGError")}}, {{event("SVGLoad")}}, {{event("SVGResize")}}, {{event("SVGScroll")}}, {{event("SVGUnload")}}, {{event("SVGZoom")}}

+ +

Tab events

+ +

tabviewsearchenabledtabviewsearchdisabledtabviewframeinitializedtabviewshown,tabviewhiddenTabOpenTabCloseTabSelectTabShowTabHideTabPinnedTabUnpinned,SSTabClosingSSTabRestoringSSTabRestored, {{event("visibilitychange")}}

+ +

Text events

+ +

{{event("compositionend")}}, {{event("compositionstart")}}, {{event("compositionupdate")}}, {{event("copy")}}, {{event("cut")}}, {{event("paste")}}, {{event("select")}}, text

+ +

Touch events

+ +

MozEdgeUIGestureMozMagnifyGestureMozMagnifyGestureStartMozMagnifyGestureUpdate,MozPressTapGestureMozRotateGestureMozRotateGestureStartMozRotateGestureUpdate,MozSwipeGestureMozTapGestureMozTouchDownMozTouchMoveMozTouchUp, {{event("touchcancel")}}, {{event("touchend")}}, {{event("touchenter")}}, {{event("touchleave")}}, {{event("touchmove")}}, {{event("touchstart")}}

+ +

Update events

+ +

{{event("checking")}}, {{event("downloading")}}, {{event("error")}}, {{event("noupdate")}}, {{event("obsolete")}}, {{event("updateready")}}

+ +

Value change events

+ +

{{event("broadcast")}}, {{event("CheckboxStateChange")}}, {{event("hashchange")}}, {{event("input")}}, {{event("RadioStateChange")}}, {{event("readystatechange")}}, {{event("ValueChange")}}

+ +

View events

+ +

fullscreen, {{event("fullscreenchange")}}, {{event("fullscreenerror")}}, MozEnteredDomFullscreen, {{event("MozScrolledAreaChanged")}}, {{event("resize")}}, {{event("scroll")}}, sizemodechange

+ +

Websocket 事件

+ +

close, {{event("error")}}, messageopen

+ +

Window events

+ +

DOMWindowCreatedDOMWindowCloseDOMTitleChangedMozBeforeResize {{obsolete_inline}},SSWindowClosingSSWindowStateReadySSWindowStateBusyclose

+ +

尚未分類的事件

+ +

{{event("beforeunload")}}, {{event("localized")}}, messagemessagemessageMozAfterPaint, {{event("moztimechange")}}, open, {{event("show")}}

+ +

延伸閱讀

+ + diff --git a/files/zh-tw/web/events/load/index.html b/files/zh-tw/web/events/load/index.html new file mode 100644 index 0000000000..7c6d314925 --- /dev/null +++ b/files/zh-tw/web/events/load/index.html @@ -0,0 +1,88 @@ +--- +title: load +slug: Web/Events/load +translation_of: Web/API/Window/load_event +--- +

load 事件發生在加載完目標資源、該資源依賴的其他資源時。

+ +

一般資訊

+ +
+
規範
+
DOM L3
+
介面
+
UIEvent
+
起泡事件
+
No
+
可取消
+
No
+
對象
+
Window
+
預設行為
+
None.
+
+ +

屬性

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

範例

+ +
<script>
+  window.addEventListener("load", function(event) {
+    console.log("All resources finished loading!");
+  });
+</script>
+
+ +

 

+ +

相關事件

+ + diff --git a/files/zh-tw/web/guide/ajax/getting_started/index.html b/files/zh-tw/web/guide/ajax/getting_started/index.html new file mode 100644 index 0000000000..7e27c1ebac --- /dev/null +++ b/files/zh-tw/web/guide/ajax/getting_started/index.html @@ -0,0 +1,287 @@ +--- +title: 入門篇 +slug: Web/Guide/AJAX/Getting_Started +tags: + - AJAX + - API + - Advanced + - JavaScript + - WebMechanics + - XMLHttpRequest +translation_of: Web/Guide/AJAX/Getting_Started +--- +

這篇文章說明 AJAX 相關技術的基礎,並提供兩個簡單的實際操作範例供您入門。

+ +

AJAX 是什麼?

+ +

AJAX 代表 Asynchronous JavaScript And XML,即非同步 JavaScript 及 XML。簡單地說,AJAX 使用 {{domxref("XMLHttpRequest")}} 物件來與伺服器進行通訊。它可以傳送並接收多種格式的資訊,包括 JSON、XML、HTML、以及文字檔案。AJAX 最吸引人的特點是「非同步」的本質,這代表它可以與伺服溝通、交換資料、以及更新頁面,且無須重整網頁。

+ +

有兩項即將討論到的特點如下︰

+ + + +

第一步 – 如何發出 HTTP 請求

+ +

為了使用 JavaScript 向伺服器發送 HTTP 請求,便需要一個能夠提供相關功能的類別實體(an instance of a class)。這樣的類別最初由 Internet Explorer 以 ActiveX 物件的方式引入,稱為 XMLHTTP。Mozilla、Safari 及其他瀏覽器則隨後跟進,實作了 XMLHttpRequest 類別,以提供微軟最初的 ActiveX 物件中的方法及屬性。

+ +

因此,為了建立能夠跨瀏覽器的物件實體,可以這麼寫:

+ +
// Old compatibility code, no longer needed.
+if (window.XMLHttpRequest) { // Mozilla, Safari, IE7+ ...
+    httpRequest = new XMLHttpRequest();
+} else if (window.ActiveXObject) { // IE 6 and older
+    httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
+}
+
+ +
備註:出於解說上的需要,上述代碼使用最簡方式建立 XMLHTTP 的實體。較貼近實際運用的範例,見第三步。
+ +

部分版本的 Mozilla 瀏覽器,在伺服器送回的資料未含 XML mime-type 標頭(header)時會出錯。為了避免這個問題,你可以用下列方法覆寫伺服器傳回的檔頭,以免傳回的不是 text/xml

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

接下來是要決定伺服器傳回資料後的處理方式,此時你只要以 onreadystatechange 這個屬性指明要處理傳回值的 JavaScript 函式名稱即可,例如:

+ +
httpRequest.onreadystatechange = nameOfTheFunction;
+ +

注意,指定的函式名稱後不加括號也沒有參數。這只是簡單的賦值,而非真的呼叫函數。除了指定函式名稱外,你也能用 Javascript 即時定義函式的技巧(稱為〝匿名函數〞)來定一個新的處理函式,如下:

+ +
httpRequest.onreadystatechange = function(){
+    // 做些事
+};
+
+ +

決定處理方式之後你得確實發出 request,此時需叫用 HTTP request 類別的 open()send() 方法,如下:

+ +
httpRequest.open('GET', 'http://www.example.org/some.file', true);
+httpRequest.send();
+
+ + + +

send() 的參數在以 POST 發出 request 時,可以是任何想傳給伺服器的東西,而資料則以查詢字串的方式列出,例如:

+ +
"name=value&anothername="+encodeURIComponent(myVar)+"&so=on"
+ +

不過如果你想要以 POST 方式傳送資料,則必須先將 MIME 型態改好,如下:

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

否則伺服器就不會理你傳過來的資料了。

+ +

第二步 – 處理伺服器傳回的資料

+ +

傳出 request 時必須提供處理傳回值的函數名稱,這個函數是用來處理伺服器的回應。

+ +
httpRequest.onreadystatechange = nameOfTheFunction;
+
+ +

那麼來看看這個函數該做些什麼。首先,它必須檢查 request 目前的狀態。如果狀態值為 4 代表伺服器已經傳回所有資訊了,便可以開始解析所得資訊。

+ +
if (httpRequest.readyState === XMLHttpRequest.DONE) {
+    // 一切 ok, 繼續解析
+} else {
+    // 還沒完成
+}
+
+ +

readyState 所有可能的值如下:

+ + + +

資料來源:MSDN

+ +

接下來要檢查伺服器傳回的 HTTP 狀態碼。所有狀態碼列表可於 W3C 網站上查到,但我們要管的是 200 OK 這種狀態。

+ +
if (httpRequest.status === 200) {
+    // 萬事具備
+} else {
+    // 似乎有點問題。
+    // 或許伺服器傳回了 404(查無此頁)
+    // 或者 500(內部錯誤)什麼的。
+}
+
+ +

檢查傳回的 HTTP 狀態碼後,要怎麼處理傳回的資料就由你決定了。有兩種存取資料的方式:

+ + + +

第三步 – 簡單範例

+ +

好,接著就做一次簡單的 HTTP 範例,演示方才的各項技巧。這段 JavaScript 會向伺服器要一份裡頭有「I'm a test.」字樣的 HTML 文件(test.html),而後以 alert() 將文件內容列出。

+ +
<button id="ajaxButton" type="button">Make a request</button>
+
+<script>
+(function() {
+  var httpRequest;
+  document.getElementById("ajaxButton").addEventListener('click', makeRequest);
+
+  function makeRequest() {
+    httpRequest = new XMLHttpRequest();
+
+    if (!httpRequest) {
+      alert('Giving up :( Cannot create an XMLHTTP instance');
+      return false;
+    }
+    httpRequest.onreadystatechange = alertContents;
+    httpRequest.open('GET', 'test.html');
+    httpRequest.send();
+  }
+
+  function alertContents() {
+    if (httpRequest.readyState === XMLHttpRequest.DONE) {
+      if (httpRequest.status === 200) {
+        alert(httpRequest.responseText);
+      } else {
+        alert('There was a problem with the request.');
+      }
+    }
+  }
+})();
+</script>
+
+ +

在此範例中:

+ + + +

你可以由此測試本例,也可以參考測試檔案

+ +
Note:如果你傳送一個要求到一段代碼,而這段代碼將回應XML而非靜態的HTML檔,那則必須要設定一個可以在IE中運作的header。如果我們不設定header  Content-Type: application/xml,IE將會在我們試圖運作的XML項目行下,回應一個"Object Expected" 的錯誤。
+ +
Note 2: 如果我們沒有設定header Cache-Control: no-cache,那瀏覽器將會藏匿response並且不再重新傳送request,造成除錯上的挑戰。我們也可以增加一個 always-different GET 參數,像是 timestamp 或 random number (詳見bypassing the cache)
+ +
Note 3: If the httpRequest variable is used globally, competing functions calling makeRequest() can overwrite each other, causing a race condition. Declaring the httpRequest variable local to a closure containing the AJAX functions avoids this.
+ +

In the event of a communication error (such as the server going down), an exception will be thrown in the onreadystatechange method when accessing the response status. To mitigate this problem, you could wrap your if...then statement in a try...catch:

+ +
function alertContents() {
+  try {
+    if (httpRequest.readyState === XMLHttpRequest.DONE) {
+      if (httpRequest.status === 200) {
+        alert(httpRequest.responseText);
+      } else {
+        alert('There was a problem with the request.');
+      }
+    }
+  }
+  catch( e ) {
+    alert('Caught Exception: ' + e.description);
+  }
+}
+
+ +

第四步 – 運用 XML 資料

+ +

前面的例子中,在收到 HTTP 傳回值後我們以物件的 reponseText 屬性接收 test.html 檔案的內容,接著來試試 responseXML 屬性。

+ +

首先,我們得做個格式正確的 XML 文件以便稍後取用。文件 (test.xml) 內容如下:

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

在程式中,我們叫用檔案的地方只須略事修改如下:

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

接著在 alertContents() 中,我們把 alert(http_request.responseText); 改成這樣:

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

這樣一來我們便可取得 responseXML 所傳回的 XMLDocument 物件,而後以 DOM 方法取用 XML 文件的內容。你可以參考 test.xml 的原始碼 以及修改過後的測試程式

+ +

關於 DOM 方法,請參考 Mozilla DOM 文件。

+ +

Step 5 – Working with data

+ +

Finally, let's send some data to the server and receive a response. Our JavaScript will request a dynamic page this time, test.php, which will take the data we send and return a "computed" string - "Hello, [user data]!" - which we'll alert().

+ +

First we'll add a text box to our HTML so the user can enter their name:

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

We'll also add a line to our event handler to get the user's data from the text box and send it to the makeRequest() function along with the URL of our server-side script:

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

We need to modify makeRequest() to accept the user data and pass it along to the server. We'll change the request method from GET to POST, and include our data as a parameter in the call to httpRequest.send():

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

The function alertContents() can be written the same way it was in Step 3 to alert our computed string, if that's all the server returns. However, let's say the server is going to return both the computed string and the original user data. So if our user typed "Jane" in the text box, the server's response would look like this:

+ +

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

+ +

To use this data within alertContents(), we can't just alert the responseText, we have to parse it and alert computedString, the property we want:

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

The test.php file should contain the following:

+ +
$name = (isset($_POST['userName'])) ? $_POST['userName'] : 'no name';
+$computedString = "Hi, " . $name;
+$array = ['userName' => $name, 'computedString' => $computedString];
+echo json_encode($array);
+ +

For more on DOM methods, be sure to check Mozilla's DOM implementation documents.

diff --git a/files/zh-tw/web/guide/ajax/index.html b/files/zh-tw/web/guide/ajax/index.html new file mode 100644 index 0000000000..8e6a49698f --- /dev/null +++ b/files/zh-tw/web/guide/ajax/index.html @@ -0,0 +1,119 @@ +--- +title: Ajax +slug: Web/Guide/AJAX +translation_of: Web/Guide/AJAX +--- +
入門篇
+Ajax 簡介。
+ +
+

非同步 JavaScript 及 XML(Asynchronous JavaScript and XML,AJAX) 並不能稱做是種「技術」,而是 2005 年時由 Jesse James Garrett 所發明的術語,描述一種使用數個既有技術的「新」方法。這些技術包括 HTMLXHTML層疊樣式表JavaScript文件物件模型XMLXSLT 以及最重要的 XMLHttpRequest 物件
+ 當這些技術被結合在 Ajax 模型中,Web 應用程式便能快速、即時更動介面及內容,不需要重新讀取整個網頁,讓程式更快回應使用者的操作。

+ +

雖然 X 在 Ajax 中代表 XML,但由於 JSON 的許多優點,如輕量以及其本身就是 JavaScript 的一部分等,讓現今 JSON 比起 XML 被更廣泛的使用。JSON 與 XML 兩者都被用來在 Ajax 模型中包裝資訊。

+
+ +
+
+

文件

+ +
+
入門篇
+
這篇文章會指引你瞭解 Ajax 的基礎知識並提供了兩個簡單的動手做範例來入門。
+
使用 XMLHttpRequest API
+
XMLHttpRequest API 是 Ajax 的核心。這篇文章將解釋如何使用一些 Ajax 技術,例如: + +
+
Fetch API
+
Fetch API 提供了取得資源(fetching resources)的介面(interface)。這似乎對於曾使用過 {{domxref("XMLHTTPRequest")}} 的人而言並不陌生,然而這個 API 提供一個更強大且彈性的功能集。
+
Server-sent events
+
傳統上來說,一個網頁必須送出 request 到伺服器來得到新的資料,也就是說,網頁藉由server-sent 事件從伺服器請求 (request) 資料,伺服器在任何時候都能送新的資料給網頁,藉由推送訊息到網頁。這些傳入的訊息可以被視為網頁中的 事件 + 資料,請參見 使用server-sent event 
+
Pure-Ajax navigation example
+
This article provides a working (minimalist) example of a pure-Ajax website composed only of three pages.
+
Sending and Receiving Binary Data
+
The responseType property of the XMLHttpRequest object can be set to change the expected response type from the server. Possible values are the empty string (default), "arraybuffer", "blob", "document", "json", and "text". The response property will contain the entity body according to responseType, as an ArrayBuffer, Blob, Document, JSON, or string. This article will show some Ajax I/O techniques.
+
XML
+
可擴展標記語言(The Extensible Markup Language, XML)是W3C推薦的用於創建特殊用途標記語言的通用標記語言。它是SGML的簡化子集,能夠描述許多不同類型的數據。其主要目的是促進不同系統間的數據共享,特別是通過網際網路連接的系統。
+
JXON
+
JXON 代表無損耗 Javascript XML Object Notation, 是一個通用名稱,用來定義使用 XML 的 Javascript 物件樹(JSON) 的通用名稱。
+
解析和序列化 XML
+
如何從一串字串,一個檔案中透過 Javascript 解析一個 XML 文件  ,以及如何將 XML 檔案序列化成字串、Javascript 物件樹(JXON) 或檔案。 
+
XPath
+
XPath stands for XML Path Language, it uses a non-XML syntax that provides a flexible way of addressing (pointing to) different parts of an XML document. As well as this, it can also be used to test addressed nodes within a document to determine whether they match a pattern or not.
+
The FileReader API
+
The FileReader API lets web applications asynchronously read the contents of files (or raw data buffers) stored on the user's computer, using File or Blob objects to specify the file or data to read. File objects may be obtained from a FileList object returned as a result of a user selecting files using the <input> element, from a drag and drop operation's DataTransfer object, or from the mozGetAsFile() API on an HTMLCanvasElement.
+
HTML in XMLHttpRequest
+
The W3C XMLHttpRequest specification adds HTML parsing support to XMLHttpRequest, which originally supported only XML parsing. This feature allows Web apps to obtain an HTML resource as a parsed DOM using XMLHttpRequest.
+
Other resources
+
Other Ajax resources you may find useful.
+
+ +

View All...

+ +

參見

+ +
+
Alternate Ajax Techniques
+
Most articles on Ajax have focused on using XMLHttp as the means to achieving such communication, but Ajax techniques are not limited to just XMLHttp. There are several other methods.
+
Ajax: A New Approach to Web Applications
+
Jesse James Garrett, of adaptive path, wrote this article in February 2005, introducing Ajax and its related concepts.
+
A Simpler Ajax Path
+
"As it turns out, it's pretty easy to take advantage of the XMLHttpRequest object to make a web app act more like a desktop app while still using traditional tools like web forms for collecting user input."
+
Ajax Mistakes
+
Alex Bosworth has written this article outlining some of the mistakes Ajax application developers can make.
+
Tutorial with examples.
+
 
+
XMLHttpRequest specification
+
W3C Working draft
+
+
+ + +
+ +

{{ListSubpages}}

diff --git a/files/zh-tw/web/guide/api/index.html b/files/zh-tw/web/guide/api/index.html new file mode 100644 index 0000000000..950affd971 --- /dev/null +++ b/files/zh-tw/web/guide/api/index.html @@ -0,0 +1,25 @@ +--- +title: Guide to Web APIs +slug: Web/Guide/API +tags: + - API + - Guide + - Landing + - NeedsTranslation + - TopicStub + - Web +translation_of: Web/Guide/API +--- +

Here you'll find links to each of the guides introducing and explaining each of the APIs that make up the Web development architecture.

+

Web APIs from A to Z

+ +

{{ListGroups}}

+ +

See also

+ + diff --git a/files/zh-tw/web/guide/dom/index.html b/files/zh-tw/web/guide/dom/index.html new file mode 100644 index 0000000000..997730a412 --- /dev/null +++ b/files/zh-tw/web/guide/dom/index.html @@ -0,0 +1,21 @@ +--- +title: DOM developer guide +slug: Web/Guide/DOM +tags: + - API + - DOM + - Guide + - NeedsTranslation + - TopicStub +translation_of: Web/API/Document_Object_Model +--- +

{{draft}}

+

The Document Object Model is an API for HTML and XML documents. It provides a structural representation of the document, enabling the developer to modify its content and visual presentation. Essentially, it connects web pages to scripts or programming languages.

+

All of the properties, methods, and events available to the web developer for manipulating and creating web pages are organized into objects (e.g., the document object that represents the document itself, the table object that represents a HTML table element, and so forth). Those objects are accessible via scripting languages in most recent web browsers.

+

The DOM is most often used in conjunction with JavaScript. However, the DOM was designed to be independent of any particular programming language, making the structural representation of the document available from a single, consistent API. Though we focus on JavaScript throughout this site, implementations of the DOM can be built for any language.

+

The World Wide Web Consortium establishes a standard for the DOM, called the W3C DOM. It should, now that the most important browsers correctly implement it, enable powerful cross-browser applications.

+

Why is the DOM important?

+

"Dynamic HTML" (DHTML) is a term used by some vendors to describe the combination of HTML, style sheets and scripts that allows documents to be animated. The W3C DOM Working Group is working hard to make sure interoperable and language-neutral solutions are agreed upon (see also the W3C FAQ). As Mozilla claims the title of "Web Application Platform", support for the DOM is one of the most requested features, and a necessary one if Mozilla wants to be a viable alternative to the other browsers.

+

Even more important is the fact that the user interface of Mozilla (also Firefox and Thunderbird) is built using XUL, using the DOM to manipulate its own UI.

+

More about the DOM

+

{{LandingPageListSubpages}}

diff --git a/files/zh-tw/web/guide/events/creating_and_triggering_events/index.html b/files/zh-tw/web/guide/events/creating_and_triggering_events/index.html new file mode 100644 index 0000000000..c198adaa5e --- /dev/null +++ b/files/zh-tw/web/guide/events/creating_and_triggering_events/index.html @@ -0,0 +1,144 @@ +--- +title: 建立或觸發事件 +slug: Web/Guide/Events/Creating_and_triggering_events +tags: + - Advanced + - DOM + - Guide + - JavaScript + - 事件 +translation_of: Web/Guide/Events/Creating_and_triggering_events +--- +

本文介紹如何建立和觸發事件。

+ +

建立自定義事件

+ +

事件可以用 {{domxref("Event")}} constructor 建立,如下所示:

+ +
var event = new Event('build');
+
+// 監聽事件
+elem.addEventListener('build', function (e) { ... }, false);
+
+// 觸發事件
+elem.dispatchEvent(event);
+ +

除了 Internet Explorer 以外,大多數的瀏覽器都支持這個 constructor 。若要能夠支援 Internet Explore 的更詳細的方法,可以參考段落《早期的做法》。

+ +

增加自定義的資料--CustomEvent()

+ +

要在事件的 object 追加其他資料,能使用 {{domxref("CustomEvent")}} 介面。它有 detail 屬性,可以用來傳送自訂資料。
+ 舉例來說,可以以下面方式建立事件:

+ +
var event = new CustomEvent('build', { 'detail': elem.dataset.time });
+ +

它可以讓你傳送自訂資料到事件的監聽器:

+ +
function eventHandler(e) {
+  log('The time is: ' + e.detail);
+}
+
+ +

早期的做法

+ +

早期建立事件的方式參考了 Java 的 API 。下為一個早期作法的例子:

+ +
// 建立事件
+var event = document.createEvent('Event');
+
+// 設定事件名稱為 “build” 。
+event.initEvent('build', true, true);
+
+// 監聽事件
+elem.addEventListener('build', function (e) {
+  // e.target matches elem
+}, false);
+
+// 事件對象可以是任一 HTML 元素或是 EventTarget 。
+elem.dispatchEvent(event);
+
+
+ +

觸發自定義事件

+ +

下面的例子演示了一個複選框藉由 DOM 的 methods 模擬一次點擊(換言之,讓程式執行一次「點擊事件」。)。 觀看實例

+ +
function simulateClick() {
+  var event = new MouseEvent('click', {
+    'view': window,
+    'bubbles': true,
+    'cancelable': true
+  });
+  var cb = document.getElementById('checkbox');
+  var canceled = !cb.dispatchEvent(event);
+  if (canceled) {
+    // A handler called preventDefault.
+    alert("canceled");
+  } else {
+    // None of the handlers called preventDefault.
+    alert("not canceled");
+  }
+}
+ +

瀏覽器的支援度

+ +

 

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)EdgeInternet ExplorerOperaSafari (WebKit)
Event() constructor1511{{CompatVersionUnknown}}{{CompatNo}}11.606
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}6
+
+ +

延伸閱讀

+ + diff --git a/files/zh-tw/web/guide/events/event_handlers/index.html b/files/zh-tw/web/guide/events/event_handlers/index.html new file mode 100644 index 0000000000..519ac8bf90 --- /dev/null +++ b/files/zh-tw/web/guide/events/event_handlers/index.html @@ -0,0 +1,178 @@ +--- +title: DOM on-event 處理器 +slug: Web/Guide/Events/Event_handlers +translation_of: Web/Guide/Events/Event_handlers +--- +

Web 平台提供了多種獲得 DOM 事件通知的方式。兩種常見的風格為:通用的 {{domxref("EventTarget.addEventListener", "addEventListener()")}} 及一組特定的 on-event 處理器。本頁聚焦在後者如何運作的細節。

+ +

註冊 on-event 處理器

+ +

on-event 處理器為一群由 DOM 元素提供的屬性({{Glossary("property")}}),用來協助管理元素要如何應對事件。元素可以是具互動性的(如:links、buttons、images、forms)或非互動性的(如頁面基礎 document)。事件為一個操作,像是點擊(clicked)、偵測按下按鍵(pressed keys)、取得焦點(focus)等。on-event 處理器通常是根據它被設計來應對的事件,例如 onclickonkeypressonfocus 等等。

+ +

你可以使用兩種不同的方式來為一個物件的特定事件(例如:{{event("click")}})指定一個 on<...> 事件處理器:

+ + + +

Note that each object can have only one on-event handler for a given event (though that handler could call multiple sub-handlers). This is why {{domxref("EventTarget.addEventListener", "addEventListener()")}} is often the better way to get notified of events, especially when wishing to apply various event handlers independently from each other, even for the same event and/or to the same element.

+ +

Also note that on-event handlers are called automatically, not at the programmer's will (although you can, like mybutton.onclick(myevent); ) since they serve more as placeholders to which a real handler function can be assigned.

+ +

非元素物件

+ +

Event handlers can also be set using properties on many non-element objects that generate events, including {{ domxref("window") }}, {{ domxref("document") }}, {{ domxref("XMLHttpRequest") }}, and others, for example:

+ +
xhr.onprogress = function() { ... }
+ +

細節

+ +

HTML 的 on<...> 屬性值及對應的 JavaScript 屬性

+ +

A handler registered via an on<...> attribute will be available via the corresponding on<...> property, but not the other way around:

+ +
<div id="a" onclick="alert('old')">Open the Developer Tools Console to see the output.</div>
+
+<script>
+window.onload = function () {
+  var div = document.getElementById("a");
+  console.log("Attribute reflected as a property: ", div.onclick.toString());
+  // Prints: function onclick(event) { alert('old') }
+  div.onclick = function() { alert('new') };
+  console.log("Changed property to: ", div.onclick.toString());
+  // Prints: function () { alert('new') }
+  console.log("Attribute value is unchanged: ", div.getAttribute("onclick"));
+  // Prints: alert('old')
+}
+</script>
+ +

For historical reasons, some attributes/properties on the {{HTMLElement("body")}} and {{HTMLElement("frameset")}} elements actually set event handlers on their parent {{domxref("Window")}} object. (The HTML specification names these: onblur, onerror, onfocus, onload, onscroll.)

+ +

事件處理器的參數、this 綁定及回傳值

+ +

當一個事件處理被定義成為一個 HTML 的屬性時,給定的程式碼會被包成一個具有下列參數的函式:

+ + + +

當事件處理函式被觸發時,處理函式中的關鍵字: this 被設定成為註冊這個事件處理函式的DOM 元件。 請參閱 this 關鍵字說明 獲得更多細節。

+ +

The return value from the handler determines if the event is canceled. The specific handling of the return value depends on the kind of event, for details see "The event handler processing algorithm" in the HTML specification.

+ +

當事件處理器被調用

+ +

TBD (non-capturing listener)

+ +

術語

+ +

The term event handler may be used to refer to:

+ + + +

When discussing the various methods of listening to events,

+ + + +

規範

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'webappapis.html#event-handler-attributes', 'event handlers')}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5 W3C', 'webappapis.html#event-handler-attributes', 'event handlers')}}{{Spec2('HTML5 W3C')}}
+ +

瀏覽器相容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Event handler changes in Firefox 9

+ +

In order to better match the specifications, and improve cross-browser compatibility, the way event handlers were implemented at a fundamental level changed in Gecko 9.0 {{ geckoRelease("9.0") }}.

+ +

Specifically, in the past, event handlers were not correctly implemented as standard IDL attributes. In Gecko 9.0, this was changed. Because of this, certain behaviors of event handlers in Gecko have changed. In particular, they now behave in all the ways standard IDL attributes behave. In most cases, this shouldn't affect web or add-on content at all; however, there are a few specific things to watch out for.

+ +

Detecting the presence of event handler properties

+ +

You can now detect the presence of an event handler property (that is, for example, onload), using the JavaScript in operator. For example:

+ +
if ("onsomenewfeature" in window) {
+  /* do something amazing */
+}
+
+ +

Event handlers and prototypes

+ +

You can't set or access the values of any IDL-defined attributes on DOM prototype objects; that means you can't, for example, change Window.prototype.onload anymore. In the past, event handlers (onload, etc.) weren't implemented as IDL attributes in Gecko, so you were able to do this for those. Now you can't. This improves compatibility.

diff --git a/files/zh-tw/web/guide/events/index.html b/files/zh-tw/web/guide/events/index.html new file mode 100644 index 0000000000..4484986b66 --- /dev/null +++ b/files/zh-tw/web/guide/events/index.html @@ -0,0 +1,52 @@ +--- +title: Event developer guide +slug: Web/Guide/Events +tags: + - DOM + - Event + - Guide + - NeedsTranslation + - NeedsUpdate + - TopicStub +translation_of: Web/Guide/Events +--- +

{{draft()}}

+ +

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

+ +

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

+ +

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

+ +

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

+ +

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

+ +

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

+ +

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

+ +

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

+ + + +

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

+ +

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

+ +

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

+ +

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

+ +
+

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

+
+ +

文件

+ +

{{LandingPageListSubpages}}

diff --git a/files/zh-tw/web/guide/graphics/index.html b/files/zh-tw/web/guide/graphics/index.html new file mode 100644 index 0000000000..224757c138 --- /dev/null +++ b/files/zh-tw/web/guide/graphics/index.html @@ -0,0 +1,49 @@ +--- +title: 網頁上的圖像 +slug: Web/Guide/Graphics +translation_of: Web/Guide/Graphics +--- +

現代網站或應用程式通常都配有圖像。我們可以很容易地使用{{HTMLElement("img")}}元素呈現靜態圖像 , 或藉由使用{{cssxref("background-image")}} 設定HTML的背景元素性質。你常會想要建立動態圖像或在事後操縱圖像。這些文章將讓你知道如何達成這些效果。

+ +
+
+

2D 圖像

+ +
+
Canvas
+
{{HTMLElement("canvas")}} 元素提供 APIs讓開發者透過Javascript來繪製2D圖像.
+
SVG
+
可縮放向量圖像(SVG) 讓你可以使用直線,曲線以及其他幾何圖形來編寫圖像。避免使用點陣圖像(bitmaps),你可以創造出適合任何大小的圖像。
+
+ +

 

+ +

 

+ +

 

+ +

 

+ +

觀看全部...

+
+ +
+

3D 圖像

+ +
+
WebGL
+
一份WebGL初始指南,網頁用3D 圖像 API。這項技術讓你在網頁內容使用standard OpenGL ES。
+
+ +

影片

+ +
+
使用 HTML5 影音
+
在 HTML 檔案嵌入影片及控制播放。
+
WebRTC
+
在WebRTC 中 RTC 是 Real-Time Communications 的簡稱,讓瀏覽器客戶端之間(peers)串流影片/音效檔案與數據分享的技術。
+
+
+
+ +

 

diff --git a/files/zh-tw/web/guide/html/content_categories/index.html b/files/zh-tw/web/guide/html/content_categories/index.html new file mode 100644 index 0000000000..707e63ca85 --- /dev/null +++ b/files/zh-tw/web/guide/html/content_categories/index.html @@ -0,0 +1,150 @@ +--- +title: 內容類型 +slug: Web/Guide/HTML/Content_categories +translation_of: Web/Guide/HTML/Content_categories +--- +

每個 HTML 元素都要遵從該元素可擁有何種內容規則,這些規則被歸為幾種常用的內容模型(content model)。每個 HTML 元素都屬於零個、一個、或數個內容的模型,所有元素內容的設置規則都要遵從 HTML 一致性文件。

+ +

內容類型有三種類型:

+ + + +
Content_categories_venn.png
+ +

主要內容類型

+ +

資訊元內容(Metadata content)

+ +

屬於元資訊內容類型的元素修飾該文件其餘部分的陳述或行為、與其他文件建立連結、或是傳達其他外來(out of band)訊息。

+ +

屬於這個類型的元素有 {{HTMLElement("base")}}、{{ Obsolete_inline() }}{{HTMLElement("command")}}、{{HTMLElement("link")}}、{{HTMLElement("meta")}}、{{HTMLElement("noscript")}}、{{HTMLElement("script")}}、{{HTMLElement("style")}} 與 {{HTMLElement("title")}}

+ +

流內容(Flow content)

+ +

屬於流內容的元素通常含有文字或嵌入內容。它們是:{{HTMLElement("a")}}、{{HTMLElement("abbr")}}、{{HTMLElement("address")}}、{{HTMLElement("article")}}、{{HTMLElement("aside")}}、{{HTMLElement("audio")}}、{{HTMLElement("b")}},{{HTMLElement("bdo")}}、{{HTMLElement("bdi")}}、{{HTMLElement("blockquote")}}、{{HTMLElement("br")}}、{{HTMLElement("button")}}、{{HTMLElement("canvas")}}、{{HTMLElement("cite")}}、{{HTMLElement("code")}}、{{ Obsolete_inline() }}{{HTMLElement("command")}}、{{HTMLElement("data")}}、{{HTMLElement("datalist")}}、{{HTMLElement("del")}}、{{HTMLElement("details")}}、{{HTMLElement("dfn")}}、{{HTMLElement("div")}}、{{HTMLElement("dl")}}、{{HTMLElement("em")}}、{{HTMLElement("embed")}}、{{HTMLElement("fieldset")}}、{{HTMLElement("figure")}}、{{HTMLElement("footer")}}、{{HTMLElement("form")}}、{{HTMLElement("h1")}}、{{HTMLElement("h2")}}、{{HTMLElement("h3")}}、{{HTMLElement("h4")}}、{{HTMLElement("h5")}}、{{HTMLElement("h6")}}、{{HTMLElement("header")}}、{{HTMLElement("hgroup")}}、{{HTMLElement("hr")}}、{{HTMLElement("i")}}、{{HTMLElement("iframe")}}、{{HTMLElement("img")}}、{{HTMLElement("input")}}、{{HTMLElement("ins")}}、{{HTMLElement("kbd")}}、{{deprecated_inline()}}{{HTMLElement("keygen")}}、{{HTMLElement("label")}}、{{HTMLElement("main")}}、{{HTMLElement("map")}}、{{HTMLElement("mark")}}、{{MathMLElement("math")}}、{{HTMLElement("menu")}}、{{HTMLElement("meter")}}、{{HTMLElement("nav")}}、{{HTMLElement("noscript")}}、{{HTMLElement("object")}}、{{HTMLElement("ol")}}、{{HTMLElement("output")}}、{{HTMLElement("p")}}、{{HTMLElement("pre")}}、{{HTMLElement("progress")}}、{{HTMLElement("q")}}、{{HTMLElement("ruby")}}、{{HTMLElement("s")}}、{{HTMLElement("samp")}}、{{HTMLElement("script")}}、{{HTMLElement("section")}}、{{HTMLElement("select")}}、{{HTMLElement("small")}}、{{HTMLElement("span")}}、{{HTMLElement("strong")}}、{{HTMLElement("sub")}}、{{HTMLElement("sup")}}、{{SVGElement("svg")}}、{{HTMLElement("table")}}、{{HTMLElement("template")}}、{{HTMLElement("textarea")}}、{{HTMLElement("time")}}、{{HTMLElement("ul")}}、{{HTMLElement("var")}}、{{HTMLElement("video")}}、{{HTMLElement("wbr")}} 還有文字。

+ +

在滿足特定條件下,某些元素也屬這個類型:

+ + + +

章節型內容(Sectioning content)

+ +

屬於章節型內容模型的元素會在該大綱裡面創立章節,這個章節會定義{{HTMLElement("header")}}、{{HTMLElement("footer")}}、還有heading content的範圍。

+ +

屬於這個類型的元素有{{HTMLElement("article")}}、{{HTMLElement("aside")}}、{{HTMLElement("nav")}}還有{{HTMLElement("section")}}。

+ +
+

注意:不要把這個內容模型,和把內容與常規大綱隔開的 sectioning root 類別搞混。

+
+ +

標題型內容(Heading content)

+ +

标题内容 定义了分节的标题,而这个分节可能由一个明确的分节内容元素直接标记,也可能由标题本身隐式地定义。

+ +

標題型內容定義了章節的標題,不論該章節由明確的章節型內容元素標記、抑或由標題本身隱式定義。

+ +

屬於這個類型的元素有{{HTMLElement("h1")}}、{{HTMLElement("h2")}}、{{HTMLElement("h3")}}, {{HTMLElement("h4")}}、{{HTMLElement("h5")}}、{{HTMLElement("h6")}}還有{{HTMLElement("hgroup")}}.

+ +
+

注意:儘管 {{HTMLElement("header")}} 可能含有某些標題型內容,但它本身並不是。

+
+ +

段落型內容(Phrasing content)

+ +

段落型內容定義了文字、還有它包含的標記。Runs of phrasing content make up paragraphs.

+ +

屬於這個類型的元素有{{HTMLElement("abbr")}}、{{HTMLElement("audio")}}、{{HTMLElement("b")}}、{{HTMLElement("bdo")}}、{{HTMLElement("br")}}、{{HTMLElement("button")}}、{{HTMLElement("canvas")}}、{{HTMLElement("cite")}}、{{HTMLElement("code")}}、{{ Obsolete_inline() }}{{HTMLElement("command")}}、{{HTMLElement("datalist")}}、{{HTMLElement("dfn")}}、{{HTMLElement("em")}}、{{HTMLElement("embed")}}、{{HTMLElement("i")}}、{{HTMLElement("iframe")}}、{{HTMLElement("img")}}、{{HTMLElement("input")}}、{{HTMLElement("kbd")}}、{{deprecated_inline()}}{{HTMLElement("keygen")}}、{{HTMLElement("label")}}、{{HTMLElement("mark")}}、{{MathMLElement("math")}}、{{HTMLElement("meter")}}、{{HTMLElement("noscript")}}、{{HTMLElement("object")}}、{{HTMLElement("output")}}、{{HTMLElement("progress")}}、{{HTMLElement("q")}}、{{HTMLElement("ruby")}}、{{HTMLElement("samp")}}、{{HTMLElement("script")}}、{{HTMLElement("select")}}、{{HTMLElement("small")}}、{{HTMLElement("span")}}、{{HTMLElement("strong")}}、{{HTMLElement("sub")}}、{{HTMLElement("sup")}}、{{SVGElement("svg")}}、{{HTMLElement("textarea")}}、{{HTMLElement("time")}}、{{HTMLElement("var")}}、{{HTMLElement("video")}}、{{HTMLElement("wbr")}}以及空白字符在內的純文本。

+ +

在滿足特定條件下,某些元素也屬這個類型:

+ + + +

嵌入型內容(Embedded content)

+ +

嵌入型內容從其他標記語言或文件命名空間,導入資源或插入內容。 屬於這個類型的元素有{{HTMLElement("audio")}}、{{HTMLElement("canvas")}}、{{HTMLElement("embed")}}、{{HTMLElement("iframe")}}、{{HTMLElement("img")}}、{{MathMLElement("math")}}、{{HTMLElement("object")}}、{{SVGElement("svg")}}、{{HTMLElement("video")}}。

+ +

互動型內容(Interactive content)

+ +

互動型內容包含專為用戶互動設計的元素。屬於這個類型的元素有 {{HTMLElement("a")}}、{{HTMLElement("button")}}、{{HTMLElement("details")}}、{{HTMLElement("embed")}}、{{HTMLElement("iframe")}}、{{deprecated_inline()}}{{HTMLElement("keygen")}}、{{HTMLElement("label")}}、{{HTMLElement("select")}} 還有 {{HTMLElement("textarea")}}。

+ +

在滿足特定條件下,某些元素也屬這個類型:

+ + + +

捫及內容(Palpable content)

+ +

不是空白或隱藏的內容稱為捫及。屬於流內容或是Phrasing content模型的元素最少要有一個捫及的節點。

+ +

表單相關內容(Form-associated content)

+ +

表單相關內容包含了由 form 屬性顯露的 form owner 元素。form owner 是本身包含於 {{HTMLElement("form")}}、或 id 由 form 屬性指定的元素。

+ + + +

本類型包含某些子類別:

+ +
+
listed
+
Elements that are listed in the form.elements and fieldset.elements IDL collections. Contains {{HTMLElement("button")}}, {{HTMLElement("fieldset")}}, {{HTMLElement("input")}}, {{deprecated_inline()}}{{HTMLElement("keygen")}}, {{HTMLElement("object")}}, {{HTMLElement("output")}}, {{HTMLElement("select")}}, and {{HTMLElement("textarea")}}.
+
labelable
+
與元素 {{HTMLElement("label")}} 相關的元素。包含 {{HTMLElement("button")}}、{{HTMLElement("input")}}、{{deprecated_inline()}}{{HTMLElement("keygen")}}、{{HTMLElement("meter")}}、{{HTMLElement("output")}}、{{HTMLElement("progress")}}、{{HTMLElement("select")}}、{{HTMLElement("textarea")}}。
+
submittable
+
用在建構送出時,資料就設定好的表單元素。包含 {{HTMLElement("button")}}、{{HTMLElement("input")}}、{{deprecated_inline()}}{{HTMLElement("keygen")}}、{{HTMLElement("object")}}、{{HTMLElement("select")}}、{{HTMLElement("textarea")}}。
+
resettable
+
當表單重設時會受影響的元素。包含 {{HTMLElement("button")}}、{{HTMLElement("input")}}、{{deprecated_inline()}}{{HTMLElement("keygen")}}、{{HTMLElement("output")}}、{{HTMLElement("select")}}、{{HTMLElement("textarea")}}。
+
+ +

透明內容模型(Transparent content model)

+ +

如果一個元素是透明內容模型,then its contents must be structured such that they would be valid HTML 5,就算該透明元素被移除、並由子元素取代。

+ +

例如,{{HTMLElement("del")}} 與 {{HTMLELement("ins")}} 元素都是透明的:

+ +
<p>我們認為下面這些真理是<del><em>神聖不可否認</em></del><ins>不言而喻的。</ins></p>
+
+ +

這果這些元素被刪掉的話,這個分段依然在 HTML 有效(if not correct English)

+ +
<p>我們認為下面這些真理是<em>神聖不可否認</em>不言而喻的。</p>
+
+ + +

其他內容模型

+ +

章節根(Sectioning root)

diff --git a/files/zh-tw/web/guide/html/event_attributes/index.html b/files/zh-tw/web/guide/html/event_attributes/index.html new file mode 100644 index 0000000000..6f57526dde --- /dev/null +++ b/files/zh-tw/web/guide/html/event_attributes/index.html @@ -0,0 +1,84 @@ +--- +title: Event attributes +slug: Web/Guide/HTML/Event_attributes +translation_of: >- + Learn/JavaScript/Building_blocks/Events#Inline_event_handlers_%E2%80%94_don%27t_use_these +--- +

每一個 HTML 元素都可以放置事件屬性,以藉此於事件發生時能執行 JavaScripte 程式。事件屬性的名稱都有一個前綴「on」,例如當使用者點選元素時要執行指定的 JavaScript,可以使用 onclick 屬性並把要執行的 JavaScript 當成屬性值。

+ +

In the JavaScript code executed in response to the event, this is bound to the HTML element and the {{domxref("Event")}} object can be reached using the event variable in the scope of the attribute.

+ +
+

Warning: These attributes should be avoided. This makes the markup bigger and less readable. Concerns of content/structure and behavior are not well-separated, making a bug harder to find. Furthermore, usage of event attributes almost always causes scripts to expose global functions on the {{domxref("Window")}} object, polluting the global namespace.

+
+ +

While these attributes can at times be attractively easy to use, you should avoid using them. Instead, use the {{domxref("EventTarget.addEventListener()")}} function to add a listener for the event.

+ +

Event attributes can be blocked by using Content Security Policy which if used, blocks all inline scripts unless the 'unsafe-inline' keyword is used.

+ +

Example using event attributes

+ +

This example appends text to an element each time time the {{HTMLElement("div")}} is clicked.

+ +
+

Note: This is an example of how not to do things, using one of these attributes.

+
+ +
<!doctype html>
+<html>
+  <head>
+    <title>Event Attribute Example</title>
+    <script>
+      function doSomething() {
+        document.getElementById("thanks").innerHTML += "<p>Thanks for clicking!</p>";
+      }
+    </script>
+  </head>
+  <body>
+    <div onclick="doSomething();">Click me!</div>
+    <div id="thanks"></div>
+  </body>
+</html>
+
+ +

Try this example below:

+ +

{{ EmbedLiveSample('Example_using_event_attributes', '', '', '') }}

+ +

Example using event listeners

+ +

Instead, you should use {{domxref("EventTarget.addEventListener()")}}, as shown here:

+ +
<!doctype html>
+<html>
+  <head>
+    <title>Event Attribute Example</title>
+    <script>
+      function doSomething() {
+        document.getElementById("thanks").innerHTML += "<p>Thanks for clicking!</p>";
+      }
+
+      // Called when the page is done loading; this is where we do any setup we need,
+      // such as creating event listeners for the elements in the page.
+
+      function setup() {
+        document.getElementById("click").addEventListener("click", doSomething, true);
+      }
+
+      // Install an event handler on the window to receive the "load" event, which
+      // indicates that the document has finished loading into the window.
+
+      window.addEventListener("load", setup, true);
+    </script>
+  </head>
+  <body>
+    <div id="click">Click me!</div>
+    <div id="thanks"></div>
+  </body>
+</html>
+ +

You can see this in action below:

+ +

{{ EmbedLiveSample('Example_using_event_listeners', '', '', '') }}

+ + diff --git a/files/zh-tw/web/guide/html/html5/index.html b/files/zh-tw/web/guide/html/html5/index.html new file mode 100644 index 0000000000..c1ea8252ef --- /dev/null +++ b/files/zh-tw/web/guide/html/html5/index.html @@ -0,0 +1,112 @@ +--- +title: HTML5 +slug: Web/Guide/HTML/HTML5 +translation_of: Web/Guide/HTML/HTML5 +--- +

HTML5 是 HTML 標準中的最新版。在 HTML5 規格還未拍板定案之前,Mozilla 以及其他瀏覽器開發商已經著手實現其中的部分功能。本文所列的連結網址與相關內容,是 Mozilla  Gecko 解析引擎已經支援的部份,Firefox許多其他產品都使用 Gecko 解析引擎。

+ +

(這裡是 另一篇 HTML5 分類整理文章。)

+ +

HTML5 簡介

+ +
+
HTML5 簡介
+
這篇文章介紹如何在你的網頁設計或 Web 應用程式中使用 HTML5。
+
+ +

HTML5 元素

+ +
+
使用 audio 和 video {{ gecko_minversion_inline("1.9.2") }}
+
Firefox 3.5 開始支援 HTML5 {{ HTMLElement("audio") }} 和 {{ HTMLElement("video") }} 兩個元素。
+
HTML5 表單 {{ gecko_minversion_inline("2.0") }}
+
簡單介紹 HTML5 對於 Web 表單的改進項目:限制條件與驗證 API、多個新增的屬性、新增多個值供 {{ HTMLElement("input") }} 的 {{ htmlattrxref("type", "input") }} 屬性使用,並且新增 {{ HTMLElement("output") }} 元素。
+
Sections 和 outlines {{ gecko_minversion_inline("2.0") }}
+
HTML5 對於大綱與分段的支援元素包含有: {{ HTMLElement("section") }}、{{ HTMLElement("article") }}、{{ HTMLElement("nav") }}、{{ HTMLElement("header") }}、{{ HTMLElement("footer") }}、{{ HTMLElement("aside") }} 以及 {{ HTMLElement("hgroup") }}。
+
元素 {{ HTMLElement("mark") }} {{ gecko_minversion_inline("2.0") }}
+
元素 mark 被用在標註特別相關的重點文字。
+
元素 {{ HTMLElement("figure") }} 和 {{ HTMLElement("figcaption") }} {{ gecko_minversion_inline("2.0") }}
+
These elements lets you add figures and illustration, with an eventual caption, loosely coupled to the main text.
+
+ +

支援 Canvas

+ +
+
Canvas 導覽 {{ gecko_minversion_inline("1.8.1") }}
+
 學習如何使用新的 {{ HTMLElement("canvas") }} 元素,以及如何在 Firefox 中繪製圖表與其他物件。
+
<canvas> 元素的 HTML5 文字(text) API {{ gecko_minversion_inline("1.9.1") }}
+
{{ HTMLElement("canvas") }} 元素現在已經支援 HTML5 文字(text) API。
+
+ +

給 Web 應用程式的新功能

+ +
+
Firefox 中的離線資源(含 HTML5 Application Cache 介紹)  {{ gecko_minversion_inline("1.9.1") }}
+
Firefox 完整支援 HTML5 離線資源規格。
+
上線與離線事件 (Online and offline events) {{ gecko_minversion_inline("1.9") }}
+
Firefox 3 支援 WHATWG 的上線與離線事件,這讓應用程式與擴充套件可以偵測目前是否有可用的 Internet 連線,也可以偵測何時建立或結束這個網路連線。
+
WHATWG 用戶端 session 與持續性儲存 (persistent storage) (亦稱 DOM 儲存) {{ gecko_minversion_inline("1.8.1") }}
+
用戶端 session 與持續性儲存功能,讓 web 應用程式可以在用戶端儲存結構性資料。
+
屬性 contentEditable ,將你的網站變成 wiki ! {{ gecko_minversion_inline("1.9.1") }}
+
HTML5 已經將 contentEditable 屬性標準化。學習更多這個新功能。
+
在 web 應用程式中存取檔案 {{ gecko_minversion_inline("1.9.2") }}
+
Gecko 已經支援新的 HTML5 檔案 API,讓 web 應用程式可以存取使用者所選的本地端檔案。這個功能也包含使用檔案類型的輸入元素 {{ HTMLElement("input") }}  type file 的新屬性 multiple 來選取多個檔案。
+
+ +

DOM 新功能

+ +
+
getElementsByClassName {{ fx_minversion_inline(3.0) }}
+
支援 Document 與 Element 節點的 getElementsByClassName 方法。這個方法允許藉由指定的一個或多個 class 尋找頁面中的元素。
+
拖曳功能 (Drag and drop) {{ fx_minversion_inline(3.5) }}
+
HTML5 拖曳 API 支援在一個或多個網站之間拖曳物件。也提供了一個更簡化的 API 供擴充套件與 Mozilla-based 應用程式使用。
+
HTML Focus 管理 {{ fx_minversion_inline(3.0) }}
+
支援新的 HTML5 屬性:activeElementhasFocus
+
Web-based 協定處理器 {{ fx_minversion_inline(3.0) }}
+
你現在可以使用 navigator.registerProtocolHandler() 方法將 web 應用程式註冊成協定處理器 (protocol handlers)。
+
+ +

HTML 解析器

+ +

Gecko 的 HTML5相容解析器 — 負責將一份 HTML 文件字元們轉化為 DOM — 已經於 2010 年五月預設為啟用。(備忘:該 HTML5 解析器版本搭載於 Gecko 1.9.2 / Firefox 3.6 當中,是個不穩定的版本,並且不建議用於正式使用環境。) {{ fx_minversion_inline(4.0) }}

+ +

其他

+ + + +

有些人自以為它是 HTML5 的一部分……XD

+ + + +

參考

+ + + +

{{ HTML5ArticleTOC() }}

+ +

{{ languages( {"es": "es/HTML/HTML5", "fr": "fr/HTML/HTML5", "ja": "ja/HTML/HTML5" , "ko": "ko/HTML/HTML5" , "pt": "pt/HTML/HTML5", "zh-cn": "cn/HTML/HTML5", "zh-tw": "zh_tw/HTML/HTML5", "pt-br": "pt-br/HTML/HTML5"} ) }}

diff --git a/files/zh-tw/web/guide/html/html5/introduction_to_html5/index.html b/files/zh-tw/web/guide/html/html5/introduction_to_html5/index.html new file mode 100644 index 0000000000..7e2eba7335 --- /dev/null +++ b/files/zh-tw/web/guide/html/html5/introduction_to_html5/index.html @@ -0,0 +1,40 @@ +--- +title: Introduction to HTML5 +slug: Web/Guide/HTML/HTML5/Introduction_to_HTML5 +tags: + - HTML + - HTML5 +translation_of: Web/Guide/HTML/HTML5/Introduction_to_HTML5 +--- +

HTML5 是目前最新的HTML標準。它提供一些新特性,不只是支援多媒體,還讓網頁應用程式可以更容易、更有效地與使用者、伺服器互動。

+ +

目前,仍有一些瀏覽器未完全支援HTML5所有特性。但是使用Gecko解析引擎的Firefox已經對HTML5十分支持,現時還繼續開發去支援更多特性。Gecko已經在1.8.1版本開始支持一些HTML5 了。你可以在main HTML5 page找到Gecko解析引擎最近支援的HTML5特性列表。若要更仔細知道多種瀏覽器支援的情況,可瀏覽CanIUse

+ +

建立HTML5文件並宣告HTML5 doctype

+ +

要建立HTML5文件很簡單,只需要在文件開首宣告:

+ +
<!DOCTYPE html>
+
+ +

對於未支援HTML5標準的瀏覽器,瀏覽器會繼續解析,但要注意一些HTML5的新特性則會忽略、不會支援。

+ +

然而這個宣告方法比以前HTML版本更簡單、更短,更容易記憶,亦減少文件容量。

+ +

利用<meta charset>來宣告字符集

+ +

你需要首先指示瀏覽器要使用哪一種字符集。在以前版本,這需要複雜的<meta>完素;來到HTML5,這變得非常簡單:

+ +
<meta charset="UTF-8">
+ +

將它放置在<head></head>之間。若果你使用的字符集與瀏覽器預先設定的不一樣,瀏覽器會重新解析文件。另外,若你目前並非UTF-8字符集,建議你在網頁中自行設定。

+ +

為了加強安全,HTML5文件限制字符集需要兼容ASCII和最少8位元。

+ +

Using the new HTML5 parser

+ +

The parsing rule of HTML5, which analyzes the meaning of mark-up, has been more precisely defined in HTML5. Until the introduction of HTML5, only the meaning of valid mark-up was defined, meaning that as soon as one small error was made in the mark-up (most Web sites have at least one), the behavior was undefined. Essentially, it meant that all browsers behaved differently, which is no longer the case. Now, faced with errors in the mark-up, all compliant browsers must behave exactly in the same way.

+ +

This requirement helps Web developers quite a bit. While it is true that all modern browsers now use these HTML5 parsing rules, non-HTML5-compliant browsers are still used by some. Keep in mind that it's still highly recommended that one write valid mark-up, as such code is easier to read and maintain, and it greatly decreases the prominence of incompatibilities that exists in various older browsers.

+ +

Don't worry — you don't have to change anything on your Web site — the Web browsers' developers have done everything for you!

diff --git a/files/zh-tw/web/guide/index.html b/files/zh-tw/web/guide/index.html new file mode 100644 index 0000000000..48772ec771 --- /dev/null +++ b/files/zh-tw/web/guide/index.html @@ -0,0 +1,29 @@ +--- +title: Web 開發者指引 +slug: Web/Guide +tags: + - Guide + - Landing + - NeedsTranslation + - TopicStub + - Web +translation_of: Web/Guide +--- +

這些文章提供了如何幫助你使用特定技術和 APIs 的資訊。

+ +
+

注意: 很抱歉。這個頁面在我們完成內容遷移之前會很混亂。

+
+ +
{{LandingPageListSubpages}}
+ +
+
JavaScript
+
JavaScript 是用來創造網頁應用程式的腳本化語言.
+
+ +

參見

+ + diff --git a/files/zh-tw/web/guide/introduction_to_web_development/index.html b/files/zh-tw/web/guide/introduction_to_web_development/index.html new file mode 100644 index 0000000000..ec264af0b3 --- /dev/null +++ b/files/zh-tw/web/guide/introduction_to_web_development/index.html @@ -0,0 +1,13 @@ +--- +title: Web開發入門 +slug: Web/Guide/Introduction_to_Web_development +translation_of: Web/Guide/Introduction_to_Web_development +--- +

不論你是否是剛入門的 Web 開發者,或者只是為了拓寬視野而進入全新的 Web 領域,這裡的連結應該幫得上你。至少,我們在此有很多的連結。

+
附註: 本頁明顯還是個片斷,我們需要在此產生一些內容。
+ +

文件主題

在此我們還沒有任何文章,但很需要。

資源

+
W3Schools簡體中文版
免費的 Web 開發教學,從提供給初學者的 HTML,到高級的 Web 技術。
+
+

 

+

{{ languages( { "en": "en/Web_Development/Introduction_to_Web_development" } ) }}

diff --git a/files/zh-tw/web/guide/performance/index.html b/files/zh-tw/web/guide/performance/index.html new file mode 100644 index 0000000000..00c4b9d7fe --- /dev/null +++ b/files/zh-tw/web/guide/performance/index.html @@ -0,0 +1,14 @@ +--- +title: Optimization and performance +slug: Web/Guide/Performance +tags: + - Landing + - NeedsTranslation + - Optimization + - Performance + - TopicStub + - Web +translation_of: Web/Guide/Performance +--- +

When building modern Web apps and sites, it's important to make your content perform well. That is, to make it work quickly and efficiently. This lets it work effectively both for users of powerful desktop systems as well as for handheld devices with less power.

+

{{LandingPageListSubpages}}

diff --git a/files/zh-tw/web/guide/woff/index.html b/files/zh-tw/web/guide/woff/index.html new file mode 100644 index 0000000000..38bc75a2c1 --- /dev/null +++ b/files/zh-tw/web/guide/woff/index.html @@ -0,0 +1,100 @@ +--- +title: 網路開放字型格式 (WOFF) +slug: Web/Guide/WOFF +tags: + - Fonts + - NeedsMobileBrowserCompatibility + - WOFF + - 字型 +translation_of: Web/Guide/WOFF +--- +

WOFF網頁開放字型格式)是由 Mozilla、Type Supply、LettError 和其它組織協力開發的全新網路字型格式。它使用了同為表格結構的 sfnt 壓縮版,廣泛用於 TrueType、OpenType 和開放字型格式,另外加入了中繼資料和私有資料結構,其中包含事先定義的欄位,讓有意願的廠商和製造商提供授權資訊。

+ +

使用 WOFF 主要有以下三項好處:

+ +
    +
  1. 字型資料經過壓縮,因此使用 WOFF 的網站流量降低,載入速度也會比未壓縮的 TrueType 或 OpenType 檔更快。
  2. +
  3. 許多不願授權的字型商都可以授權 WOFF 格式的字型,網站設計師有更多的字型可以選擇。
  4. +
  5. 專有軟體和自由軟體商都喜歡 WOFF 格式,因此在網路世界上,可以成為真正通用和可交換的字型格式,有別於目前其它字型格式。
  6. +
+ +

使用 WOFF

+ +

您可透過{{cssxref("@font-face")}} CSS 屬性在網頁內的文字使用 WOFF 字型。它的運作方式和 OpenType 以及 TrueType 字型並無二異,但在下載內容時可能會更有效率,這完全歸功於其與生俱來的壓縮特性。

+ +

規格文件

+ + + + + + + + + + + + + + + + +
規格文件狀態註解
{{SpecName('WOFF1.0', '', '')}}{{Spec2('WOFF1.0')}}初始規格文件
+ +

瀏覽器相容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
功能特色ChromeFirefox (Gecko)Internet ExplorerOperaSafari
基本支援6.0{{CompatGeckoDesktop("1.9.1")}}9.011.105.1
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
功能特色AndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
基本支援{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("1.9.1")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

詳見

+ + diff --git a/files/zh-tw/web/guide/writing_forward-compatible_websites/index.html b/files/zh-tw/web/guide/writing_forward-compatible_websites/index.html new file mode 100644 index 0000000000..67d7b2c5e9 --- /dev/null +++ b/files/zh-tw/web/guide/writing_forward-compatible_websites/index.html @@ -0,0 +1,70 @@ +--- +title: Writing forward-compatible websites +slug: Web/Guide/Writing_forward-compatible_websites +translation_of: Web/Guide/Writing_forward-compatible_websites +--- +

這個頁面將解釋如何撰寫在新的瀏覽器版本發布時不會遭受毀損的網頁。

+

這對內部網路和其他非公共網站尤其重要,如果我們不能看到你的原始碼,我們將無法看到它是否已遭受毀損。底下所提到的原則可能無法全數做到,但盡可能遵守這些原則,對於你的網站在未來發展維護上有所幫助。

+

JavaScript

+

以「window.」前綴修飾所有存取於 onfoo 屬性的全域變數

+

當一個事件處理器內容屬性(例如:onclick, onmouseover 等等)被使用在 HTML 的元素上時,所有對於屬性內名稱的查找首先發生在元素本身,若元素為表單控制項,再來尋找元素的表單,接著是 document,最後是 window(你定義全域變數的地方)。例如,如果你有這樣的原始碼:

+
<div onclick="alert(ownerDocument)">點我一下</div>
+

在點選文字時,div 中的 ownerDocument 會被提示,即使是在全域範圍內宣告 var ownerDocument 這種情況依然會發生。

+

這意味著,無論你何時在事件處理器內容屬性存取了一個全域變數,包括呼叫任何全域函數,當規格中新增了和您變數或函式同名的 DOM 屬性到元素或文件之中,在瀏覽器實作之後,就會產生名稱衝突。這時你的函式將突然被停止呼叫。這種情況在 HTML5 的發展之下,多次在不同網站中發生。

+

為了避免這種情況,以 window 來限定全域變數的存取,例如:

+
<script>
+  function localName() {
+    alert('函式 localName 被呼叫了');
+  }
+</script>
+<div onclick="window.localName()">按一下會跑出一個提示訊息</div>
+
+

不要直接附加非您能控制的腳本

+

"use strict;" 指令在 ECMAScript 裡,使用於檔案層級時適用於檔案的所有程式碼。因此,若將取決非嚴格模式行為的腳本,直接附加到要求嚴格模式的腳本會導致不正常的行為。

要求 JavaScript 函式庫的作者遵守這些規則

+

向您喜歡的函式庫開發者們建議他們遵循這些規範,否則您無法確保未來這些函式庫能否依舊正常運作。可惜的是函式庫往往違反這些準則。

+

偵測

+

偵測特定功能支援

+

如果您打算使用某些功能,盡可能使用物件偵測來偵測功能是否支援。簡單來說,不要假設只要 "filter" in body.style 測試結果為 true 的瀏覽器必定是 Microsoft Internet Explorer,進而我們一定會有 window.event 物件提供事件處理器。不要假設一個擁有特定 DOM 功能的瀏覽器一定也有另外一個 DOM 功能(特別是非標準功能);或著反過來假設一定不會支持某些功能(例如,假設在腳本元素中支援 onload 的瀏覽器一定不會支援 onreadystatechange)。隨著瀏覽器們整合他們的行為,它們會同時新增和刪除許多功能並修正錯誤。過去即是如此,未來也將會如此。

+

所以,在偵測特定功能時,不要接著假定「只要某個功能支援與否,另外一樣功能就一定支援與否」。

+

別做 UA 偵測

+

這就是假設一項功能存在(User Agent 中包含特定的字元)時,必定有哪些東西可用或不可用的常見實例。

+

如果您不得不做 UA 偵測,僅針對過去的瀏覽器版本

+

如果您還是得訴諸 UA(User Agent)偵測,請只針對特定瀏覽器的過去版本進行偵測。首先,對於未知的、所測試瀏覽器的目前與未來版本執行預設的程式內容。接著如果無法透過偵測,找出過去瀏覽器版本中預設程式內容中無法使用的功能,就可以透過偵測特定瀏覽器的過去版本來追加對應的修正。

+

在這個提案中,「目前的版本」意指您所能測試到的最新版本。如果您的預設程式內容在 Firefox Aurora 中可以正常運作,而在 Beta 和最新釋出版中存在問題而無法運作,此時您可以將您所測試中的 Firefox Aurora 版本標為「目前的版本」,將 Beta 以前的版本都視為「過去的版本」,即使它們還沒有被正式釋出給大眾。

+

不要為了不同的瀏覽器設計多餘的對應程式

+

當您所用的一部分程式內容可能在所有瀏覽器都能運作時,別隨便透過物件或 UA 偵測來決定執行不同的程式碼。瀏覽器很有可能改變它們的行為並互相整合,若您任意切出不同的替代程式,您的網站將有可能會損壞。

+

測試

+

測試所有主流引擎

+

至少在 Firefox、Chrome 或 Safari(因為兩者都基於相同的 WebKit 引擎)、Opera 及 Internet Explorer 測試您的程式碼。若遵循以上原則,你有一個單一的程式碼內容在目前所有的和未知的瀏覽器都測試過,在所有主要引擎都能運作下,極有可能表示您的程式碼將不會在未來被破壞。

+

有時不同瀏覽器對特定功能的實作不盡相同。如果你有一個單一的程式碼內容,在所有常用的引擎中都沒問題,這可能表示,你使用了各瀏覽器間已經整合的行為,或著使用了尚未整合,而程式碼無關引擎的行為標準所堅持的部份。

+

特定瀏覽器支援的功能和前綴

+

別針對目前或未來的瀏覽器版本做臨時方案

+

這又是一個常見的實例:假設目前瀏覽器臭蟲之間的關聯性可以代表未來也會繼續擁有如此的關聯。針對舊瀏覽器,如果您用做臨時方案的臭蟲在目前的瀏覽器已經不存在,那針對舊瀏覽器套用方案沒有問題;只針對舊瀏覽器下,一旦瀏覽器修正了 X 臭蟲,您可以肯定所有具有臭蟲 X 的瀏覽器都有臭蟲 Y,因此使用臭蟲 X 的存在來針對臭蟲 Y 的問題做解套。

+

跟之前 UA 偵測中的建議一樣,「目前的版本」意指您所能測試到的最新版本。

+

避免依賴新潮的非標準功能

+

就算加了前綴,使用新潮的功能依舊還是很危險:隨著規格的發展,瀏覽器前綴的實作也會遵循最新的規範而改變。一旦功能被標準化,含前綴的版本有可能會被刪除。

+

瀏覽器開發者提供前綴與非標準功能給您是為了實驗和意見回饋,而非讓您將這些酷玩意散佈出去。如果您選擇使用它們,請準備經常更新您的網站以趕上變化。

+

當使用未普遍實作(即使是標準)的新潮功能時,記得測試備援方案

+

要檢查在未實作所用功能的瀏覽器下瀏覽網頁會發生什麼事,尤其是您在工作時不會經常使用的瀏覽器。

+

除非針對過去有問題的版本,不要使用廠商前綴(Vender-prefix)功能

+

廠商前綴的功能可以在將來的版本中改變。然而,一旦瀏覽器已提供不帶前綴的功能,您可以在確保不帶前綴版在可用時總會被套用下,使用前綴版本針對舊版本。一個很好的例子,假設-vnd 廠商已經將不帶前綴的 make-it-pretty 屬性實作加入新出品的瀏覽器,包含一個前綴版與不含前綴版作用不同的值「sometimes」:

+
<style>
+  .pretty-element {
+    -vnd-make-it-pretty: sometimes;
+    make-it-pretty: sometimes;
+  }
+</style>
+
+

上述規則中,聲明的順序非常重要:無前綴者一定要排在最後。

+

在沒有瀏覽器支援前,不要使用不含前綴的 CSS 屬性或 API

+

除非不帶前綴的版本得到了廣泛支持,其行為可能仍會發生意想不到的改變。特別是,當沒有瀏覽器支援不帶前綴的版本時,就不要使用不帶前綴的版本。最終的語法不盡然會和任何帶前綴的語法相同。

+

程式碼維護

+

別忘了 >

+

透過驗證器可以確保這個問題不會發生,但即使你的網站沒有完全驗證,你仍應確保你所有的 > 字元都有出現。少了它可能會讓接下來的 Tag 名稱被當成上一個 Tag 所屬的屬性,而造成意想不到的結果。可能一小段沒問題,但接下來因為某段文字代表一個屬性而完全被破壞。舉例來說,以下是一段在不支援 HTML5 瀏覽器下可正常運作,但卻讓支援 HTML5 的瀏覽器無法正常運作的網頁程式碼:

+
<form action="http://www.example.com">
+  <input type="submit" value="傳送此表單"
+</form>
+
+

因為在 input Tag 的最後忘了加上 >

+

別把失敗的實驗品留在您的網頁程式碼裡

+

如果您想嘗試一個 CSS 屬性或其他的酷東西,但沒有效果,請記得拿掉。不然您無法預知這東西未來會做什麼壞事。

diff --git a/files/zh-tw/web/html/applying_color/index.html b/files/zh-tw/web/html/applying_color/index.html new file mode 100644 index 0000000000..4e9aa26498 --- /dev/null +++ b/files/zh-tw/web/html/applying_color/index.html @@ -0,0 +1,502 @@ +--- +title: Applying color to HTML elements using CSS +slug: Web/HTML/Applying_color +translation_of: Web/HTML/Applying_color +--- +
{{HTMLRef}}
+ +

The use of color is a fundamental form of human expression. Children experiment with color before they even have the manual dexterity to draw. Maybe that's why color is one of the first things people often want to experiment with when learning to develop web sites. With CSS, there are lots of ways to add color to your HTML elements to create just the look you want. This article is a primer introducing each of the ways CSS color can be used in HTML.

+ +

Fortunately, adding color to your HTML is actually really easy to do, and you can add color to nearly anything.

+ +

We're going to touch on most of what you'll need to know when using color, including a {{anch("Things that can have color", "list of what you can color and what CSS properties are involved")}}, {{anch("How to describe a color", "how you describe colors")}}, and how to actually {{anch("Using color", "use colors both in stylesheets and in scripts")}}. We'll also take a look at how to {{anch("Letting the user picka color", "let the user pick a color")}}.

+ +

Then we'll wrap things up with a brief discussion of how to {{anch("Using color wisely", "use color wisely")}}: how to select appropriate colors, keeping in mind the needs of people with differing visual capabilities.

+ +

Things that can have color

+ +

At the element level, everything in HTML can have color applied to it. Instead, let's look at things in terms of the kinds of things that are drawn in the elements, such as text and borders and so forth. For each, we'll see a list of the CSS properties that apply color to them.

+ +

At a fundamental level, the {{cssxref("color")}} property defines the foreground color of an HTML element's content and the {{cssxref("background-color")}} property defines the element's background color. These can be used on just about any element.

+ +

Text

+ +

Whenever an element is rendered, these properties are used to determine the color of the text, its background, and any decorations on the text.

+ +
+
{{cssxref("color")}}
+
The color to use when drawing the text and any text decorations (such as the addition of under- or overlines, strike-through lines, and so forth.
+
{{cssxref("background-color")}}
+
The text's background color.
+
{{cssxref("text-shadow")}}
+
Configures a shadow effect to apply to text. Among the options for the shadow is the shadow's base color (which is then blurred and blended with the background based on the other parameters). See {{SectionOnPage("/en-US/docs/Learn/CSS/Styling_text/Fundamentals", "Text drop shadows")}} to learn more.
+
{{cssxref("text-decoration-color")}}
+
By default, text decorations (such as underlines, strikethroughs, etc) use the color property as their colors. However, you can override that behavior and use a different color for them with the text-decoration-color property.
+
{{cssxref("text-emphasis-color")}}
+
The color to use when drawing emphasis symbols adjacent to each character in the text. This is used primarily when drawing text for East Asian languages.
+
{{cssxref("caret-color")}}
+
The color to use when drawing the {{Glossary("caret")}} (sometimes referred to as the text input cursor) within the element. This is only useful in elements that are editable, such as {{HTMLElement("input")}} and {{HTMLElement("textarea")}} or elements whose HTML {{htmlattrxref("contenteditable")}} attribute is set.
+
+ +

Boxes

+ +

Every element is a box with some sort of content, and has a background and a border in addition to whatever contents the box may have.

+ +
+
{{anch("Borders")}}
+
See the section {{anch("Borders")}} for a list of the CSS properties you can use to set the colors of a box's borders.
+
{{cssxref("background-color")}}
+
The background color to use in areas of the element that have no foreground content.
+
{{cssxref("column-rule-color")}}
+
The color to use when drawing the line separating columns of text.
+
{{cssxref("outline-color")}}
+
The color to use when drawing an outline around the outside of the element. This outline is different from the border in that it doesn't get space set aside for it in the document (so it may overlap other content). It's generally used as a focus indicator, to show which element will receive input events.
+
+ +

Borders

+ +

Any element can have a border drawn around it. A basic element border is a line drawn around the edges of the element's content. See {{SectionOnPage("/en-US/docs/Learn/CSS/Introduction_to_CSS/Box_model", "Box properties")}} to learn about the relationship between elements and their borders, and the article Styling borders using CSS to learn more about applying styles to borders.

+ +

You can use the {{cssxref("border")}} shorthand property, which lets you configure everything about the border in one shot (including non-color features of borders, such as its width, style (solid, dashed, etc.), and so forth.

+ +
+
{{cssxref("border-color")}}
+
Specifies a single color to use for every side of the element's border.
+
{{cssxref("border-left-color")}}, {{cssxref("border-right-color")}}, {{cssxref("border-top-color")}}, and {{cssxref("border-bottom-color")}}
+
Lets you set the color of the corresponding side of the element's border.
+
{{cssxref("border-block-start-color")}} and {{cssxref("border-block-end-color")}}
+
With these, you can set the color used to draw the borders which are closest to the start and end of the block the border surrounds. In a left-to-right writing mode (such as the way English is written), the block start border is the top edge and the block end is the bottom. This differs from the inline start and end, which are the left and right edges (corresponding to where each line of text in the box begins and ends).
+
{{cssxref("border-inline-start-color")}} and {{cssxref("border-inline-end-color")}}
+
These let you color the edges of the border closest to to the beginning and the end of the start of lines of text within the box. Which side this is will vary depending on the {{cssxref("writing-mode")}}, {{cssxref("direction")}}, and {{cssxref("text-orientation")}} properties, which are typically (but not always) used to adjust text directionality based on the language being displayed. For example, if the box's text is being rendered right-to-left, then the border-inline-start-color is applied to the right side of the border.
+
+ +

Other ways to use color

+ +

CSS isn't the only web technology that supports color. There are graphics technologies that are available on the web which also support color.

+ +
+
The HTML Canvas API
+
Lets you draw 2D bitmapped graphics in a {{HTMLElement("canvas")}} element. See our Canvas tutorial to learn more.
+
SVG (Scalable Vector Graphics)
+
Lets you draw images using commands that draw specific shapes, patterns, and lines to produce an image. SVG commands are formatted as XML, and can be embedded directly into a web page or can be placed in he page using the {{HTMLElement("img")}} element, just like any other type of image.
+
WebGL
+
The Web Graphics Library is an OpenGL ES-based API for drawing high-performance 2D and 3D graphics on the Web. See Learn WebGL for 2D and 3D graphics to find out more.
+
+ +

How to describe a color

+ +

In order to represent a color in CSS, you have to find a way to translate the analog concept of "color" into a digital form that a computer can use. This is typically done by breaking down the color into components, such as how much of each of a set of primary colors to mix together, or how bright to make the color. As such, there are several ways you can describe color in CSS.

+ +

For more detailed discussion of each of the color value types, see the reference for the CSS {{cssxref("<color>")}} unit.

+ +

Keywords

+ +

A set of standard color names have been defined, letting you use these keywords instead of numeric representations of colors if you choose to do so and there's a keyword representing the exact color you want to use. Color keywords include the standard primary and secondary colors (such as red, blue, or orange), shades of gray (from black to white, including colors like darkgray and lightgrey), and a variety of other blended colors including lightseagreen, cornflowerblue, and rebeccapurple.

+ +

See {{SectionOnPage("/en-US/docs/Web/CSS/color_value", "Color keywords", "code")}} for a list of all available color keywords.

+ +

RGB values

+ +

There are three ways to represent an RGB color in CSS.

+ +

Hexadecimal string notation

+ +

Hexadecimal string notation represents a color using hexadecimal digits to represent each of the color components (red, green, and blue). It may also include a fourth component: the alpha channel (or opacity). Each color component can be represented as a number between 0 and 255 (0x00 and 0xFF) or, optionally, as a number between 0 and 15 (0x0 and 0xF). All components must be specified using the same number of digits. If you use the single-digit notation, the final color is computed by using each component's digit twice; that is, "#D" becomes "#DD" when drawing.

+ +

A color in hexadecimal string notation always begins with the character "#". After that come the hexadecimal digits of the color code. The string is case-insensitive.

+ +
+
"#rrggbb"
+
Specifies a fully-opaque color whose red component is the hexadecimal number 0xrr, green component is 0xgg, and blue component is 0xbb.
+
"#rrggbbaa"
+
Specifies a color whose red component is the hexadecimal number 0xrr, green component is 0xgg, and blue component is 0xbb. The alpha channel is specified by 0xaa; the lower this value is, the more translucent the color becomes.
+
"#rgb"
+
Specifies a color whose red component is the hexadecimal number 0xrr, green component is 0xgg, and blue component is 0xbb.
+
"#rgba"
+
Specifies a color whose red component is the hexadecimal number 0xrr, green component is 0xgg, and blue component is 0xbb. The alpha channel is specified by 0xaa; the lower this value is, the more translucent the color becomes.
+
+ +

As an example, you can represent the opaque color bright blue as "#0000ff" or "#00f". To make it 25% opaque, you can use "#0000ff44" or "#00f4".

+ +

RGB functional notation

+ +

RGB (Red/Green/Blue) functional notation, like hexadecimal string notation, represents colors using their red, green, and blue components (as well as, optionally, an alpha channel component for opacity). However, instead of using a string, the color is defined using the CSS function {{cssxref("color_value", "rgb()", "#rgb()")}}. This function accepts as its input parameters the values of the red, green, and blue components and an optional fourth parameter, the value for the alpha channel.

+ +

Legal values for each of these parameters are:

+ +
+
red, green, and blue
+
Each must be an {{cssxref("<integer>")}} value between 0 and 255 (inclusive), or a {{cssxref("<percentage>")}} from 0% to 100%.
+
alpha
+
The alpha channel is a number between 0.0 (fully transparent) and 1.0 (fully opaque). You can also specify a percentage where 0% is the same as 0.0 and 100% is the same as 1.0.
+
+ +

For example, a bright red that's 50% opaque can be represented as rgb(255, 0, 0, 0.5) or rgb(100%, 0, 0, 50%).

+ +

HSL functional notation

+ +

Designers and artists often prefer to work using the {{interwiki("wikipedia", "HSL and HSV", "HSL")}} (Hue/Saturation/Luminosity) color method. On the web, HSL colors are represented using HSL functional notation. The hsl() CSS function is very similar to the rgb() function in usage otherwise.

+ +
+
HSL color cylinder +
Figure 1. An HSL color cylinder. Hue defines the actual color based on the position along a circular color wheel representing the colors of the visible spectrum. Saturation is a percentage of how much of the way between being a shade of gray and having the maximum possible amount of the given hue. As the value of luminance (or lightness) increases, the color transitions from the darkest possible to the brightest possible (from black to white). Image courtesy of user SharkD on Wikipedia, distributed under the CC BY-SA 3.0 license.
+
+
+ +

The value of the hue (H) component of an HSL color is an angle from red around through yellow, green, cyan, blue, and magenta (ending up back at red again at 360°) that identifies what the base color is. The value can be specified in any {{cssxref("<angle>")}} unit supported by CSS, including degrees (deg), radians (rad), gradians (grad), or turns (turn). But this doesn't control how vivid or dull, or how bright or dark the color is.

+ +

The saturation (S) component of the color specifies what percentage of the final color is comprised of the specified hue. The rest is defined by the grey level provided by the luminance (L) component.

+ +

Think of it like creating the perfect paint color:

+ +
    +
  1. You start with base paint that's the maximum intensity possible for a given color, such as  the most intense blue that can be represented by the user's screen. This is the hue (H) component: a value representing the angle around the color wheel for the vivid hue we want to use as our base.
  2. +
  3. Then select a greyscale paint that corresponds how bright you want the color to be; this is the luminance. Do you want it to be very bright and nearly white, or very dark and closer to black, or somewhere in between? This is specified using a percentage, where 0% is perfectly black and 100% is perfectly white. (regardless of the saturation or hue). In between values are a literal grey area.
  4. +
  5. Now that you have a grey paint and a perfectly vivid color, you need to mix them together. The saturation (S) component of the color indicates what percentage of the final color should be comprised of that perfectly vivid color. The rest of the final color is made up of the grey paint that represents the saturation.
  6. +
+ +

You can also optionally include an alpha channel, to make the color less than 100% opaque.

+ +

Here are some sample colors in HSL notation:

+ +
+ + +

{{EmbedLiveSample("hsl-swatches", 300, 260)}}

+
+ +
+

Note that when you omit the hue's unit, it's assumed to be in degrees (deg).

+
+ +

Using color

+ +

Now that you know what CSS properties exist that let you apply color to elements and the formats you can use to describe colors, you can put this together to begin to make use of color. As you may have seen from the list under {{anch("Things that can have color")}}, there are plenty of things you can color with CSS. Let's look at this from two sides: using color within a {{Glossary("stylesheet")}}, and adding and changing color using {{Glossary("JavaScript")}} code to alter the styles of elements.

+ +

Specifying colors in stylesheets

+ +

The easiest way to apply color to elements—and the way you'll usually do it—is to simply specify colors in the CSS that's used when rendering elements. While we won't use every single property mentioned previously, we'll look at a couple of examples. The concept is the same anywhere you use color.

+ +

Let's take a look at an example, starting by looking at the results we're trying to achieve:

+ +
{{EmbedLiveSample("Specifying_colors_in_stylesheets", 650, 150)}}
+ +

HTML

+ +

The HTML responsible for creating the above example is shown here:

+ +
<div class="wrapper">
+  <div class="box boxLeft">
+    <p>
+      This is the first box.
+    </p>
+  </div>
+  <div class="box boxRight">
+    <p>
+      This is the second box.
+    </p>
+  </div>
+</div>
+ +

This is pretty simple, using a {{HTMLElement("div")}} as a wrapper around the contents, which consists of two more <div>s, each styled differently with a single paragraph ({{HTMLElement("p")}}) in each box.

+ +

The magic happens, as usual, in the CSS, where we'll apply colors define the layout for the HTML above.

+ +

CSS

+ +

We'll look at the CSS to create the above results a piece at a time, so we can review the interesting parts one by one.

+ +
.wrapper {
+  width: 620px;
+  height: 110px;
+  margin: 0;
+  padding: 10px;
+  border: 6px solid mediumturquoise;
+}
+ +

The .wrapper class is used to assign styles to the {{HTMLElement("div")}} that encloses all of our other content. This establishes thesize of the container using {{cssxref("width")}} and {{cssxref("height")}} as well as its {{cssxref("margin")}} and {{cssxref("padding")}}.

+ +

Of more interest to our discussion here is the use of the {{cssxref("border")}} property to establish a border around the outside edge of the element. This border is a solid line, 6 pixels wide, in the color mediumturquoise.

+ +

Our two colored boxes share a number of properties in common, so next we establish a class, .box, that defines those shared properties:

+ +
.box {
+  width: 290px;
+  height: 100px;
+  margin: 0;
+  padding: 4px 6px;
+  font: 28px "Marker Felt", "Zapfino", cursive;
+  display: flex;
+  justify-content: center;
+  align-items: center;
+}
+ +

In brief, .box establishes the size of each box, as well as the configuration of the font used within. We also take advantage of CSS Flexbox to easily center the contents of each box. We enable flex mode using {{cssxref("display", "display: flex")}}, and set both {{cssxref("justify-content")}} and {{cssxref("align-items")}} to center. Then we can create a class for each of the two boxes that defines the propeties that differ between the two.

+ +
.boxLeft {
+  float: left;
+  background-color: rgb(245, 130, 130);
+  outline: 2px solid darkred;
+}
+ +

The .boxLeft class—which, cleverly, is used to style the box on the left—floats the box to the left, then sets up the colors:

+ + + +
.boxRight {
+  float: right;
+  background-color: hsl(270deg, 50%, 75%);
+  outline: 4px dashed rgb(110, 20, 120);
+  color: hsl(0deg, 100%, 100%);
+  text-decoration: underline wavy #88ff88;
+  text-shadow: 2px 2px 3px black;
+}
+ +

Finally, the .boxRight class describes the unique properties of the box that's drawn on the right. It's configured to float the box to the right so that it appears next to the previous box. Then the following colors are established:

+ + + +

Letting the user pick a color

+ +

There are many situations in which your web site may need to let the user select a color. Perhaps you have a customizable user interface, or you're implementing a drawing app. Maybe you have editable text and need to let the user choose the text color. Or perhaps your app lets the user assign colors to folders or items. Although historically it's been necessary to implement your own {{interwiki("wikipedia", "color picker")}}, HTML now provides support for browsers to provide one for your use through the {{HTMLElement("input")}} element, by using "color" as the value of its {{htmlattrxref("type", "input")}} attribute.

+ +

The <input> element represents a color only in the {{anch("Hexadecimal string notation", "hexadecimal string notation")}} covered above.

+ +

Example: Picking a color

+ +

Let's look at a simple example, in which the user can choose a color. As the user adjusts the color, the border around the example changes to reflect the new color. After finishing up and picking the final color, the color picker's value is displayed.

+ +

{{EmbedLiveSample("Example_Picking_a_color", 525, 275)}}

+ +
+

On macOS, you indicate that you've finalized selection of the color by closing the color picker window.

+
+ +

HTML

+ +

The HTML here creates a box that contains a color picker control (with a label created using the {{HTMLElement("label")}} element) and an empty paragraph element ({{HTMLElement("p")}}) into which we'll output some text from our JavaScript code.

+ +
<div id="box">
+  <label for="colorPicker">Border color:</label>
+  <input type="color" value="#8888ff" id="colorPicker">
+  <p id="output"></p>
+</div>
+ +

CSS

+ +

The CSS simply establishes a size for the box and some basic styling for appearances. The border is also established with a 2-pixel width and a border color that won't last, courtesy of the JavaScript below...

+ +
#box {
+  width: 500px;
+  height: 200px;
+  border: 2px solid rgb(245, 220, 225);
+  padding: 4px 6px;
+  font: 16px "Lucida Grande", "Helvetica", "Arial", "sans-serif"
+}
+ +

JavaScript

+ +

The script here handles the task of updating the starting color of the border to match the color picker's value. Then two event handlers are added to deal with input from the <input type="color"> element.

+ +
let colorPicker = document.getElementById("colorPicker");
+let box = document.getElementById("box");
+let output = document.getElementById("output");
+
+box.style.borderColor = colorPicker.value;
+
+colorPicker.addEventListener("input", function(event) {
+  box.style.borderColor = event.target.value;
+}, false);
+
+colorPicker.addEventListener("change", function(event) {
+  output.innerText = "Color set to " + colorPicker.value + ".";
+}, false);
+ +

The {{event("input")}} event is sent every time the value of the element changes; that is, every time the user adjusts the color in the color picker. Each time this event arrives, we set the box's border color to match the color picker's current value.

+ +

The {{event("change")}} event is received when the color picker's value is finalized. We respond by setting the contents of the <p> element with the ID "output" to a string describing the finally selected color.

+ +

Using color wisely

+ +

Making the right choices when selecting colors when designing a web site can be a tricky process, especially if you aren't well-grounded in art, design, or at least basic color theory. The wrong color choice can render your site unattractive, or even worse, leave the content unreadable due to problems with contrast or conflicting colors. Worse still, if using the wrong colors can result in your content being outright unusable by people withcertain vision problems, particularly color blindness.

+ +

Finding the right colors

+ +

Coming up with just the right colors can be tricky, especially without training in art or design. Fortunately, there are tools available that can help you. While they can't replace having a good designer helping you make these decisions, they can definitely get you started.

+ +

Base color

+ +

The first step is to choose your base color. This is the color that in some way defines your web site or the subject matter of the site. Just as we associate green with the beverage {{interwiki("wikipedia", "Mountain Dew")}} and one might think of the color blue in relationship with the sky or the ocean, choosing an appropriate base color to represent your site is a good place to start. There are plenty of ways to select a base color; a few ideas include:

+ + + +

When trying to decide upon a base color, you may find that browser extensions that let you select colors from web content can be particularly handy. Some of these are even specifically designed to help with this sort of work. For example, the web site ColorZilla offers an extension (Chrome / Firefox) that offers an eyedropper tool for picking colors from the web. It can also take averages of the colors of pixels in various sized areas or even a selected area of the page.

+ +
+

The advantage to averaging colors can be that often what looks like a solid color is actually a surprisingly varied number of related colors all used in concert, blending to create a desired effect. Picking just one of these pixels can result in getting a color that on its own looks very out of place.

+
+ +

Fleshing out the palette

+ +

Once you have decided on your base color, there are plenty of online tools that can help you build out a palette of appropriate colors to use along with your base color by applying color theory to your base color to determine appropriate added colors. Many of these tools also support viewing the colors filtered so you can see what they would look like to people with various forms of color blindness. See {{anch("Color and accessibility")}} for a brief explanation of why this matters.

+ +

A few examples (all free to use as of the time this list was last revised):

+ + + +

When designing your palette, be sure to keep in mind that in addition to the colors these tools typically generate, you'll probably also need to add some core neutral colors such as white (or nearly white), black (or nearly black), and some number of shades of gray.

+ +
+

Usually, you are far better off using the smallest number of colors possible. By using color to accentuate rather than adding color to everything on the page, you keep your content easy to read and the colors you do use have far more impact.

+
+ +

Color theory resources

+ +

A full review of color theory is beyond the scope of this article, but there are plenty of articles about color theory available, as well as courses you can find at nearby schools and universities. A couple of useful resources about color theory:

+ +
+
Color Science (Khan Academy in association with Pixar)
+
An online course which introduces concepts such as what color is, how it's percieved, and how to use colors to express ideas. Presented by Pixar artists and designers.
+
{{interwiki("wikipedia", "Color theory")}} on Wikipedia
+
Wikipedia's entry on color theory, which has a lot of great information from a technical perspective. It's not really a resource for helping you with the color sleection process, but is still full of useful information.
+
+ +

Color and accessibility

+ +

There are several ways color can be an {{Glossary("accessibility")}} problem. Improper or careless use of color can result in a web site or app that a percentage of your target audience may not be able to use adequately, resulting in lost traffic, lost business, and possibly even a public relations problem. So it's important to consider your use of color carefully.

+ +

You should do at least basic research into {{interwiki("wikipedia", "color blindness")}}. There are several kinds; the most common is red-green color blindness, which causes people to be unable to differentiate between the colors red and green. There are others, too, ranging from inabilities to tell the difference between certain colors to total inability to see color at all.

+ +
+

The most important rule: never use color as the only way to know something. If, for example, you indicate success or failure of an operation by changing the color of a shape from white to green for success and red for failure, users with red-green color-blindness won't be able to use your site properly. Instead, perhaps use both text and color together, so that everyone can understand what's happening.

+
+ +

For more information about color blindness, see the following articles:

+ + + +

Palette design example

+ +

Let's consider a quick example of selecting an appropriate color palette for a site. Imagine that you're building a web site for a new game that takes place on the planet Mars. So let's do a Google search for photos of Mars. Lots of good examples of Martian coloration there. We carefully avoid the mockups and the photos from movies. And we decide to use a photo taken by one of the Mars landers humanity has parked on the surface over the last few decades, since the game takes place on the planet's surface. We use a color picker tool to select a sample of the color we choose.

+ +

Using an eyedropper tool, we identify a color we like and determine that the color in question is #D79C7A, which is an appropriate rusty orange-red color that's so stereotypical of the Martian surface.

+ +

Having selected our base color, we need to build out our palette. We decide to use Paletton to come up with the other colors we need. Upon opening Paletton, we see:

+ +

Right after loading Paletton.

+ +

Next, we enter our color's hex code (D79C7A) into the "Base RGB" box at the bottom-left corner of the tool:

+ +

After entering base color

+ +

We now see a monochromatic palette based on the color we picked from the Mars photo. If you need a lot of related colors for some reason, those are likely to be good ones. But what we really want is an accent color. Something that will pop along side the base color. To find that, we click the "add complementary" toggle underneath the menu that lets you select the palette type (currently "Monochromatic"). Paletton computes an appropriate accent color; clicking on the accent color down in the bottom-right corner tells us that this color is #508D7C.

+ +

Now with complementary colors included.

+ +

If you're unhappy with the color that's proposed to you, you can change the color scheme, to see if you find something you like better. For example, if we don't like the proposed greenish-blue color, we can click the Triad color scheme icon, which presents us with the following:

+ +

Triad color scheme selected

+ +

That greyish blue in the top-right looks pretty good. Clicking on it, we find that it's #556E8D. That would be used as the accent color, to be used sparingly to make things stand out, such as in headlines or in the highlighting of tabs or other indicators on the site:

+ +

Triad color scheme selected

+ +

Now we have our base color and our accent. On top of that, we have a few complementary shades of each, just in case we need them for gradients and the like. The colors can then be exported in a number of formats so you can make use of them.

+ +

Once you have these colors, you will probably still need to select appropriate neutral colors. Common design practice is to try to find the sweet spot where there's just enough contrast that the text is crisp and readable but not enough contrast to become harsh for the eyes. It's easy to go too far in one way or another so be sure to get feedback on your colors once you've selected them and have examples of them in use available. If the contrast is too low, your text will tend to be washed out by the background, leaving it unreadable, but if your contrast is too high, the user may find your site garish and unpleasant to look at.

+ +

Color, backgrounds, contrast, and printing

+ +

What looks good on screen may look very different on paper. In addition, ink can be expensive, and if a user is printing your page, they don't necessarily need all the backgrounds and such using up their precious ink when all that matters is the text itself. Most browsers, by default, remove background images when printing documents.

+ +

If your background colors and images have been selected carefully and/or are crucial to the usefulness of the content, you can use the CSS {{cssxref("color-adjust")}} property to tell the browser that it should not make adjustments to the appearance of content.

+ +

The default value of color-adjust, economy, indicates that the browser is allowed to make appearance changes as it deems necessary in order to try to optimize the legibility and/or print economy of the content, given the type of output device the document is being drawn onto.

+ +

You can set color-adjust to exact to tell the browser that the element or elements on which you use it have been designed specifically to best work with the colors and images left as they are. With this set, the browser won't tamper with the appearance of the element, and will draw it as indicated by your CSS.

+ +
+

Note: There is no guarantee, though, that color-adjust: exact will result in your CSS being used exactly as given. If the browser provides user preferences to change the output (such as a "don't print backgrounds" checkbox in a print dialog box), that overrides the value of color-adjust.

+
+ +

See also

+ + diff --git a/files/zh-tw/web/html/attributes/index.html b/files/zh-tw/web/html/attributes/index.html new file mode 100644 index 0000000000..834f36b4a9 --- /dev/null +++ b/files/zh-tw/web/html/attributes/index.html @@ -0,0 +1,643 @@ +--- +title: HTML attribute reference +slug: Web/HTML/Attributes +translation_of: Web/HTML/Attributes +--- +

HTML 中的元素具有屬性 ; 而這些屬性可以藉由各種方式去設定元素或調整它們的行為,以符合使用者的期待。

+ +

屬性列表

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
屬性名稱元素描述
hiddenGlobal attribute避免呈現給定的元素,並且保持子元素,例如 script elements、active。
high{{ HTMLElement("meter") }}指示下界的上限範圍。
href{{ HTMLElement("a") }}, {{ HTMLElement("area") }}, {{ HTMLElement("base") }}, {{ HTMLElement("link") }}連結資源的 URL。
hreflang{{ HTMLElement("a") }}, {{ HTMLElement("area") }}, {{ HTMLElement("link") }}指定連結資源的語言。
http-equiv{{ HTMLElement("meta") }} 
icon{{ HTMLElement("command") }}指定呈現指令的圖片。
idGlobal attribute經常和 CSS 一起被用來設計特定元素。這個屬性的值必須是唯一的。
ismap{{ HTMLElement("img") }}指示該圖像是伺服器端之影像地圖的一部分。
itempropGlobal attribute 
keytype{{ HTMLElement("keygen") }}指定所生成密鑰的類型。
kind{{ HTMLElement("track") }}指明文章 track 的類型。
label{{ HTMLElement("track") }}指明文章 track 的使用者可讀之標題。
langGlobal attribute定義該元素中所使用的語言。
language{{ HTMLElement("script") }}定義該元素中所使用的腳本語言。
list{{ HTMLElement("input") }}指示一串預先定義的選項供使用者參考。
loop{{ HTMLElement("audio") }}, {{ HTMLElement("bgsound") }}, {{ HTMLElement("marquee") }}, {{ HTMLElement("video") }}指示當媒體完成時,是否應該從一開始的時候播放。
low{{ HTMLElement("meter") }}指示上界的下限範圍。
manifest{{ HTMLElement("html") }}指定文件中緩存清單的 URL。
max{{ HTMLElement("input") }}, {{ HTMLElement("meter") }}, {{ HTMLElement("progress") }}指示所允許的最大值。
maxlength{{ HTMLElement("input") }}, {{ HTMLElement("textarea") }}定義該元素中所允許的最大字元數目。
media{{ HTMLElement("a") }}, {{ HTMLElement("area") }}, {{ HTMLElement("link") }}, {{ HTMLElement("source") }}, {{ HTMLElement("style") }}指定一些連接資源已經被設計的媒體。
method{{ HTMLElement("form") }}定義當呈交該格式時,哪個 HTTP 方法要被使用。可以用 GET(預設)或是 POST。
min{{ HTMLElement("input") }}, {{ HTMLElement("meter") }}指示所允許的最小值。
multiple{{ HTMLElement("input") }}, {{ HTMLElement("select") }}指示多個值是否可以進入單一輸入的 email 或是 file 之類別。
name{{ HTMLElement("button") }}, {{ HTMLElement("form") }}, {{ HTMLElement("fieldset") }}, {{ HTMLElement("iframe") }}, {{ HTMLElement("input") }}, {{ HTMLElement("keygen") }}, {{ HTMLElement("object") }}, {{ HTMLElement("output") }}, {{ HTMLElement("select") }}, {{ HTMLElement("textarea") }}, {{ HTMLElement("map") }}, {{ HTMLElement("meta") }}, {{ HTMLElement("param") }} +

元素的名字。例如被伺服器所使用時,來識別格式提交的現場。

+
novalidate{{ HTMLElement("form") }}該屬性指示當本格式被提交時,並無法通過驗證。
open{{ HTMLElement("details") }}指示是否細節顯示於加載頁面上。
optimum{{ HTMLElement("meter") }}指示最佳化數值。
pattern{{ HTMLElement("input") }}定義一個元素值將被驗證的正規表達式。
ping{{ HTMLElement("a") }}, {{ HTMLElement("area") }} 
placeholder{{ HTMLElement("input") }}, {{ HTMLElement("textarea") }}提示使用者什麼可以被輸入進該區。
poster{{ HTMLElement("video") }} +

顯現一個指示 poster frame 的 URL,直到使用者撥放或是搜索。

+
preload{{ HTMLElement("audio") }}, {{ HTMLElement("video") }}指示是否整個資源、一部分的資源、或是沒有資源應該被預先裝載。
pubdate{{ HTMLElement("time") }}指示該日期和時間,是否和距離最近的 {{ HTMLElement("article") }} 舊元素的日期一樣。
radiogroup{{ HTMLElement("command") }} 
readonly{{ HTMLElement("input") }}, {{ HTMLElement("textarea") }}指示是否該元素可以被編輯。
rel{{ HTMLElement("a") }}, {{ HTMLElement("area") }}, {{ HTMLElement("link") }}指定目標物件和連結物驗的關係。
required{{ HTMLElement("input") }}, {{ HTMLElement("select") }}, {{ HTMLElement("textarea") }}指示該元素是否被要求填寫。
reversed{{ HTMLElement("ol") }}指示該目錄是否應以降序展出而不是升序。
rows{{ HTMLElement("textarea") }}定義 textarea 的行數。
rowspan{{ HTMLElement("td") }}, {{ HTMLElement("th") }}定義表格單元的行數應該被 span over。
sandbox{{ HTMLElement("iframe") }} 
spellcheckGlobal attribute指示為該元素的拼字檢查是否允許。
scope{{ HTMLElement("th") }} 
scoped{{ HTMLElement("style") }} 
seamless{{ HTMLElement("iframe") }} 
selected{{ HTMLElement("option") }}定義一個值將被選擇到上載頁面中。
shape{{ HTMLElement("a") }}, {{ HTMLElement("area") }} 
size{{ HTMLElement("input") }}, {{ HTMLElement("select") }}定義元素的寬度 (以 pixel 為單位) 。如果該元素之類型的屬性是文本或是密碼,那麼它就是字元的數目。
sizes{{ HTMLElement("link") }} 
span{{ HTMLElement("col") }}, {{ HTMLElement("colgroup") }} 
src{{ HTMLElement("audio") }}, {{ HTMLElement("embed") }}, {{ HTMLElement("iframe") }}, {{ HTMLElement("img") }}, {{ HTMLElement("input") }}, {{ HTMLElement("script") }}, {{ HTMLElement("source") }}, {{ HTMLElement("track") }}, {{ HTMLElement("video") }}可嵌入內容的網址。
srcdoc{{ HTMLElement("iframe") }} 
srclang{{ HTMLElement("track") }} 
srcset{{ HTMLElement("img") }} 
start{{ HTMLElement("ol") }}如果第一個數字不是 1 的話,則定義該數。
step{{ HTMLElement("input") }} 
styleGlobal attribute定義多載先前的樣式設定之 CSS 樣式。
summary{{ HTMLElement("table") }} 
tabindexGlobal attribute多載瀏覽器的預設頁面標籤之順序並且遵守指定的那個。
target{{ HTMLElement("a") }}, {{ HTMLElement("area") }}, {{ HTMLElement("base") }}, {{ HTMLElement("form") }} 
titleGlobal attribute當滑鼠標停在元素時,文本會顯示在工具提示中。
type{{ HTMLElement("button") }}, {{ HTMLElement("input") }}, {{ HTMLElement("command") }}, {{ HTMLElement("embed") }}, {{ HTMLElement("object") }}, {{ HTMLElement("script") }}, {{ HTMLElement("source") }}, {{ HTMLElement("style") }}, {{ HTMLElement("menu") }}定義元素的類型。
usemap{{ HTMLElement("img") }},  {{ HTMLElement("input") }}, {{ HTMLElement("object") }} 
value{{ HTMLElement("button") }}, {{ HTMLElement("option") }}, {{ HTMLElement("input") }}, {{ HTMLElement("li") }}, {{ HTMLElement("meter") }}, {{ HTMLElement("progress") }}, {{ HTMLElement("param") }}定義將顯示在加載頁面上元素的預設值。
width{{ HTMLElement("canvas") }}, {{ HTMLElement("embed") }}, {{ HTMLElement("iframe") }}, {{ HTMLElement("img") }}, {{ HTMLElement("input") }}, {{ HTMLElement("object") }}, {{ HTMLElement("video") }}注意 : 在有些情況中,例如 {{ HTMLElement("div") }},這是傳統的屬性,而 CSS {{ Cssxref("width") }} 特性應當被使用。在其他的情況中,例如 {{ HTMLElement("canvas") }} ,寬度必須用該屬性來指定。
wrap{{ HTMLElement("textarea") }}指定文章是否要被掩飾。
border{{ HTMLElement("img") }}, {{ HTMLElement("object") }}, {{ HTMLElement("table") }} +

邊界寬度。

+ +

注意 : 這是一個傳統的屬性。請利用 CSS {{ Cssxref("border") }} 特性。

+
buffered{{ HTMLElement("audio") }}, {{ HTMLElement("video") }}包含被緩衝之媒體的時間範圍。
challenge{{ HTMLElement("keygen") }}隨著公共密鑰提交的挑戰字串。
charset{{ HTMLElement("meta") }}, {{ HTMLElement("script") }}聲明頁面或腳本的字元編碼。
checked{{ HTMLElement("command") }}, {{ HTMLElement("input") }}指定在加載頁面上的元素是否要被檢查。
cite{{ HTMLElement("blockquote") }}, {{ HTMLElement("del") }}, {{ HTMLElement("ins") }}, {{ HTMLElement("q") }}包含一個 URL,用來指出引用或是改變的來源地址。
classGlobal attribute經常使用共同屬性和 CSS 一起設計元素。
code{{ HTMLElement("applet") }}指明被加載與執行的 applet 類別文件之 URL。
codebase{{ HTMLElement("applet") }}This attribute gives the absolute or relative URL of the directory where applets' .class files referenced by the code attribute are stored.
color{{ HTMLElement("basefont") }}, {{ HTMLElement("font") }}, {{ HTMLElement("hr") }} +

該屬性使用命名顏色或十六進制 #RRGGBB 格式來設置文本顏色。

+ +

注意 : 這是一個傳統的屬性。請使用 CSS {{ Cssxref("color") }} 特性。

+
cols{{ HTMLElement("textarea") }}定義在一個 textarea 中有多少欄位。
colspan{{ HTMLElement("td") }}, {{ HTMLElement("th") }}colspan 屬性定義一個單元格之欄位的數量。
content{{ HTMLElement("meta") }}一個有關於 http-equiv 或是根據上下文 name 的值 。
contenteditableGlobal attribute指定元素的內容是否可以被編輯。
contextmenuGlobal attribute定義將作為元素上下文選項單的 {{ HTMLElement("menu") }} 元素之 ID。
controls{{ HTMLElement("audio") }}, {{ HTMLElement("video") }}指定瀏覽器是否應該顯示錄放控制給使用者。
coords{{ HTMLElement("area") }}一組值指明熱點區域的座標。
+

data

+
+

{{ HTMLElement("object") }}

+
+

指明 URL 的資源。

+
+

data-*

+
+

Global attribute

+
+

讓您可以將自行定義屬性附加在 HTML 元素上。

+
datetime{{ HTMLElement("del") }}, {{ HTMLElement("ins") }}, {{ HTMLElement("time") }}指定元素所相關的日期與時間。
default{{ HTMLElement("track") }}指定 track 應被啟用,除非使用者的偏好表示不同。
defer{{ HTMLElement("script") }}指定該頁面被瀏覽完後腳本應被執行。
dirGlobal attribute定義文章的方向。被允許的值有 ltr (Left-To-Right) 或 rtl (Right-To-Left)。
dirname{{ HTMLElement("input") }}, {{ HTMLElement("textarea") }} 
disabled{{ HTMLElement("button") }}, {{ HTMLElement("command") }}, {{ HTMLElement("fieldset") }}, {{ HTMLElement("input") }}, {{ HTMLElement("keygen") }}, {{ HTMLElement("optgroup") }}, {{ HTMLElement("option") }}, {{ HTMLElement("select") }}, {{ HTMLElement("textarea") }}指名使用者是否可以與元素互動。
download{{ HTMLElement("a") }}, {{ HTMLElement("area") }} +

指定該超連結是用於下載的資源。

+
draggableGlobal attribute定義元素是否可以拖曳。
dropzoneGlobal attribute指定該元素接受它內容的滑鼠落下物。
enctype{{ HTMLElement("form") }}當方法為 POST 的時候,定義格式日期的內容類型。
for{{ HTMLElement("label") }}, {{ HTMLElement("output") }}描述屬於這一個的元素。
form{{ HTMLElement("button") }}, {{ HTMLElement("fieldset") }}, {{ HTMLElement("input") }}, {{ HTMLElement("keygen") }}, {{ HTMLElement("label") }}, {{ HTMLElement("meter") }}, {{ HTMLElement("object") }}, {{ HTMLElement("output") }}, {{ HTMLElement("progress") }}, {{ HTMLElement("select") }}, {{ HTMLElement("textarea") }} +

指定元素之所有者的格式。

+
formaction{{ HTMLElement("input") }}, {{ HTMLElement("button") }}指定元素的作用,多載的動作被定義在 {{ HTMLElement("form") }}。
headers{{ HTMLElement("td") }}, {{ HTMLElement("th") }}對適用於該元素的 <th> 元素之 ID。
height{{ HTMLElement("canvas") }}, {{ HTMLElement("embed") }}, {{ HTMLElement("iframe") }}, {{ HTMLElement("img") }}, {{ HTMLElement("input") }}, {{ HTMLElement("object") }}, {{ HTMLElement("video") }}注意 : 在有些情況中,例如 {{ HTMLElement("div") }},這是傳統的屬性,而 CSS {{ Cssxref("height") }} 特性應當被使用。在其他的情況中,例如 {{ HTMLElement("canvas") }},高度必須用該屬性來指定。
accept{{ HTMLElement("form") }}, {{ HTMLElement("input") }}伺服器接受的類型之列表,通常是文件類型。
accept-charset{{ HTMLElement("form") }}支持字元集的列表。
accesskeyGlobal attribute定義鍵盤快捷鍵來啟動或添加焦點到該元素。
action{{ HTMLElement("form") }}一個程序處理經由該格式提交信息的 URI。
align{{ HTMLElement("applet") }}, {{ HTMLElement("caption") }}, {{ HTMLElement("col") }}, {{ HTMLElement("colgroup") }},  {{ HTMLElement("hr") }}, {{ HTMLElement("iframe") }}, {{ HTMLElement("img") }}, {{ HTMLElement("table") }}, {{ HTMLElement("tbody") }},  {{ HTMLElement("td") }},  {{ HTMLElement("tfoot") }} , {{ HTMLElement("th") }}, {{ HTMLElement("thead") }}, {{ HTMLElement("tr") }}指定元素的水平對齊方式。
alt +

{{ HTMLElement("applet") }}, {{ HTMLElement("area") }}, {{ HTMLElement("img") }}, {{ HTMLElement("input") }}

+
在圖像無法顯示的情況下,顯示代替文本。
async{{ HTMLElement("script") }}指定該腳本應該被不同步得執行。
autocomplete{{ HTMLElement("form") }}, {{ HTMLElement("input") }}指定是否以該格式控制,可以在默認情況下由瀏覽器自動完成其值。
autofocus{{ HTMLElement("button") }}, {{ HTMLElement("input") }}, {{ HTMLElement("keygen") }}, {{ HTMLElement("select") }}, {{ HTMLElement("textarea") }}該元素應該在頁面加載後自動焦距。
autoplay{{ HTMLElement("audio") }}, {{ HTMLElement("video") }}音頻或視頻應該越早撥放越好。
autosave{{ HTMLElement("input") }}上一個值應該持續存在到跨頁面加載的可選值之下拉列表中。
bgcolor{{ HTMLElement("body") }}, {{ HTMLElement("col") }}, {{ HTMLElement("colgroup") }}, {{ HTMLElement("marquee") }}, {{ HTMLElement("table") }}, {{ HTMLElement("tbody") }}, {{ HTMLElement("tfoot") }}, {{ HTMLElement("td") }}, {{ HTMLElement("th") }}, {{ HTMLElement("tr") }} +

元素的背景顏色。

+ +

注意 : 這是一個傳統的屬性。請使用 CSS {{ Cssxref("background-color") }} 特性。

+
+ +

內容與IDL屬性

+ +

在 HTML 中,大部分的屬性有兩種面向 : 內容屬性IDL 屬性

+ +

內容屬性是您可以從內容中設定的屬性 (HTML 程式碼) 而且您可以藉由 {{domxref("element.setAttribute()")}} 或是 {{domxref("element.getAttribute()")}} 來設定它或得到它。內容屬性永遠都是字串,即便我們所期望的值是一個整數。舉例來說,假設今天要用內容屬性去設定一個 {{HTMLElement("input")}} 元素的最大長度是42,您必須在該元素上呼叫 setAttribute("maxlength", "42")。

+ +

IDL 屬性也被稱為 JavaScript 特性。您可以使用 JavaScript 特性的 element.foo 以閱讀或是設定這些屬性。當您要得到 IDL 屬性時,它總是要使用 (但可能改變) 基本的內容屬性以返回值,而當您要設定 IDL 屬性時,它需要儲存資料在內容屬性中。換句話說,IDL 屬性在本質上反映了內容屬性。

+ +

在大部分的時間中,當 IDL 屬性真正被使用時,將會返回它們的值。舉例而言,{{HTMLElement("input")}} 元素的預設型態是 "text",所以如果您設定 input.type="foobar",<input> 元素一樣是 text 的型態 (在外觀和行為上而言),但是 "type" 內容屬性的值將會變成 "foobar"。然而,IDL 屬性的型態將會回傳 "text" 字串。

+ +

IDL 屬性並非永遠的字串 ; 舉例來說,input.maxlength 便是一個數字(型態為 signed long)。當使用 IDL 屬性,您會閱讀或是設定所需的型態,而當您設定 input.maxlength 時,它總是回傳一個數字,因為它正需要一個數字。如果您傳入別的型態,它會依照標準 JavaScript 型態轉換規則,將傳入值轉成一個數字。

+ +

IDL 屬性可以 反應其他型態,例如 unsigned long、URLs、booleans,等等。不幸的是,並沒有明確的規則來規範,而且與 IDL 屬性行為相對應的內容屬性連結中,也沒有取決於該屬性的方式。在大部分的時間裡,它會遵守 規範中所制定的規則,但有時候它並不會。HTML 規範嘗試讓它變得容易使用,但由於各種原因 (大多是因為歷史),有些屬性表現得很奇怪 (舉例來說,select.size),而您應該詳細閱讀規範以了解各個屬性的行為。

+ +

另請參見

+ + diff --git a/files/zh-tw/web/html/block-level_elements/index.html b/files/zh-tw/web/html/block-level_elements/index.html new file mode 100644 index 0000000000..32d8a405b0 --- /dev/null +++ b/files/zh-tw/web/html/block-level_elements/index.html @@ -0,0 +1,130 @@ +--- +title: 區塊級元素 +slug: Web/HTML/Block-level_elements +translation_of: Web/HTML/Block-level_elements +--- +

HTML (超文字標記語言, Hypertext Markup Language) 元素通常為 "區塊級" 元素或是 "行內" 元素。 一個區塊級元素會藉由建立"區塊"的動作, 完全佔滿其父元素(容器)的空間。本文將為您說明其意涵.

+ +

瀏覽器預設以在元素前後換行的方式, 表現區塊級元素. 視覺上會呈現為一排縱向堆疊的方塊。

+ +
+

區塊級元素必定以換行方式, 取得完整寬度的空間(向左右兩側儘可能地延伸出去)。

+
+ +

以下範例將展示區塊級元素的影響:

+ +

區塊級元素

+ +

HTML

+ +
<p>This paragraph is a block-level element; its background has been colored to display the paragraph's parent element.</p>
+ +

CSS

+ +
p { background-color: #8ABB55; }
+
+ +

{{ EmbedLiveSample('Block-level_Example') }}

+ +

用法

+ + + +

區塊級 vs. 行內元素

+ +

There are a couple of key differences between block-level elements and inline elements:

+ +
+
Formatting
+
By default, block-level elements begin on new lines, but inline elements can start anywhere in a line.
+
Content model
+
Generally, block-level elements may contain inline elements and other block-level elements. Inherent in this structural distinction is the idea that block elements create "larger" structures than inline elements.
+
+ +

The distinction of block-level vs. inline elements is used in HTML specifications up to 4.01. In HTML5, this binary distinction is replaced with a more complex set of content categories. The "block-level" category roughly corresponds to the category of flow content in HTML5, while "inline" corresponds to phrasing content, but there are additional categories.

+ +

相關元素

+ +

The following is a complete list of all HTML block level elements (although "block-level" is not technically defined for elements that are new in HTML5).

+ +
+
+
{{ HTMLElement("address") }}
+
Contact information.
+
{{ HTMLElement("article") }} {{ HTMLVersionInline(5) }}
+
Article content.
+
{{ HTMLElement("aside") }} {{ HTMLVersionInline(5) }}
+
Aside content.
+
{{ HTMLElement("blockquote") }}
+
Long ("block") quotation.
+
{{ HTMLElement("canvas") }} {{ HTMLVersionInline(5) }}
+
Drawing canvas.
+
{{ HTMLElement("dd") }}
+
Describes a term in a description list.
+
{{ HTMLElement("div") }}
+
Document division.
+
{{ HTMLElement("dl") }}
+
Description list.
+
{{ HTMLElement("dt") }}
+
Description list term.
+
{{ HTMLElement("fieldset") }}
+
Field set label.
+
+ +
+
{{ HTMLElement("figcaption") }} {{ HTMLVersionInline(5) }}
+
Figure caption.
+
{{ HTMLElement("figure") }} {{ HTMLVersionInline(5) }}
+
Groups media content with a caption (see {{ HTMLElement("figcaption") }}).
+
{{ HTMLElement("footer") }} {{ HTMLVersionInline(5) }}
+
Section or page footer.
+
{{ HTMLElement("form") }}
+
Input form.
+
{{ HTMLElement("h1") }}, {{ HTMLElement("h2") }}, {{ HTMLElement("h3") }}, {{ HTMLElement("h4") }}, {{ HTMLElement("h5") }}, {{ HTMLElement("h6") }}
+
Heading levels 1-6.
+
{{ HTMLElement("header") }} {{ HTMLVersionInline(5) }}
+
Section or page header.
+
{{ HTMLElement("hgroup") }} {{ HTMLVersionInline(5) }}
+
Groups header information.
+
{{ HTMLElement("hr") }}
+
Horizontal rule (dividing line).
+
{{ HTMLElement("li") }}
+
List item.
+
{{ HTMLElement("main") }}
+
Contains the central content unique to this document.
+
{{ HTMLElement("nav") }}
+
Contains navigation links.
+
+ +
+
{{ HTMLElement("noscript") }}
+
Content to use if scripting is not supported or turned off.
+
{{ HTMLElement("ol") }}
+
Ordered list.
+
{{ HTMLElement("output") }} {{ HTMLVersionInline(5) }}
+
Form output.
+
{{ HTMLElement("p") }}
+
Paragraph.
+
{{ HTMLElement("pre") }}
+
Preformatted text.
+
{{ HTMLElement("section") }} {{ HTMLVersionInline(5) }}
+
Section of a web page.
+
{{ HTMLElement("table") }}
+
Table.
+
{{ HTMLElement("tfoot") }}
+
Table footer.
+
{{ HTMLElement("ul") }}
+
Unordered list.
+
{{ HTMLElement("video") }} {{ HTMLVersionInline(5) }}
+
Video player.
+
+
+ +


+ 參閱

+ + diff --git a/files/zh-tw/web/html/element/a/index.html b/files/zh-tw/web/html/element/a/index.html new file mode 100644 index 0000000000..91224a9318 --- /dev/null +++ b/files/zh-tw/web/html/element/a/index.html @@ -0,0 +1,313 @@ +--- +title: +slug: Web/HTML/Element/a +translation_of: Web/HTML/Element/a +--- +

HTML <a> 元素(意為 Anchor)建立了通往其他頁面、檔案、Email 地址、或其他 URL 的超連結。

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
內容類型流型內容phrasing content, interactive content, palpable content.
內容省略Transparent, containing either flow content (excluding interactive content) or phrasing content.
標籤省略{{no_tag_omission}}
允許的父元素任何允許 phrasing contentflow content 的內容,但 <a> 永遠例外(according to the logical principle of symmetry, if <a> tag, as a parent, can not have interactive content, then the same <a> content can not have <a> tag as its parent)
Permitted ARIA roles{{ARIARole("button")}}, {{ARIARole("checkbox")}}, {{ARIARole("menuitem")}}, {{ARIARole("menuitemcheckbox")}}, {{ARIARole("menuitemradio")}}, {{ARIARole("option")}}, {{ARIARole("radio")}}, {{ARIARole("switch")}}, {{ARIARole("tab")}}, {{ARIARole("treeitem")}}
DOM 介面{{domxref("HTMLAnchorElement")}}
+ +

屬性

+ +

本元素包含全域屬性

+ +
+
{{htmlattrdef("download")}} {{HTMLVersionInline(5)}}
+
This attribute instructs browsers to download a URL instead of navigating to it, so the user will be prompted to save it as a local file. If the attribute has a value, it is used as the pre-filled file name in the Save prompt (the user can still change the file name if they want). There are no restrictions on allowed values, though / and \ are converted to underscores. Most file systems limit some punctuation in file names, and browsers will adjust the suggested name accordingly. +
Notes: +
    +
  • This attribute only works for same-origin URLs.
  • +
  • This attribute can be used with blob: URLs and data: URLs to download content generated by JavaScript, such as pictures created in an image-editor Web app.
  • +
  • If the HTTP header Content-Disposition: gives a different filename than this attribute, the HTTP header takes priority over this attribute.
  • +
  • If Content-Disposition: is set to inline, Firefox prioritizes Content-Disposition, like the filename case, while Chrome prioritizes the download attribute.
  • +
+
+
+
{{htmlattrdef("href")}}
+
Contains a URL or a URL fragment that the hyperlink points to.
+
A URL fragment is a name preceded by a hash mark (#), which specifies an internal target location (an ID of an HTML element) within the current document. URLs are not restricted to Web (HTTP)-based documents, but can use any protocol supported by the browser. For example, file:, ftp:, and mailto: work in most browsers.
+
This attribute may be omitted (as of HTML5) to create a placeholder link. A placeholder link resembles a traditional hyperlink, but does not lead anywhere. +
+

Note: You can use href="#top" or the empty fragment href="#" to link to the top of the current page. This behavior is specified by HTML5.

+
+
+
{{htmlattrdef("hreflang")}}
+
This attribute indicates the human language of the linked resource. It is purely advisory, with no built-in functionality. Allowed values are determined by BCP47.
+
{{htmlattrdef("ping")}}
+
Contains a space-separated list of URLs to which, when the hyperlink is followed, {{HTTPMethod("POST")}} requests with the body PING will be sent by the browser (in the background). Typically used for tracking.
+
{{htmlattrdef("referrerpolicy")}} {{experimental_inline}}
+
Indicates which referrer to send when fetching the URL: +
    +
  • 'no-referrer' means the Referer: header will not be sent.
  • +
  • 'no-referrer-when-downgrade' means no Referer: header will be sent when navigating to an origin without HTTPS. This is the default behavior.
  • +
  • 'origin' means the referrer will be the origin of the page, not including information after the domain.
  • +
  • 'origin-when-cross-origin' meaning that navigations to other origins will be limited to the scheme, the host and the port, while navigations on the same origin will include the referrer's path.
  • +
  • 'unsafe-url' means the referrer will include the origin and path, but not the fragment, password, or username. This is unsafe because it can leak data from secure URLs to insecure ones.
  • +
+
+
{{htmlattrdef("rel")}}
+
Specifies the relationship of the target object to the link object. The value is a space-separated list of link types.
+
{{htmlattrdef("target")}}
+
Specifies where to display the linked URL. It is a name of, or keyword for, a browsing context: a tab, window, or <iframe>. The following keywords have special meanings: +
    +
  • _self: Load the URL into the same browsing context as the current one. This is the default behavior.
  • +
  • _blank: Load the URL into a new browsing context. This is usually a tab, but users can configure browsers to use new windows instead.
  • +
  • _parent: Load the URL into the parent browsing context of the current one. If there is no parent, this behaves the same way as _self.
  • +
  • _top: Load the URL into the top-level browsing context (that is, the "highest" browsing context that is an ancestor of the current one, and has no parent). If there is no parent, this behaves the same way as _self.
  • +
+ +
+

Note: When using target, consider adding rel="noopener noreferrer" to avoid exploitation of the window.opener API.

+
+
+
{{htmlattrdef("type")}}
+
Specifies the media type in the form of a {{Glossary("MIME type")}} for the linked URL. It is purely advisory, with no built-in functionality.
+
+ +

Obsolete

+ +
+
{{htmlattrdef("charset")}} {{obsoleteGeneric("inline","HTML5")}}
+
This attribute defined the character encoding of the linked URL. The value should be a space- and/or comma-delimited list of character sets defined in RFC 2045. The default value is ISO-8859-1. +
+

Usage note: This attribute is obsolete in HTML5 and should not be used by authors. To achieve its effect, use the HTTP Content-Type: header on the linked URL.

+
+
+
{{htmlattrdef("coords")}} {{HTMLVersionInline(4)}} only, {{obsoleteGeneric("inline","HTML5")}}
+
For use with the below shape attribute, this attribute used a comma-separated list of numbers to define the coordinates of the link on the page.
+
{{htmlattrdef("name")}} {{HTMLVersionInline(4)}} only, {{obsoleteGeneric("inline","HTML5")}}
+
This attribute was required for anchors defining a possible target location within a page. In HTML 4.01, id and name could be used simultaneously on a <a> element as long as they have identical values. +
+

Usage note: This attribute is obsolete in HTML5, use the global attribute id instead.

+
+
+
{{htmlattrdef("rev")}} {{HTMLVersionInline(4)}} only, {{obsoleteGeneric("inline","HTML5")}}
+
This attribute specified a reverse link, the inverse relationship of the rel attribute. It was deprecated for being very confusing.
+
{{htmlattrdef("shape")}} {{HTMLVersionInline(4)}} only, {{obsoleteGeneric("inline","HTML5")}}
+
This attribute was used to define a region for hyperlinks to create an image map. The values are circle, default, polygon, and rect. The format of the coords attribute depends on the value of shape. For circle, the value is x,y,r where x and y are the pixel coordinates for the center of the circle and r is the radius value in pixels. For rect, the coords attribute should be x,y,w,h. The x,y values define the upper-left-hand corner of the rectangle, while w and h define the width and height respectively. A value of polygon for shape requires x1,y1,x2,y2,... values for coords. Each of the x,y pairs defines a point in the polygon, with successive points being joined by straight lines and the last point joined to the first. The value default for shape requires that the entire enclosed area, typically an image, be used. +
Note: Use the usemap attribute for the {{HTMLElement("img")}} element and the associated {{HTMLElement("map")}} element to define hotspots instead of the shape attribute.
+
+
+ +

Examples

+ +

Linking to an external location

+ +
<!-- anchor linking to external file -->
+<a href="https://www.mozilla.com/">
+External Link
+</a>
+
+ +

Result

+ +

External Link

+ +

Linking to another section on the same page

+ +
<!-- links to element on this page with id="attr-href" -->
+<a href="#attr-href">
+Description of Same-Page Links
+</a>
+
+ +

Result

+ +

Description of Same Page Links

+ +

Creating a clickable image

+ +

This example uses an image to link to the MDN home page. The home page will open in a new browsing context, that is, a new page or a new tab.

+ +
<a href="https://developer.mozilla.org/en-US/" target="_blank">
+  <img src="https://mdn.mozillademos.org/files/6851/mdn_logo.png"
+       alt="MDN logo" />
+</a>
+
+ +

Result

+ +
+

{{EmbedLiveSample("Creating_a_clickable_image", "320", "64")}}

+
+ + + +

It's common to create links that open in the user's email program to allow them to send a new message. This is done with a mailto: link. Here's a simple example:

+ +
<a href="mailto:nowhere@mozilla.org">Send email to nowhere</a>
+ +

Result

+ +

Send email to nowhere

+ +

For additional details about the mailto URL scheme, such as including the subject, body, or other predetermined content, see Email links or {{RFC(6068)}}.

+ + + +

Offering phone links is helpful for users viewing web documents and laptops connected to phones.

+ +
<a href="tel:+491570156">+49 157 0156</a>
+ +

For additional details about the tel URL scheme, see {{RFC(3966)}}.

+ +

Using the download attribute to save a <canvas> as a PNG

+ +

If you want to let users download an HTML {{HTMLElement("canvas")}} element as an image, you can create a link with a download attribute and the canvas data as a file URL:

+ +
var link = document.createElement('a');
+link.textContent = 'download image';
+
+link.addEventListener('click', function(ev) {
+    link.href = canvas.toDataURL();
+    link.download = "mypainting.png";
+}, false);
+
+document.body.appendChild(link);
+ +

You can see this in action at jsfiddle.net/codepo8/V6ufG/2/.

+ +

Notes

+ +

HTML 3.2 defines only the name, href, rel, rev, and title attributes.

+ +

Accessibility recommendations

+ +

Anchor tags are often abused with the onclick event to create pseudo-buttons by setting href to "#" or "javascript:void(0)" to prevent the page from refreshing. These values cause unexpected behavior when copying/dragging links, opening links in a new tabs/windows, bookmarking, and when JavaScript is still downloading, errors out, or is disabled. This also conveys incorrect semantics to assistive technologies (e.g., screen readers). In these cases, it is recommended to use a {{HTMLElement("button")}} instead. In general you should only use an anchor for navigation using a proper URL.

+ +

Clicking and focus

+ +

Whether clicking on an {{HTMLElement("a")}} causes it to become focused varies by browser and OS.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Does clicking on an {{HTMLElement("a")}} give it focus?
Desktop BrowsersWindows 8.1OS X 10.9
Firefox 30.0YesYes
Chrome ≥39
+ (Chromium bug 388666)
YesYes
Safari 7.0.5N/AOnly when it has a tabindex
Internet Explorer 11YesN/A
Presto (Opera 12)YesYes
+ + + + + + + + + + + + + + + + + + + + +
Does tapping on an {{HTMLElement("a")}} give it focus?
Mobile BrowsersiOS 7.1.2Android 4.4.4
Safari MobileOnly when it has a tabindexN/A
Chrome 35???Only when it has a tabindex
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Referrer Policy', '#referrer-policy-delivery-referrer-attribute', 'referrer attribute')}}{{Spec2('Referrer Policy')}}Added the referrer attribute.
{{SpecName('HTML WHATWG', 'semantics.html#the-a-element', '<a>')}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5 W3C', 'text-level-semantics.html#the-a-element', '<a>')}}{{Spec2('HTML5 W3C')}}
{{SpecName('HTML4.01', 'struct/links.html#h-12.2', '<a>')}}{{Spec2('HTML4.01')}}
+ +

Browser compatibility

+ + + +

{{Compat("html.elements.a")}}

+ +

See also

+ + + +
{{HTMLRef}}
diff --git a/files/zh-tw/web/html/element/blink/index.html b/files/zh-tw/web/html/element/blink/index.html new file mode 100644 index 0000000000..9913548a5c --- /dev/null +++ b/files/zh-tw/web/html/element/blink/index.html @@ -0,0 +1,75 @@ +--- +title: :文字閃爍元素(已過時) +slug: Web/HTML/Element/blink +translation_of: Web/HTML/Element/blink +--- +
{{Deprecated_header}} {{obsolete_header}}
+ +

非標準元素 HTML Blink<blink>)可以讓該元素裡面的文字緩慢閃爍。

+ +
不要使用這個元素,因為它已經被棄用,而且是糟糕的設計。無障礙標準不會接受閃爍文字、而 CSS 規範上允許瀏覽器忽略閃爍效果。
+ +

DOM 介面

+ +

此元素並未被支援,因此是透過 {{domxref("HTMLUnknownElement")}} 介面實做。

+ +

示例

+ +
<blink>Why would somebody use this?</blink>
+
+ +

結果(已經過淡化!)

+ +

Image:HTMLBlinkElement.gif

+ +

規範

+ +

此元素並非標準元素,也不屬於任何規範。不信的話,你自己來看 HTML 規範

+ +

CSS Polyfill

+ +

如果真的需要 polyfill,請使用以下的 CSS。它支援 IE10 以上。

+ +
blink {
+    -webkit-animation: 2s linear infinite condemned_blink_effect; // for android
+    animation: 2s linear infinite condemned_blink_effect;
+}
+@-webkit-keyframes condemned_blink_effect { // for android
+    0% {
+        visibility: hidden;
+    }
+    50% {
+        visibility: hidden;
+    }
+    100% {
+        visibility: visible;
+    }
+}
+@keyframes condemned_blink_effect {
+    0% {
+        visibility: hidden;
+    }
+    50% {
+        visibility: hidden;
+    }
+    100% {
+        visibility: visible;
+    }
+}
+ +

瀏覽器相容性

+ + + +

{{Compat("html.elements.blink")}}

+ +

參見

+ + + +

{{HTMLRef}}

diff --git a/files/zh-tw/web/html/element/blockquote/index.html b/files/zh-tw/web/html/element/blockquote/index.html new file mode 100644 index 0000000000..6b0fe2650f --- /dev/null +++ b/files/zh-tw/web/html/element/blockquote/index.html @@ -0,0 +1,149 @@ +--- +title:
+slug: Web/HTML/Element/blockquote +translation_of: Web/HTML/Element/blockquote +--- +

摘要

+ +

HTML <blockquote> 元素HTML 區塊引言元素)定義一段文字屬於引用。通常,這元素會透過縮排來呈現(要知道如何改變,請參考備註)。引言的 URL 來源可透過 cite 屬性賦予,而來源的文本形式可以使用 {{HTMLElement("cite")}} 元素。

+ + + + + + + + + + + + + + + + + + + + + + + + +
內容類別流內容、sectioning root、捫及內容。
允許內容內容流.
Tag 省略{{no_tag_omission}}
允許父元素任何允許內容流的元素
DOM 介面{{domxref("HTMLQuoteElement")}}
+ +

屬性

+ +

這個屬性包含全局屬性

+ +
+
{{htmlattrdef("cite")}}
+
一個指向被引用的原始文件或訊息的 URL 。這個屬性預期要指引到解釋內容的資訊,或是引言的援引。
+
+ +

範例

+ +
<blockquote cite="http://developer.mozilla.org">
+  <p>這是取自於 Mozilla Developer Center 的引言。</p>
+</blockquote>
+
+ +

以上的 HTML 原始碼會輸出:

+ +
+

這是取自於 Mozilla Developer Center 的引言。

+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
規範狀態註解
{{SpecName('HTML WHATWG', 'semantics.html#the-blockquote-element', '<blockquote>')}}{{Spec2('HTML WHATWG')}} 
{{SpecName('HTML5 W3C', 'grouping-content.html#the-blockquote-element', '<blockquote>')}}{{Spec2('HTML5 W3C')}} 
{{SpecName('HTML4.01', 'struct/text.html#h-9.2.2', '<blockquote>')}}{{Spec2('HTML4.01')}} 
+ +

瀏覽器相容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
特徵ChromeFirefox (Gecko)Internet ExplorerOperaSafari
基本支援{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
特徵AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
基本支援{{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

備註

+ +

要改變<blockquote>的縮進,請使用 CSS 的 {{cssxref("margin")}} 屬性。

+ +

針對短篇引文請使用 {{HTMLElement("q")}} 元素。

+ +

延伸閱讀

+ +
    +
  • {{HTMLElement("q")}} 元素:用以表示單行的引用內容。
  • +
  • {{HTMLElement("cite")}} 元素:用以表示引用來源。
  • +
+ +

{{HTMLRef}}

diff --git a/files/zh-tw/web/html/element/br/index.html b/files/zh-tw/web/html/element/br/index.html new file mode 100644 index 0000000000..2542c0182e --- /dev/null +++ b/files/zh-tw/web/html/element/br/index.html @@ -0,0 +1,130 @@ +--- +title:
(斷行元素) +slug: Web/HTML/Element/br +translation_of: Web/HTML/Element/br +--- +
{{HTMLRef}}
+ +

HTML <br> 元素會產生文字的斷行(carriage-return、CR 或是確認鍵)。此元素主要用於斷行有所意義的時候,像是寫詩或寫住址。

+ +
{{EmbedInteractiveExample("pages/tabbed/br.html", "tabbed-standard")}}
+ + + +

如上所示,<br> 元素會在需要斷行的時候出現。在 <br> 之後的文字會從文字區域的下一行出現。

+ +
+

注意:不要用 <br> 建立段落間距:這種情況下要用 {{htmlelement("p")}} 把它們包起來,並使用 CSS {{cssxref('margin')}} 屬性控制間距大小。

+
+ +

屬性

+ +

這個元件屬性含有全域屬性

+ +

棄用屬性

+ +
+
{{htmlattrdef("clear")}}
+
指示中斷後下一行的開始位置。
+
+ +

使用 CSS 樣式化

+ +

<br> 元素有一個定義明確的用途:在文字區塊裡面建立斷行。因此它本身沒有尺寸或視覺輸出,基本上你做不了任何樣式化。

+ +

你可以給 <br> 元素設置 {{cssxref("margin")}} 以增加文字之間的斷行大小,但這並不是正確的作法:你應該用 {{cssxref("line-height")}} 屬性做這件事情。

+ +

示例

+ +
Mozilla Foundation<br>
+1981 Landings Drive<br>
+Building K<br>
+Mountain View, CA 94043-0801<br>
+USA
+
+ +

以上 HTML 將顯示

+ +

{{ EmbedLiveSample('示例', '100%', '90') }}

+ +

無障礙議題

+ +

使用 <br> 元素分段不只作法不佳,對於使用輔具的人來說,也會是有問題的。螢幕閱讀器會念出該元素,但 <br> 裡面的內容是念不出來的。對於使用螢幕閱讀器的人來說,這可能是困惑與沮喪的體驗。

+ +

請使用 <p> 元素搭配 CSS 屬性如 {{cssxref("margin")}} 來控制間距大小。

+ +

技術摘要

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
內容類型流型內容段落型內容
允許內容無,這是個{{Glossary("空元素")}}.
標籤省略絕對要有開啟標籤,也絕不能關閉標籤。在 XHTML 文件內,要把這個元素寫成 <br />.
允許父元素任何接受段落型內容的元素
允許的 ARIA roles所有
DOM 介面{{domxref("HTMLBRElement")}}
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
規範狀態註解
{{SpecName('HTML WHATWG', 'semantics.html#the-br-element', '<br>')}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5 W3C', 'textlevel-semantics.html#the-br-element', '<br>')}}{{Spec2('HTML5 W3C')}}
{{SpecName('HTML4.01', 'struct/text.html#h-9.3.2.1', '<br>')}}{{Spec2('HTML4.01')}}
+ +

瀏覽器相容性

+ + + +

{{Compat("html.elements.br")}}

+ +

參見

+ +
    +
  • {{HTMLElement("address")}} 元素
  • +
  • {{HTMLElement("p")}} 元素
  • +
  • {{HTMLElement("wbr")}} 元素
  • +
+ +
{{HTMLRef}}
diff --git a/files/zh-tw/web/html/element/button/index.html b/files/zh-tw/web/html/element/button/index.html new file mode 100644 index 0000000000..a78352ca0f --- /dev/null +++ b/files/zh-tw/web/html/element/button/index.html @@ -0,0 +1,355 @@ +--- +title: